blob: 3f0de3b7c778a8da46ef7e3152cca1f57229a9f3 [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
154namespace art {
155
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800156using android::base::StringPrintf;
157
Orion Hodson5880c772020-07-28 20:12:08 +0100158static constexpr bool kCheckImageObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700159static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700160
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161static void ThrowNoClassDefFoundError(const char* fmt, ...)
162 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700163 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700164static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700165 va_list args;
166 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800167 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000168 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800169 va_end(args);
170}
171
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100172static ObjPtr<mirror::Object> GetErroneousStateError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700173 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700174 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
175 if (ext == nullptr) {
176 return nullptr;
177 } else {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100178 return ext->GetErroneousStateError();
Alex Lightd6251582016-10-31 11:12:30 -0700179 }
180}
181
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100182static bool IsVerifyError(ObjPtr<mirror::Object> obj)
Alex Lightd6251582016-10-31 11:12:30 -0700183 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100184 // This is slow, but we only use it for rethrowing an error, and for DCHECK.
185 return obj->GetClass()->DescriptorEquals("Ljava/lang/VerifyError;");
186}
187
188// Helper for ThrowEarlierClassFailure. Throws the stored error.
189static void HandleEarlierErroneousStateError(Thread* self,
190 ClassLinker* class_linker,
191 ObjPtr<mirror::Class> c)
192 REQUIRES_SHARED(Locks::mutator_lock_) {
193 ObjPtr<mirror::Object> obj = GetErroneousStateError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800194 DCHECK(obj != nullptr);
195 self->AssertNoPendingException();
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100196 DCHECK(!obj->IsClass());
197 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
198 ObjPtr<mirror::Class> error_class = obj->GetClass();
199 CHECK(throwable_class->IsAssignableFrom(error_class));
200 self->SetException(obj->AsThrowable());
Andreas Gampe99babb62015-11-02 16:20:00 -0800201 self->AssertPendingException();
202}
203
Nicolas Geoffray66934ef2021-07-07 14:56:23 +0100204static void UpdateClassAfterVerification(Handle<mirror::Class> klass,
205 PointerSize pointer_size,
206 verifier::FailureKind failure_kind)
Andreas Gampe5b20b352018-10-11 19:03:20 -0700207 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000208 Runtime* runtime = Runtime::Current();
209 ClassLinker* class_linker = runtime->GetClassLinker();
Nicolas Geoffray2990b882021-11-30 15:48:49 +0000210 if (klass->IsVerified() && (failure_kind == verifier::FailureKind::kNoFailure)) {
Andreas Gampe5b20b352018-10-11 19:03:20 -0700211 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +0100212 }
213
214 // Now that the class has passed verification, try to set nterp entrypoints
215 // to methods that currently use the switch interpreter.
216 if (interpreter::CanRuntimeUseNterp()) {
217 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +0000218 if (class_linker->IsQuickToInterpreterBridge(m.GetEntryPointFromQuickCompiledCode())) {
219 runtime->GetInstrumentation()->InitializeMethodsCode(&m, /*aot_code=*/nullptr);
220 }
Nicolas Geoffray00391822019-12-10 10:17:23 +0000221 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700222 }
223}
224
Vladimir Markobf121912019-06-04 13:49:05 +0100225// Callback responsible for making a batch of classes visibly initialized
226// after all threads have called it from a checkpoint, ensuring visibility.
227class ClassLinker::VisiblyInitializedCallback final
228 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
229 public:
230 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
231 : class_linker_(class_linker),
232 num_classes_(0u),
233 thread_visibility_counter_(0),
234 barriers_() {
235 std::fill_n(classes_, kMaxClasses, nullptr);
236 }
237
238 bool IsEmpty() const {
239 DCHECK_LE(num_classes_, kMaxClasses);
240 return num_classes_ == 0u;
241 }
242
243 bool IsFull() const {
244 DCHECK_LE(num_classes_, kMaxClasses);
245 return num_classes_ == kMaxClasses;
246 }
247
248 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
249 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
250 DCHECK(!IsFull());
251 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
252 ++num_classes_;
253 }
254
255 void AddBarrier(Barrier* barrier) {
256 barriers_.push_front(barrier);
257 }
258
259 std::forward_list<Barrier*> GetAndClearBarriers() {
260 std::forward_list<Barrier*> result;
261 result.swap(barriers_);
262 result.reverse(); // Return barriers in insertion order.
263 return result;
264 }
265
266 void MakeVisible(Thread* self) {
267 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
268 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
269 AdjustThreadVisibilityCounter(self, count);
270 }
271
272 void Run(Thread* self) override {
273 self->ClearMakeVisiblyInitializedCounter();
274 AdjustThreadVisibilityCounter(self, -1);
275 }
276
277 private:
278 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
279 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
280 if (old + adjustment == 0) {
281 // All threads passed the checkpoint. Mark classes as visibly initialized.
282 {
283 ScopedObjectAccess soa(self);
284 StackHandleScope<1u> hs(self);
285 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
286 JavaVMExt* vm = self->GetJniEnv()->GetVm();
287 for (size_t i = 0, num = num_classes_; i != num; ++i) {
288 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
289 vm->DeleteWeakGlobalRef(self, classes_[i]);
290 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100291 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100292 class_linker_->FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100293 }
294 }
295 num_classes_ = 0u;
296 }
297 class_linker_->VisiblyInitializedCallbackDone(self, this);
298 }
299 }
300
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100301 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100302
303 ClassLinker* const class_linker_;
304 size_t num_classes_;
305 jweak classes_[kMaxClasses];
306
307 // The thread visibility counter starts at 0 and it is incremented by the number of
308 // threads that need to run this callback (by the thread that request the callback
309 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
310 // whether after the increment or after a decrement, we know that `Run()` was executed
311 // for all threads and therefore we can mark the classes as visibly initialized.
312 std::atomic<ssize_t> thread_visibility_counter_;
313
314 // List of barries to `Pass()` for threads that wait for the callback to complete.
315 std::forward_list<Barrier*> barriers_;
316};
317
318void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
319 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
320 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
321 }
322 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
323 if (wait) {
324 maybe_barrier.emplace(0);
325 }
326 int wait_count = 0;
327 VisiblyInitializedCallback* callback = nullptr;
328 {
329 MutexLock lock(self, visibly_initialized_callback_lock_);
330 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
331 callback = visibly_initialized_callback_.release();
332 running_visibly_initialized_callbacks_.push_front(*callback);
333 }
334 if (wait) {
335 DCHECK(maybe_barrier.has_value());
336 Barrier* barrier = std::addressof(*maybe_barrier);
337 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
338 cb.AddBarrier(barrier);
339 ++wait_count;
340 }
341 }
342 }
343 if (callback != nullptr) {
344 callback->MakeVisible(self);
345 }
346 if (wait_count != 0) {
347 DCHECK(maybe_barrier.has_value());
348 maybe_barrier->Increment(self, wait_count);
349 }
350}
351
352void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
353 VisiblyInitializedCallback* callback) {
354 MutexLock lock(self, visibly_initialized_callback_lock_);
355 // Pass the barriers if requested.
356 for (Barrier* barrier : callback->GetAndClearBarriers()) {
357 barrier->Pass(self);
358 }
359 // Remove the callback from the list of running callbacks.
360 auto before = running_visibly_initialized_callbacks_.before_begin();
361 auto it = running_visibly_initialized_callbacks_.begin();
362 DCHECK(it != running_visibly_initialized_callbacks_.end());
363 while (std::addressof(*it) != callback) {
364 before = it;
365 ++it;
366 DCHECK(it != running_visibly_initialized_callbacks_.end());
367 }
368 running_visibly_initialized_callbacks_.erase_after(before);
369 // Reuse or destroy the callback object.
370 if (visibly_initialized_callback_ == nullptr) {
371 visibly_initialized_callback_.reset(callback);
372 } else {
373 delete callback;
374 }
375}
376
Alex Lightfb119572019-09-18 15:04:53 -0700377void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
378 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
379 if (cb != nullptr) {
380 cb->MakeVisible(self);
381 }
382 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
383 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
384}
385
Vladimir Markobf121912019-06-04 13:49:05 +0100386ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
387 Thread* self, Handle<mirror::Class> klass) {
388 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
389 // Thanks to the x86 memory model, we do not need any memory fences and
390 // we can immediately mark the class as visibly initialized.
391 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100392 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100393 return nullptr;
394 }
395 if (Runtime::Current()->IsActiveTransaction()) {
396 // Transactions are single-threaded, so we can mark the class as visibly intialized.
397 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
398 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100399 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100400 return nullptr;
401 }
402 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
403 MutexLock lock(self, visibly_initialized_callback_lock_);
404 if (visibly_initialized_callback_ == nullptr) {
405 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
406 }
407 DCHECK(!visibly_initialized_callback_->IsFull());
408 visibly_initialized_callback_->AddClass(self, klass.Get());
409
410 if (visibly_initialized_callback_->IsFull()) {
411 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
412 running_visibly_initialized_callbacks_.push_front(*callback);
413 return callback;
414 } else {
415 return nullptr;
416 }
417}
418
Vladimir Marko86c87522020-05-11 16:55:55 +0100419const void* ClassLinker::RegisterNative(
420 Thread* self, ArtMethod* method, const void* native_method) {
421 CHECK(method->IsNative()) << method->PrettyMethod();
422 CHECK(native_method != nullptr) << method->PrettyMethod();
423 void* new_native_method = nullptr;
424 Runtime* runtime = Runtime::Current();
425 runtime->GetRuntimeCallbacks()->RegisterNativeMethod(method,
426 native_method,
427 /*out*/&new_native_method);
428 if (method->IsCriticalNative()) {
429 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
430 // Remove old registered method if any.
431 auto it = critical_native_code_with_clinit_check_.find(method);
432 if (it != critical_native_code_with_clinit_check_.end()) {
433 critical_native_code_with_clinit_check_.erase(it);
434 }
435 // To ensure correct memory visibility, we need the class to be visibly
436 // initialized before we can set the JNI entrypoint.
437 if (method->GetDeclaringClass()->IsVisiblyInitialized()) {
438 method->SetEntryPointFromJni(new_native_method);
439 } else {
440 critical_native_code_with_clinit_check_.emplace(method, new_native_method);
441 }
442 } else {
443 method->SetEntryPointFromJni(new_native_method);
444 }
445 return new_native_method;
446}
447
448void ClassLinker::UnregisterNative(Thread* self, ArtMethod* method) {
449 CHECK(method->IsNative()) << method->PrettyMethod();
450 // Restore stub to lookup native pointer via dlsym.
451 if (method->IsCriticalNative()) {
452 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
453 auto it = critical_native_code_with_clinit_check_.find(method);
454 if (it != critical_native_code_with_clinit_check_.end()) {
455 critical_native_code_with_clinit_check_.erase(it);
456 }
457 method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
458 } else {
459 method->SetEntryPointFromJni(GetJniDlsymLookupStub());
460 }
461}
462
463const void* ClassLinker::GetRegisteredNative(Thread* self, ArtMethod* method) {
464 if (method->IsCriticalNative()) {
465 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
466 auto it = critical_native_code_with_clinit_check_.find(method);
467 if (it != critical_native_code_with_clinit_check_.end()) {
468 return it->second;
469 }
470 const void* native_code = method->GetEntryPointFromJni();
471 return IsJniDlsymLookupCriticalStub(native_code) ? nullptr : native_code;
472 } else {
473 const void* native_code = method->GetEntryPointFromJni();
474 return IsJniDlsymLookupStub(native_code) ? nullptr : native_code;
475 }
476}
477
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800478void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
479 bool wrap_in_no_class_def,
480 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700481 // The class failed to initialize on a previous attempt, so we want to throw
482 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
483 // failed in verification, in which case v2 5.4.1 says we need to re-throw
484 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800485 Runtime* const runtime = Runtime::Current();
486 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700487 std::string extra;
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100488 ObjPtr<mirror::Object> verify_error = GetErroneousStateError(c);
Vladimir Markobb206de2019-03-28 10:30:32 +0000489 if (verify_error != nullptr) {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100490 DCHECK(!verify_error->IsClass());
491 extra = verify_error->AsThrowable()->Dump();
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700492 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800493 if (log) {
494 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
495 << ": " << extra;
496 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700497 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700498
David Sehr709b0702016-10-13 09:12:37 -0700499 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800500 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800501 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700502 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700503 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000504 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700505 } else {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100506 ObjPtr<mirror::Object> erroneous_state_error = GetErroneousStateError(c);
507 if (erroneous_state_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800508 // Rethrow stored error.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100509 HandleEarlierErroneousStateError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800510 }
Alex Lightd6251582016-10-31 11:12:30 -0700511 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
512 // might have meant to go down the earlier if statement with the original error but it got
513 // swallowed by the OOM so we end up here.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100514 if (erroneous_state_error == nullptr ||
515 (wrap_in_no_class_def && !IsVerifyError(erroneous_state_error))) {
Andreas Gampecb086952015-11-02 16:20:00 -0800516 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
517 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
518 // exception will be a cause.
519 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700520 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700521 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700522 }
523}
524
Brian Carlstromb23eab12014-10-08 17:55:21 -0700525static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700526 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700527 if (VLOG_IS_ON(class_linker)) {
528 std::string temp;
529 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000530 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700531 }
532}
533
534static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700535 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700536 Thread* self = Thread::Current();
537 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700538
539 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700540 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700541
David Srbecky346fd962020-07-27 16:51:00 +0100542 // Boot classpath classes should not fail initialization. This is a consistency debug check.
543 // This cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800544 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800545 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800546 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
547 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
548 // could have caused the error.
549 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
550 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
551 << " failed initialization: "
552 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800553 }
554
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700555 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700556 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
557 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700558
Elliott Hughesa4f94742012-05-29 16:28:38 -0700559 // We only wrap non-Error exceptions; an Error can just be used as-is.
560 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000561 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700562 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700563 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700564}
565
Andreas Gampe87658f32019-04-18 18:39:02 +0000566ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700567 : boot_class_table_(new ClassTable()),
568 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800569 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800570 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700571 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000572 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700573 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000574 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000575 jni_dlsym_lookup_trampoline_(nullptr),
Vladimir Markofa458ac2020-02-12 14:08:07 +0000576 jni_dlsym_lookup_critical_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800577 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800578 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100579 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800580 quick_to_interpreter_bridge_trampoline_(nullptr),
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000581 nterp_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700582 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100583 visibly_initialized_callback_lock_("visibly initialized callback lock"),
584 visibly_initialized_callback_(nullptr),
Vladimir Marko86c87522020-05-11 16:55:55 +0100585 critical_native_code_with_clinit_check_lock_("critical native code with clinit check lock"),
586 critical_native_code_with_clinit_check_(),
Andreas Gampe7dface32017-07-25 21:32:59 -0700587 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
588 // For CHA disabled during Aot, see b/34193647.
589
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700590 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700591 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
592 "Array cache size wrong.");
593 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700594}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700595
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800596void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700597 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800598 if (c2 == nullptr) {
599 LOG(FATAL) << "Could not find class " << descriptor;
600 UNREACHABLE();
601 }
602 if (c1.Get() != c2) {
603 std::ostringstream os1, os2;
604 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
605 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
606 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
607 << ". This is most likely the result of a broken build. Make sure that "
608 << "libcore and art projects match.\n\n"
609 << os1.str() << "\n\n" << os2.str();
610 UNREACHABLE();
611 }
612}
613
Vladimir Marko78f62d82022-01-10 16:25:19 +0000614ObjPtr<mirror::IfTable> AllocIfTable(Thread* self,
615 size_t ifcount,
616 ObjPtr<mirror::Class> iftable_class)
617 REQUIRES_SHARED(Locks::mutator_lock_) {
618 DCHECK(iftable_class->IsArrayClass());
619 DCHECK(iftable_class->GetComponentType()->IsObjectClass());
620 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
621 mirror::IfTable::Alloc(self, iftable_class, ifcount * mirror::IfTable::kMax)));
622}
623
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800624bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
625 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800626 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700627
Mathieu Chartiere401d142015-04-22 13:56:20 -0700628 Thread* const self = Thread::Current();
629 Runtime* const runtime = Runtime::Current();
630 gc::Heap* const heap = runtime->GetHeap();
631
Jeff Haodcdc85b2015-12-04 14:06:18 -0800632 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700633 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700634
Mathieu Chartiere401d142015-04-22 13:56:20 -0700635 // Use the pointer size from the runtime since we are probably creating the image.
636 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
637
Elliott Hughes30646832011-10-13 16:59:46 -0700638 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700639 // 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 -0800640 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700641 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700642 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700643 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
644 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000645 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100646 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800647 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100648 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700649 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700650 if (kUseBakerReadBarrier) {
651 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800652 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700653 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700654 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800655 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700656 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700657
Elliott Hughes418d20f2011-09-22 14:00:39 -0700658 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700659 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700660 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700661 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700662 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700663
Ian Rogers23435d02012-09-24 11:23:12 -0700664 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700665 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700666 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800667 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700668 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700669 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000670 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700671
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700672 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800673 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
674 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100675 runtime->SetSentinel(heap->AllocNonMovableObject(self,
676 java_lang_Object.Get(),
677 java_lang_Object->GetObjectSize(),
678 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700679
Igor Murashkin86083f72017-10-27 10:59:04 -0700680 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000681 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700682 // It might seem the lock here is unnecessary, however all the SubtypeCheck
683 // functions are annotated to require locks all the way down.
684 //
685 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
686 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000687 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
688 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700689 }
690
Ian Rogers23435d02012-09-24 11:23:12 -0700691 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700692 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700693 AllocClass(self, java_lang_Class.Get(),
694 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700695 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700696
Roland Levillain0e840272018-08-23 19:55:30 +0100697 // Setup java.lang.String.
698 //
699 // We make this class non-movable for the unlikely case where it were to be
700 // moved by a sticky-bit (minor) collection when using the Generational
701 // Concurrent Copying (CC) collector, potentially creating a stale reference
702 // in the `klass_` field of one of its instances allocated in the Large-Object
703 // Space (LOS) -- see the comment about the dirty card scanning logic in
704 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700705 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700706 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100707 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700708 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000709 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400710
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700711 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700712 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700713 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700714 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000715 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700716
Ian Rogers23435d02012-09-24 11:23:12 -0700717 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700718 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100719 mirror::ObjectArray<mirror::Class>::Alloc(self,
720 object_array_class.Get(),
721 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700722 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100723 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
724 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
725 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
726 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100727 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
728 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700729
Mathieu Chartier6beced42016-11-15 15:51:31 -0800730 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
Vladimir Marko78f62d82022-01-10 16:25:19 +0000731 java_lang_Object->SetIfTable(AllocIfTable(self, 0, object_array_class.Get()));
Mathieu Chartier6beced42016-11-15 15:51:31 -0800732
Vladimir Marko02610552018-06-04 14:38:00 +0100733 // Create array interface entries to populate once we can load system classes.
Vladimir Marko78f62d82022-01-10 16:25:19 +0000734 object_array_class->SetIfTable(AllocIfTable(self, 2, object_array_class.Get()));
Vladimir Marko02610552018-06-04 14:38:00 +0100735 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
736
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700737 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100738 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
739 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
740 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
741 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
742 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
743 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
744 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
745 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
746 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700747
Vladimir Marko70e2a762019-07-12 16:49:00 +0100748 // Allocate the primitive array classes. We need only the native pointer
749 // array at this point (int[] or long[], depending on architecture) but
750 // we shall perform the same setup steps for all primitive array classes.
751 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
752 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
753 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
754 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
755 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
756 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
757 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
758 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700759
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700760 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700761
Ian Rogers52813c92012-10-11 11:50:38 -0700762 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700763 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700764 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100765 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100766 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700767 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000768 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700769
Alex Lightd6251582016-10-31 11:12:30 -0700770
771 // Setup dalvik.system.ClassExt
772 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
773 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100774 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000775 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700776
Mathieu Chartier66f19252012-09-18 08:57:04 -0700777 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700778 Handle<mirror::Class> object_array_string(hs.NewHandle(
779 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700780 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700781 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100782 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700783
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000784 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700785 // Create runtime resolution and imt conflict methods.
786 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000787 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
788 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700789
Ian Rogers23435d02012-09-24 11:23:12 -0700790 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
791 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
792 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800793 if (boot_class_path.empty()) {
794 *error_msg = "Boot classpath is empty.";
795 return false;
796 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800797 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800798 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800799 *error_msg = "Null dex file.";
800 return false;
801 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800802 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800803 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700804 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700805
806 // now we can use FindSystemClass
807
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700808 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
809 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700810 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800811 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700812 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000813 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Vladimir Markofa458ac2020-02-12 14:08:07 +0000814 jni_dlsym_lookup_critical_trampoline_ = GetJniDlsymLookupCriticalStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700815 quick_resolution_trampoline_ = GetQuickResolutionStub();
816 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000817 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700818 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000819 nterp_trampoline_ = interpreter::GetNterpEntryPoint();
Alex Light64ad14d2014-08-19 14:23:13 -0700820 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700821
Alex Lightd6251582016-10-31 11:12:30 -0700822 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000823 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800824 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700825 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000826 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800827 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000828 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800829 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700830 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000831 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700832 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
833 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700834
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800835 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
836 // in class_table_.
837 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700838
Vladimir Marko70e2a762019-07-12 16:49:00 +0100839 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
840 // arrays - can't be done until Object has a vtable and component classes are loaded.
841 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
842 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
843 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
844 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
845 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
846 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
847 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
848 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
849 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
850 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
851 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700852
Ian Rogers23435d02012-09-24 11:23:12 -0700853 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700854 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800855 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700856 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800857 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700858 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
859 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100860 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
861 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700862
Vladimir Markob10668c2021-06-10 09:52:53 +0100863 // Check Class[] and Object[]'s interfaces.
864 CHECK_EQ(java_lang_Cloneable.Get(), class_array_class->GetDirectInterface(0));
865 CHECK_EQ(java_io_Serializable.Get(), class_array_class->GetDirectInterface(1));
866 CHECK_EQ(java_lang_Cloneable.Get(), object_array_class->GetDirectInterface(0));
867 CHECK_EQ(java_io_Serializable.Get(), object_array_class->GetDirectInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700868
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700869 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100870 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700871
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800872 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700873
Ian Rogers23435d02012-09-24 11:23:12 -0700874 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100875 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
876 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700877
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700878 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100879 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700880 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100881 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700882
883 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700884 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
885 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100886 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700887
888 // Create java.lang.reflect.Constructor.class root and array root.
889 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
890 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100891 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700892 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
893 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100894 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700895
896 // Create java.lang.reflect.Method.class root and array root.
897 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
898 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100899 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700900 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
901 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100902 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700903
Orion Hodson005ac512017-10-24 15:43:43 +0100904 // Create java.lang.invoke.CallSite.class root
905 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
906 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100907 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100908
Narayan Kamathafa48272016-08-03 12:46:58 +0100909 // Create java.lang.invoke.MethodType.class root
910 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
911 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100912 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100913
914 // Create java.lang.invoke.MethodHandleImpl.class root
915 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
916 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100917 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100918 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100919
Orion Hodsonc069a302017-01-18 09:23:12 +0000920 // Create java.lang.invoke.MethodHandles.Lookup.class root
921 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
922 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100923 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000924
Orion Hodson005ac512017-10-24 15:43:43 +0100925 // Create java.lang.invoke.VarHandle.class root
926 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000927 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100928 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100929
930 // Create java.lang.invoke.FieldVarHandle.class root
931 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
932 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100933 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100934
Orion Hodsondd411962021-06-25 08:55:22 +0100935 // Create java.lang.invoke.StaticFieldVarHandle.class root
936 class_root = FindSystemClass(self, "Ljava/lang/invoke/StaticFieldVarHandle;");
937 CHECK(class_root != nullptr);
938 SetClassRoot(ClassRoot::kJavaLangInvokeStaticFieldVarHandle, class_root);
939
Orion Hodson005ac512017-10-24 15:43:43 +0100940 // Create java.lang.invoke.ArrayElementVarHandle.class root
941 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
942 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100943 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100944
945 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
946 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
947 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100948 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100949
950 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
951 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
952 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100953 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000954
Narayan Kamath000e1882016-10-24 17:14:25 +0100955 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
956 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100957 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100958
Brian Carlstrom1f870082011-08-23 16:02:11 -0700959 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700960 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000961 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800962 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700963 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700964 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
965 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700966 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700967 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700968 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700969 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700970 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700971 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700972 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700973 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700974 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700975 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700976 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700977 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700978
Ian Rogers23435d02012-09-24 11:23:12 -0700979 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700980 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700981 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700982 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100983 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700984
jeffhao8cd6dda2012-02-22 10:15:34 -0800985 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700986 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100987 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100988 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700989 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100990 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
991 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
992 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700993 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000994 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
995 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700996
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700997 // Create conflict tables that depend on the class linker.
998 runtime->FixupConflictTables();
999
Ian Rogers98379392014-02-24 16:53:16 -08001000 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001001
Brian Carlstroma004aa92012-02-08 18:05:09 -08001002 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001003
1004 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001005}
1006
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001007static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1008 REQUIRES_SHARED(Locks::mutator_lock_) {
1009 // Find String.<init> -> StringFactory bindings.
1010 ObjPtr<mirror::Class> string_factory_class =
1011 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1012 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001013 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001014 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1015 // Update the primordial thread.
1016 self->InitStringEntryPoints();
1017}
1018
Ian Rogers98379392014-02-24 16:53:16 -08001019void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001020 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001021
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001022 CreateStringInitBindings(self, this);
1023
Brian Carlstrom16192862011-09-12 17:50:06 -07001024 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001025 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001026 // as the types of the field can't be resolved prior to the runtime being
1027 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001028 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001029 Handle<mirror::Class> java_lang_ref_Reference =
1030 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001031 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1032 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001033
Mathieu Chartierc7853442015-03-27 14:35:38 -07001034 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001035 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1036 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001037
Mathieu Chartierc7853442015-03-27 14:35:38 -07001038 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001039 CHECK_STREQ(queue->GetName(), "queue");
1040 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001041
Mathieu Chartierc7853442015-03-27 14:35:38 -07001042 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001043 CHECK_STREQ(queueNext->GetName(), "queueNext");
1044 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001045
Mathieu Chartierc7853442015-03-27 14:35:38 -07001046 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001047 CHECK_STREQ(referent->GetName(), "referent");
1048 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001049
Mathieu Chartierc7853442015-03-27 14:35:38 -07001050 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001051 CHECK_STREQ(zombie->GetName(), "zombie");
1052 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001053
Brian Carlstroma663ea52011-08-19 23:33:41 -07001054 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001055 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001056 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001057 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001058 CHECK(klass != nullptr);
1059 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001060 // note SetClassRoot does additional validation.
1061 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001062 }
1063
Vladimir Marko02610552018-06-04 14:38:00 +01001064 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001065
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001066 // disable the slow paths in FindClass and CreatePrimitiveClass now
1067 // that Object, Class, and Object[] are setup
1068 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001069
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001070 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1071 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1072 // ensure that the class will be initialized.
1073 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001074 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001075
1076 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1077 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1078 // Strange, but don't crash.
1079 LOG(WARNING) << "Could not prepare StackOverflowError.";
1080 self->ClearException();
1081 }
1082 }
1083
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001084 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001085}
1086
Vladimir Markodcfcce42018-06-27 10:00:28 +00001087void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001088 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1089 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001090 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001091 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001092 Handle<mirror::Class> h_class(hs.NewHandle(c));
David Srbecky08110ef2020-05-20 19:33:43 +01001093 if (!EnsureInitialized(self, h_class, true, true)) {
1094 LOG(FATAL) << "Exception when initializing " << h_class->PrettyClass()
1095 << ": " << self->GetException()->Dump();
1096 }
Vladimir Markodcfcce42018-06-27 10:00:28 +00001097 } else {
1098 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001099 }
1100 }
1101}
1102
Vladimir Marko8670e042021-12-21 17:55:48 +00001103ALWAYS_INLINE
1104static uint32_t ComputeMethodHash(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1105 DCHECK(!method->IsRuntimeMethod());
1106 DCHECK(!method->IsProxyMethod());
1107 DCHECK(!method->IsObsolete());
1108 // Do not use `ArtMethod::GetNameView()` to avoid unnecessary runtime/proxy/obsolete method
1109 // checks. It is safe to avoid the read barrier here, see `ArtMethod::GetDexFile()`.
1110 const DexFile& dex_file = method->GetDeclaringClass<kWithoutReadBarrier>()->GetDexFile();
1111 const dex::MethodId& method_id = dex_file.GetMethodId(method->GetDexMethodIndex());
1112 std::string_view name = dex_file.GetMethodNameView(method_id);
1113 return ComputeModifiedUtf8Hash(name);
1114}
1115
Vladimir Markobed84ef2022-01-21 13:57:14 +00001116ALWAYS_INLINE
1117static bool MethodSignatureEquals(ArtMethod* lhs, ArtMethod* rhs)
1118 REQUIRES_SHARED(Locks::mutator_lock_) {
1119 DCHECK(!lhs->IsRuntimeMethod());
1120 DCHECK(!lhs->IsProxyMethod());
1121 DCHECK(!lhs->IsObsolete());
1122 DCHECK(!rhs->IsRuntimeMethod());
1123 DCHECK(!rhs->IsProxyMethod());
1124 DCHECK(!rhs->IsObsolete());
1125 // Do not use `ArtMethod::GetDexFile()` to avoid unnecessary obsolete method checks.
1126 // It is safe to avoid the read barrier here, see `ArtMethod::GetDexFile()`.
1127 const DexFile& lhs_dex_file = lhs->GetDeclaringClass<kWithoutReadBarrier>()->GetDexFile();
1128 const DexFile& rhs_dex_file = rhs->GetDeclaringClass<kWithoutReadBarrier>()->GetDexFile();
1129 const dex::MethodId& lhs_mid = lhs_dex_file.GetMethodId(lhs->GetDexMethodIndex());
1130 const dex::MethodId& rhs_mid = rhs_dex_file.GetMethodId(rhs->GetDexMethodIndex());
1131 if (&lhs_dex_file == &rhs_dex_file) {
1132 return lhs_mid.name_idx_ == rhs_mid.name_idx_ &&
1133 lhs_mid.proto_idx_ == rhs_mid.proto_idx_;
1134 } else {
1135 return
1136 lhs_dex_file.GetMethodNameView(lhs_mid) == rhs_dex_file.GetMethodNameView(rhs_mid) &&
1137 lhs_dex_file.GetMethodSignature(lhs_mid) == rhs_dex_file.GetMethodSignature(rhs_mid);
1138 }
1139}
1140
Vladimir Marko43354742021-02-03 15:37:01 +00001141static void InitializeObjectVirtualMethodHashes(ObjPtr<mirror::Class> java_lang_Object,
1142 PointerSize pointer_size,
1143 /*out*/ ArrayRef<uint32_t> virtual_method_hashes)
1144 REQUIRES_SHARED(Locks::mutator_lock_) {
1145 ArraySlice<ArtMethod> virtual_methods = java_lang_Object->GetVirtualMethods(pointer_size);
1146 DCHECK_EQ(virtual_method_hashes.size(), virtual_methods.size());
1147 for (size_t i = 0; i != virtual_method_hashes.size(); ++i) {
Vladimir Marko8670e042021-12-21 17:55:48 +00001148 virtual_method_hashes[i] = ComputeMethodHash(&virtual_methods[i]);
Vladimir Marko43354742021-02-03 15:37:01 +00001149 }
1150}
1151
Jeff Haodcdc85b2015-12-04 14:06:18 -08001152struct TrampolineCheckData {
1153 const void* quick_resolution_trampoline;
1154 const void* quick_imt_conflict_trampoline;
1155 const void* quick_generic_jni_trampoline;
1156 const void* quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001157 const void* nterp_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001158 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001159 ArtMethod* m;
1160 bool error;
1161};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001162
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001163bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1164 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001165 CHECK(!init_done_);
1166
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001167 Runtime* const runtime = Runtime::Current();
1168 Thread* const self = Thread::Current();
1169 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001170 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1171 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001172 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1173 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001174 if (!ValidPointerSize(pointer_size_unchecked)) {
1175 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001176 return false;
1177 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001178 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001179 if (!runtime->IsAotCompiler()) {
1180 // Only the Aot compiler supports having an image with a different pointer size than the
1181 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1182 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001183 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001184 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001185 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001186 sizeof(void*));
1187 return false;
1188 }
1189 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001190 DCHECK(!runtime->HasResolutionMethod());
1191 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1192 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1193 runtime->SetImtUnimplementedMethod(
1194 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1195 runtime->SetCalleeSaveMethod(
1196 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1197 CalleeSaveType::kSaveAllCalleeSaves);
1198 runtime->SetCalleeSaveMethod(
1199 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1200 CalleeSaveType::kSaveRefsOnly);
1201 runtime->SetCalleeSaveMethod(
1202 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1203 CalleeSaveType::kSaveRefsAndArgs);
1204 runtime->SetCalleeSaveMethod(
1205 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1206 CalleeSaveType::kSaveEverything);
1207 runtime->SetCalleeSaveMethod(
1208 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1209 CalleeSaveType::kSaveEverythingForClinit);
1210 runtime->SetCalleeSaveMethod(
1211 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1212 CalleeSaveType::kSaveEverythingForSuspendCheck);
1213
Jeff Haodcdc85b2015-12-04 14:06:18 -08001214 std::vector<const OatFile*> oat_files =
1215 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1216 DCHECK(!oat_files.empty());
1217 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001218 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001219 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001220 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1221 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1222 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1223 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001224 nterp_trampoline_ = default_oat_header.GetNterpTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001225 if (kIsDebugBuild) {
1226 // Check that the other images use the same trampoline.
1227 for (size_t i = 1; i < oat_files.size(); ++i) {
1228 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001229 const void* ith_jni_dlsym_lookup_trampoline_ =
1230 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001231 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1232 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001233 const void* ith_quick_resolution_trampoline =
1234 ith_oat_header.GetQuickResolutionTrampoline();
1235 const void* ith_quick_imt_conflict_trampoline =
1236 ith_oat_header.GetQuickImtConflictTrampoline();
1237 const void* ith_quick_generic_jni_trampoline =
1238 ith_oat_header.GetQuickGenericJniTrampoline();
1239 const void* ith_quick_to_interpreter_bridge_trampoline =
1240 ith_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001241 const void* ith_nterp_trampoline =
1242 ith_oat_header.GetNterpTrampoline();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001243 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001244 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001245 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001246 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1247 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001248 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_ ||
1249 ith_nterp_trampoline != nterp_trampoline_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001250 // Make sure that all methods in this image do not contain those trampolines as
1251 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1252 TrampolineCheckData data;
1253 data.error = false;
1254 data.pointer_size = GetImagePointerSize();
1255 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1256 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1257 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1258 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001259 data.nterp_trampoline = ith_nterp_trampoline;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001260 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001261 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1262 if (obj->IsClass()) {
1263 ObjPtr<mirror::Class> klass = obj->AsClass();
1264 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1265 const void* entrypoint =
1266 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1267 if (entrypoint == data.quick_resolution_trampoline ||
1268 entrypoint == data.quick_imt_conflict_trampoline ||
1269 entrypoint == data.quick_generic_jni_trampoline ||
1270 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1271 data.m = &m;
1272 data.error = true;
1273 return;
1274 }
1275 }
1276 }
1277 };
1278 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001279 if (data.error) {
1280 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001281 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001282 *error_msg = "Found an ArtMethod with a bad entrypoint";
1283 return false;
1284 }
1285 }
1286 }
1287 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001288
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001289 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001290 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001291 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001292 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001293
Vladimir Marko024d69f2019-06-13 10:52:32 +01001294 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1295 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1296 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1297 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1298 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1299 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001300
Vladimir Markod1908512018-11-22 14:57:28 +00001301 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001302 // Boot class loader, use a null handle.
1303 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001304 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001305 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001306 /*out*/&dex_files,
1307 error_msg)) {
1308 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001309 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001310 // Append opened dex files at the end.
1311 boot_dex_files_.insert(boot_dex_files_.end(),
1312 std::make_move_iterator(dex_files.begin()),
1313 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001314 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001315 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
Jared Duke95bb9952021-08-11 15:07:25 -07001316 OatDexFile::MadviseDexFileAtLoad(*dex_file);
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001317 }
Vladimir Marko43354742021-02-03 15:37:01 +00001318 InitializeObjectVirtualMethodHashes(GetClassRoot<mirror::Object>(this),
1319 image_pointer_size_,
1320 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Ian Rogers98379392014-02-24 16:53:16 -08001321 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001322
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001323 VLOG(startup) << __FUNCTION__ << " exiting";
1324 return true;
1325}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001326
Vladimir Marko4433c432018-12-04 14:57:47 +00001327void ClassLinker::AddExtraBootDexFiles(
1328 Thread* self,
1329 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1330 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001331 AppendToBootClassPath(self, dex_file.get());
Orion Hodson771708f2021-01-06 15:45:16 +00001332 if (kIsDebugBuild) {
1333 for (const auto& boot_dex_file : boot_dex_files_) {
1334 DCHECK_NE(boot_dex_file->GetLocation(), dex_file->GetLocation());
1335 }
1336 }
Vladimir Marko4433c432018-12-04 14:57:47 +00001337 boot_dex_files_.push_back(std::move(dex_file));
1338 }
1339}
1340
Jeff Hao5872d7c2016-04-27 11:07:41 -07001341bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001342 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001343 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001344 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1345 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001346}
1347
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001348class CHAOnDeleteUpdateClassVisitor {
1349 public:
1350 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1351 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1352 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1353 self_(Thread::Current()) {}
1354
1355 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1356 // This class is going to be unloaded. Tell CHA about it.
1357 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1358 return true;
1359 }
1360 private:
1361 const LinearAlloc* allocator_;
1362 const ClassHierarchyAnalysis* cha_;
1363 const PointerSize pointer_size_;
1364 const Thread* self_;
1365};
1366
Chris Wailes0c61be42018-09-26 17:27:34 -07001367/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001368 * A class used to ensure that all references to strings interned in an AppImage have been
1369 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001370 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001371class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001372 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001373 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1374 const InternTable::UnorderedSet& image_interns)
1375 : space_(space),
1376 image_interns_(image_interns),
1377 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001378
Chris Wailes0c61be42018-09-26 17:27:34 -07001379 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001380 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001381 if (referred_obj != nullptr &&
1382 space_.HasAddress(referred_obj.Ptr()) &&
1383 referred_obj->IsString()) {
1384 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001385 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1386 if (it != image_interns_.end() && it->Read() == referred_str) {
1387 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001388 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001389 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001390 }
1391
Chris Wailes0c61be42018-09-26 17:27:34 -07001392 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001393 mirror::CompressedReference<mirror::Object>* root) const
1394 REQUIRES_SHARED(Locks::mutator_lock_) {
1395 if (!root->IsNull()) {
1396 VisitRoot(root);
1397 }
1398 }
1399
Chris Wailes0c61be42018-09-26 17:27:34 -07001400 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001401 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001402 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001403 }
1404
1405 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001406 void operator()(ObjPtr<mirror::Object> obj,
1407 MemberOffset offset,
1408 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001409 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001410 // References within image or across images don't need a read barrier.
1411 ObjPtr<mirror::Object> referred_obj =
1412 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1413 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001414 }
1415
1416 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1417 ObjPtr<mirror::Reference> ref) const
1418 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001419 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001420 }
1421
Vladimir Marko8e05f092019-06-10 11:10:38 +01001422 size_t GetCount() const {
1423 return count_;
1424 }
1425
1426 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001427 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001428 const InternTable::UnorderedSet& image_interns_;
1429 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001430};
1431
Chris Wailes0c61be42018-09-26 17:27:34 -07001432/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001433 * This function counts references to strings interned in the AppImage.
1434 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001435 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001436size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1437 const InternTable::UnorderedSet& image_interns)
1438 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001439 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1440 const ImageHeader& image_header = space.GetImageHeader();
1441 const uint8_t* target_base = space.GetMemMap()->Begin();
1442 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001443
1444 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1445 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001446
Vladimir Marko8e05f092019-06-10 11:10:38 +01001447 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001448 bitmap->VisitMarkedRange(objects_begin,
1449 objects_end,
1450 [&space, &visitor](mirror::Object* obj)
1451 REQUIRES_SHARED(Locks::mutator_lock_) {
1452 if (space.HasAddress(obj)) {
1453 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001454 obj->VisitReferences</* kVisitNativeRoots= */ true,
1455 kVerifyNone,
1456 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001457 } else {
1458 // Don't visit native roots for non-dex-cache as they can't contain
1459 // native references to strings. This is verified during compilation
1460 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001461 obj->VisitReferences</* kVisitNativeRoots= */ false,
1462 kVerifyNone,
1463 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001464 }
1465 }
1466 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001467 return visitor.GetCount();
1468}
1469
1470template <typename Visitor>
1471static void VisitInternedStringReferences(
1472 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001473 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1474 const uint8_t* target_base = space->Begin();
1475 const ImageSection& sro_section =
1476 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1477 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1478
1479 VLOG(image)
1480 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1481 << num_string_offsets;
1482
1483 const auto* sro_base =
1484 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1485
1486 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1487 uint32_t base_offset = sro_base[offset_index].first;
1488
David Srbecky86d6cd52020-12-02 18:13:10 +00001489 uint32_t raw_member_offset = sro_base[offset_index].second;
1490 DCHECK_ALIGNED(base_offset, 2);
1491 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001492
David Srbecky86d6cd52020-12-02 18:13:10 +00001493 ObjPtr<mirror::Object> obj_ptr =
1494 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1495 MemberOffset member_offset(raw_member_offset);
1496 ObjPtr<mirror::String> referred_string =
1497 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001498 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001499 kWithoutReadBarrier,
1500 /* kIsVolatile= */ false>(member_offset);
1501 DCHECK(referred_string != nullptr);
1502
1503 ObjPtr<mirror::String> visited = visitor(referred_string);
1504 if (visited != referred_string) {
1505 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1506 /* kCheckTransaction= */ false,
1507 kVerifyNone,
1508 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001509 }
1510 }
1511}
1512
1513static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1514 REQUIRES_SHARED(Locks::mutator_lock_) {
1515 InternTable::UnorderedSet image_interns;
1516 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1517 if (section.Size() > 0) {
1518 size_t read_count;
1519 const uint8_t* data = space->Begin() + section.Offset();
1520 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1521 image_set.swap(image_interns);
1522 }
1523 size_t num_recorded_refs = 0u;
1524 VisitInternedStringReferences(
1525 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001526 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1527 REQUIRES_SHARED(Locks::mutator_lock_) {
1528 auto it = image_interns.find(GcRoot<mirror::String>(str));
1529 CHECK(it != image_interns.end());
1530 CHECK(it->Read() == str);
1531 ++num_recorded_refs;
1532 return str;
1533 });
1534 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1535 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001536}
1537
Andreas Gampe2af99022017-04-25 08:32:59 -07001538// new_class_set is the set of classes that were read from the class table section in the image.
1539// If there was no class table section, it is null.
1540// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001541class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001542 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001543 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001544 ClassLinker* class_linker,
1545 gc::space::ImageSpace* space,
1546 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001547 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001548 REQUIRES(!Locks::dex_lock_)
1549 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001550
Chris Wailesfbeef462018-10-19 14:16:35 -07001551 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001552 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001553};
1554
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001555void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001556 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001557 gc::space::ImageSpace* space,
1558 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001559 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001560 REQUIRES(!Locks::dex_lock_)
1561 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001562 ScopedTrace app_image_timing("AppImage:Updating");
1563
Vladimir Marko8e05f092019-06-10 11:10:38 +01001564 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1565 // In debug build, verify the string references before applying
1566 // the Runtime::LoadAppImageStartupCache() option.
1567 VerifyInternedStringReferences(space);
1568 }
1569
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001570 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001571 Runtime* const runtime = Runtime::Current();
1572 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001573 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001574 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001575 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001576 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001577 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001578 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001579 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001580 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001581 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001582 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001583 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001584 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001585 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001586
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001587 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001588 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001589 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001590
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001591 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001592 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001593 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001594 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1595 header.VisitPackedArtMethods([&](ArtMethod& method)
1596 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1597 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1598 if (klass != nullptr) {
1599 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1600 }
1601 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001602 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001603}
1604
Chris Wailesfbeef462018-10-19 14:16:35 -07001605void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001606 // Iterate over the string reference offsets stored in the image and intern
1607 // the strings they point to.
1608 ScopedTrace timing("AppImage:InternString");
1609
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001610 Runtime* const runtime = Runtime::Current();
1611 InternTable* const intern_table = runtime->GetInternTable();
1612
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001613 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1614 // for faster lookup.
1615 // TODO: Optimize with a bitmap or bloom filter
1616 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001617 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001618 REQUIRES_SHARED(Locks::mutator_lock_)
1619 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001620 const size_t non_boot_image_strings = intern_table->CountInterns(
1621 /*visit_boot_images=*/false,
1622 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001623 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001624 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1625 // Visit the smaller of the two sets to compute the intersection.
1626 if (interns.size() < non_boot_image_strings) {
1627 for (auto it = interns.begin(); it != interns.end(); ) {
1628 ObjPtr<mirror::String> string = it->Read();
1629 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1630 if (existing == nullptr) {
1631 existing = intern_table->LookupStrongLocked(string);
1632 }
1633 if (existing != nullptr) {
1634 intern_remap.Put(string.Ptr(), existing.Ptr());
1635 it = interns.erase(it);
1636 } else {
1637 ++it;
1638 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001639 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001640 } else {
1641 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1642 REQUIRES_SHARED(Locks::mutator_lock_)
1643 REQUIRES(Locks::intern_table_lock_) {
1644 auto it = interns.find(root);
1645 if (it != interns.end()) {
1646 ObjPtr<mirror::String> existing = root.Read();
1647 intern_remap.Put(it->Read(), existing.Ptr());
1648 it = interns.erase(it);
1649 }
1650 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1651 }
David Srbecky346fd962020-07-27 16:51:00 +01001652 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001653 if (kIsDebugBuild) {
1654 for (GcRoot<mirror::String>& root : interns) {
1655 ObjPtr<mirror::String> string = root.Read();
1656 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1657 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001658 }
1659 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001660 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001661 intern_table->AddImageStringsToTable(space, func);
1662 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001663 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001664 VisitInternedStringReferences(
1665 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001666 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1667 auto it = intern_remap.find(str.Ptr());
1668 if (it != intern_remap.end()) {
1669 return ObjPtr<mirror::String>(it->second);
1670 }
1671 return str;
1672 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001673 }
1674}
1675
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001676static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1677 const char* location,
1678 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001679 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001680 DCHECK(error_msg != nullptr);
1681 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001682 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001683 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001684 return std::unique_ptr<const DexFile>();
1685 }
1686 std::string inner_error_msg;
1687 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1688 if (dex_file == nullptr) {
1689 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1690 location,
1691 oat_file->GetLocation().c_str(),
1692 inner_error_msg.c_str());
1693 return std::unique_ptr<const DexFile>();
1694 }
1695
1696 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1697 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1698 location,
1699 dex_file->GetLocationChecksum(),
1700 oat_dex_file->GetDexFileLocationChecksum());
1701 return std::unique_ptr<const DexFile>();
1702 }
1703 return dex_file;
1704}
1705
1706bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1707 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1708 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001709 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001710 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001711 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001712 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001713 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001714 dex_caches_object->AsObjectArray<mirror::DexCache>();
1715 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001716 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001717 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1718 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1719 dex_file_location.c_str(),
1720 error_msg);
1721 if (dex_file == nullptr) {
1722 return false;
1723 }
1724 dex_cache->SetDexFile(dex_file.get());
1725 out_dex_files->push_back(std::move(dex_file));
1726 }
1727 return true;
1728}
1729
Andreas Gampe0793bec2016-12-01 11:37:33 -08001730// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1731// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001732class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001733 public:
1734 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1735 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001736 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001737 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1738 DCHECK(obj != nullptr);
1739 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1740 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1741 if (obj->IsClass()) {
1742 auto klass = obj->AsClass();
1743 for (ArtField& field : klass->GetIFields()) {
1744 CHECK_EQ(field.GetDeclaringClass(), klass);
1745 }
1746 for (ArtField& field : klass->GetSFields()) {
1747 CHECK_EQ(field.GetDeclaringClass(), klass);
1748 }
Orion Hodson5880c772020-07-28 20:12:08 +01001749 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001750 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001751 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001752 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001753 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001754 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001755 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001756 }
1757 if (klass->ShouldHaveImt()) {
1758 ImTable* imt = klass->GetImt(pointer_size);
1759 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001760 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001761 }
1762 }
1763 if (klass->ShouldHaveEmbeddedVTable()) {
1764 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001765 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001766 }
1767 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001768 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001769 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1770 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001771 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001772 }
1773 }
1774 }
1775 };
1776 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001777 }
1778
Andreas Gampe0793bec2016-12-01 11:37:33 -08001779 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001780 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001781 : spaces_(heap->GetBootImageSpaces()),
1782 pointer_size_(class_linker->GetImagePointerSize()) {
1783 space_begin_.reserve(spaces_.size());
1784 method_sections_.reserve(spaces_.size());
1785 runtime_method_sections_.reserve(spaces_.size());
1786 for (gc::space::ImageSpace* space : spaces_) {
1787 space_begin_.push_back(space->Begin());
1788 auto& header = space->GetImageHeader();
1789 method_sections_.push_back(&header.GetMethodsSection());
1790 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1791 }
1792 }
1793
Orion Hodson5880c772020-07-28 20:12:08 +01001794 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001795 REQUIRES_SHARED(Locks::mutator_lock_) {
1796 if (m->IsRuntimeMethod()) {
1797 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1798 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1799 } else if (m->IsCopied()) {
1800 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1801 } else if (expected_class != nullptr) {
1802 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1803 }
1804 if (!spaces_.empty()) {
1805 bool contains = false;
1806 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1807 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1808 contains = method_sections_[i]->Contains(offset) ||
1809 runtime_method_sections_[i]->Contains(offset);
1810 }
1811 CHECK(contains) << m << " not found";
1812 }
1813 }
1814
Orion Hodson5880c772020-07-28 20:12:08 +01001815 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1816 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001817 REQUIRES_SHARED(Locks::mutator_lock_) {
1818 CHECK(arr != nullptr);
1819 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1820 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1821 // expected_class == null means we are a dex cache.
1822 if (expected_class != nullptr) {
1823 CHECK(method != nullptr);
1824 }
1825 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001826 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001827 }
1828 }
1829 }
1830
Andreas Gampe0793bec2016-12-01 11:37:33 -08001831 const std::vector<gc::space::ImageSpace*>& spaces_;
1832 const PointerSize pointer_size_;
1833
1834 // Cached sections from the spaces.
1835 std::vector<const uint8_t*> space_begin_;
1836 std::vector<const ImageSection*> method_sections_;
1837 std::vector<const ImageSection*> runtime_method_sections_;
1838};
1839
Andreas Gampebe7af222017-07-25 09:57:28 -07001840static void VerifyAppImage(const ImageHeader& header,
1841 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001842 ClassTable* class_table,
1843 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001844 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001845 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1846 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1847 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1848 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1849 << mirror::Class::PrettyClass(klass);
1850 }
1851 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001852 {
1853 // Verify that all direct interfaces of classes in the class table are also resolved.
1854 std::vector<ObjPtr<mirror::Class>> classes;
1855 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1856 REQUIRES_SHARED(Locks::mutator_lock_) {
1857 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1858 classes.push_back(klass);
1859 }
1860 return true;
1861 };
1862 class_table->Visit(verify_direct_interfaces_in_table);
Andreas Gampebe7af222017-07-25 09:57:28 -07001863 for (ObjPtr<mirror::Class> klass : classes) {
1864 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +01001865 CHECK(klass->GetDirectInterface(i) != nullptr)
Andreas Gampebe7af222017-07-25 09:57:28 -07001866 << 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
David Srbecky86d6cd52020-12-02 18:13:10 +00001941 {
David Srbecky33df0e32021-09-30 14:36:32 +00001942 // Native fields are all null. Initialize them.
David Srbecky86d6cd52020-12-02 18:13:10 +00001943 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky33df0e32021-09-30 14:36:32 +00001944 dex_cache->Initialize(dex_file.get(), class_loader.Get());
David Srbecky86d6cd52020-12-02 18:13:10 +00001945 }
1946 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001947 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001948 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001949 }
1950 out_dex_files->push_back(std::move(dex_file));
1951 }
1952
1953 if (app_image) {
1954 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001955 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001956 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1957 *error_msg = "Unexpected BootClassLoader in app image";
1958 return false;
1959 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001960 }
1961
Orion Hodson5880c772020-07-28 20:12:08 +01001962 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001964 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001965 }
1966 }
1967
1968 // Set entry point to interpreter if in InterpretOnly mode.
1969 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001970 // Set image methods' entry point to interpreter.
1971 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1972 if (!method.IsRuntimeMethod()) {
1973 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001974 if (!method.IsNative() && !method.IsResolutionMethod()) {
1975 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1976 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001977 }
1978 }
1979 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001980 }
1981
Nicolas Geoffray47171752020-08-31 15:03:20 +01001982 if (!runtime->IsAotCompiler()) {
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001983 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001984 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00001985 uint16_t hotness_threshold = runtime->GetJITOptions()->GetWarmupThreshold();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001986 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01001987 // In the image, the `data` pointer field of the ArtMethod contains the code
1988 // item offset. Change this to the actual pointer to the code item.
1989 if (method.HasCodeItem()) {
1990 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
1991 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
zhaoxuyang7156ea22022-01-10 13:58:11 +08001992 method.SetCodeItem(code_item, method.GetDexFile()->IsCompactDexFile());
Nicolas Geoffray61673dc2021-11-06 13:58:31 +00001993 // The hotness counter may have changed since we compiled the image, so
1994 // reset it with the runtime value.
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00001995 method.ResetCounter(hotness_threshold);
Nicolas Geoffray47171752020-08-31 15:03:20 +01001996 }
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001997 if (method.GetEntryPointFromQuickCompiledCode() == nterp_trampoline_) {
1998 if (can_use_nterp) {
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00001999 // Set image methods' entry point that point to the nterp trampoline to the
2000 // nterp entry point. This allows taking the fast path when doing a
2001 // nterp->nterp call.
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00002002 DCHECK_IMPLIES(NeedsClinitCheckBeforeCall(&method),
2003 method.GetDeclaringClass()->IsVisiblyInitialized());
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00002004 method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
2005 } else {
2006 method.SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2007 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01002008 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002009 }, space->Begin(), image_pointer_size_);
2010 }
2011
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00002012 if (runtime->IsVerificationSoftFail()) {
2013 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2014 if (!method.IsNative() && method.IsInvokable()) {
2015 method.ClearSkipAccessChecks();
2016 }
2017 }, space->Begin(), image_pointer_size_);
2018 }
2019
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002020 ClassTable* class_table = nullptr;
2021 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002022 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002023 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002024 }
2025 // If we have a class table section, read it and use it for verification in
2026 // UpdateAppImageClassLoadersAndDexCaches.
2027 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002028 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002029 const bool added_class_table = class_table_section.Size() > 0u;
2030 if (added_class_table) {
2031 const uint64_t start_time2 = NanoTime();
2032 size_t read_count = 0;
2033 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2034 /*make copy*/false,
2035 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002036 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002037 }
2038 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002039 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002040
2041 {
2042 ScopedTrace trace("AppImage:UpdateClassLoaders");
2043 // Update class loader and resolved strings. If added_class_table is false, the resolved
2044 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002045 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002046 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002047 // Note: We probably don't need the read barrier unless we copy the app image objects into
2048 // the region space.
2049 ObjPtr<mirror::Class> klass(root.Read());
2050 // Do not update class loader for boot image classes where the app image
2051 // class loader is only the initiating loader but not the defining loader.
2052 // Avoid read barrier since we are comparing against null.
2053 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002054 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002055 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002056 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002057 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002058
Vladimir Marko305c38b2018-02-14 11:50:07 +00002059 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002060 // Every class in the app image has initially SubtypeCheckInfo in the
2061 // Uninitialized state.
2062 //
2063 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2064 // after class initialization is complete. The app image ClassStatus as-is
2065 // are almost all ClassStatus::Initialized, and being in the
2066 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2067 //
2068 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2069 //
2070 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002071 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002072 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2073 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002074 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002075 }
2076 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002077 }
2078 if (!oat_file->GetBssGcRoots().empty()) {
2079 // Insert oat file to class table for visiting .bss GC roots.
2080 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002081 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002082
Mathieu Chartier69731002016-03-02 16:08:31 -08002083 if (added_class_table) {
2084 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2085 class_table->AddClassSet(std::move(temp_set));
2086 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002087
Mathieu Chartier69731002016-03-02 16:08:31 -08002088 if (kIsDebugBuild && app_image) {
2089 // This verification needs to happen after the classes have been added to the class loader.
2090 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002091 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002092 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002093 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002094
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002095 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002096 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002097}
2098
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002099void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002100 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2101 // enabling tracing requires the mutator lock, there are no race conditions here.
2102 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002103 Thread* const self = Thread::Current();
2104 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002105 if (kUseReadBarrier) {
2106 // We do not track new roots for CC.
2107 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2108 kVisitRootFlagClearRootLog |
2109 kVisitRootFlagStartLoggingNewRoots |
2110 kVisitRootFlagStopLoggingNewRoots));
2111 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002112 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002113 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2114 // There is 3 GC cases to handle:
2115 // Non moving concurrent:
2116 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002117 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002118 //
2119 // Moving non-concurrent:
2120 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2121 // To prevent missing roots, this case needs to ensure that there is no
2122 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2123 // class which is in the class table.
2124 //
2125 // Moving concurrent:
2126 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2127 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002128 //
2129 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2130 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2131 // these objects.
2132 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002133 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002134 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002135 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002136 for (const ClassLoaderData& data : class_loaders_) {
2137 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2138 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2139 }
2140 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002141 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002142 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002143 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002144 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002145 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002146 // Concurrent moving GC marked new roots through the to-space invariant.
2147 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002148 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002149 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2150 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2151 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2152 if (old_ref != nullptr) {
2153 DCHECK(old_ref->IsClass());
2154 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2155 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2156 // Concurrent moving GC marked new roots through the to-space invariant.
2157 CHECK_EQ(new_ref, old_ref);
2158 }
2159 }
2160 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002161 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002162 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002163 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002164 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002165 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002166 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002167 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002168 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002169 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002170 }
2171 // We deliberately ignore the class roots in the image since we
2172 // handle image roots by using the MS/CMS rescanning of dirty cards.
2173}
2174
Brian Carlstroma663ea52011-08-19 23:33:41 -07002175// Keep in sync with InitCallback. Anything we visit, we need to
2176// reinit references to when reinitializing a ClassLinker from a
2177// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002178void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002179 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002180 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002181 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2182 // unloading if we are marking roots.
2183 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002184}
2185
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002186class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2187 public:
2188 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2189 : visitor_(visitor),
2190 done_(false) {}
2191
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002192 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002193 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002194 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002195 if (!done_ && class_table != nullptr) {
2196 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2197 if (!class_table->Visit(visitor)) {
2198 // If the visitor ClassTable returns false it means that we don't need to continue.
2199 done_ = true;
2200 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002201 }
2202 }
2203
2204 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002205 // Class visitor that limits the class visits from a ClassTable to the classes with
2206 // the provided defining class loader. This filter is used to avoid multiple visits
2207 // of the same class which can be recorded for multiple initiating class loaders.
2208 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2209 public:
2210 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2211 ClassVisitor* visitor)
2212 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2213
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002214 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002215 if (klass->GetClassLoader() != defining_class_loader_) {
2216 return true;
2217 }
2218 return (*visitor_)(klass);
2219 }
2220
Vladimir Marko0984e482019-03-27 16:41:41 +00002221 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002222 ClassVisitor* const visitor_;
2223 };
2224
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002225 ClassVisitor* const visitor_;
2226 // If done is true then we don't need to do any more visiting.
2227 bool done_;
2228};
2229
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002230void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002231 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002232 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2233 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002234 }
2235}
2236
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002237void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002238 Thread* const self = Thread::Current();
2239 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2240 // Not safe to have thread suspension when we are holding a lock.
2241 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002242 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002243 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002244 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002245 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002246 }
2247}
2248
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002249class GetClassesInToVector : public ClassVisitor {
2250 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002251 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002252 classes_.push_back(klass);
2253 return true;
2254 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002255 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002256};
2257
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002258class GetClassInToObjectArray : public ClassVisitor {
2259 public:
2260 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2261 : arr_(arr), index_(0) {}
2262
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002263 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002264 ++index_;
2265 if (index_ <= arr_->GetLength()) {
2266 arr_->Set(index_ - 1, klass);
2267 return true;
2268 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002269 return false;
2270 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002271
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002272 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002273 return index_ <= arr_->GetLength();
2274 }
2275
2276 private:
2277 mirror::ObjectArray<mirror::Class>* const arr_;
2278 int32_t index_;
2279};
2280
2281void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002282 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2283 // is avoiding duplicates.
2284 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002285 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002286 GetClassesInToVector accumulator;
2287 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002288 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002289 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002290 return;
2291 }
2292 }
2293 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002294 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002295 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002296 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002297 // We size the array assuming classes won't be added to the class table during the visit.
2298 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002299 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002300 size_t class_table_size;
2301 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002302 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002303 // Add 100 in case new classes get loaded when we are filling in the object array.
2304 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002305 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002306 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002307 classes.Assign(
2308 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002309 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002310 GetClassInToObjectArray accumulator(classes.Get());
2311 VisitClasses(&accumulator);
2312 if (accumulator.Succeeded()) {
2313 break;
2314 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002315 }
2316 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2317 // If the class table shrank during creation of the clases array we expect null elements. If
2318 // the class table grew then the loop repeats. If classes are created after the loop has
2319 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002320 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002321 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002322 return;
2323 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002324 }
2325 }
2326}
2327
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002328ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002329 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002330 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002331 // CHA unloading analysis is not needed. No negative consequences are expected because
2332 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002333 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002334 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002335 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002336 while (!running_visibly_initialized_callbacks_.empty()) {
2337 std::unique_ptr<VisiblyInitializedCallback> callback(
2338 std::addressof(running_visibly_initialized_callbacks_.front()));
2339 running_visibly_initialized_callbacks_.pop_front();
2340 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002341}
2342
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002343void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002344 Runtime* const runtime = Runtime::Current();
2345 JavaVMExt* const vm = runtime->GetJavaVM();
2346 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002347 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002348 if (runtime->GetJit() != nullptr) {
2349 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2350 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002351 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002352 code_cache->RemoveMethodsIn(self, *data.allocator);
2353 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002354 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002355 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002356 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002357 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002358 // Cleanup references to single implementation ArtMethods that will be deleted.
2359 if (cleanup_cha) {
2360 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
Vladimir Marko5f958f62022-02-08 12:01:07 +00002361 data.class_table->Visit<kWithoutReadBarrier>(visitor);
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002362 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002363 {
2364 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2365 auto end = critical_native_code_with_clinit_check_.end();
2366 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2367 if (data.allocator->ContainsUnsafe(it->first)) {
2368 it = critical_native_code_with_clinit_check_.erase(it);
2369 } else {
2370 ++it;
2371 }
2372 }
2373 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002374
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002375 delete data.allocator;
2376 delete data.class_table;
2377}
2378
Vladimir Markobcf17522018-06-01 13:14:32 +01002379ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2380 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002381 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002382 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2383 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002384}
2385
David Srbecky86d6cd52020-12-02 18:13:10 +00002386ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002387 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002388 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002389 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002390 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002391 self->AssertPendingOOMException();
2392 return nullptr;
2393 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002394 // Use InternWeak() so that the location String can be collected when the ClassLoader
2395 // with this DexCache is collected.
2396 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002397 if (location == nullptr) {
2398 self->AssertPendingOOMException();
2399 return nullptr;
2400 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002401 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002402 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002403}
2404
David Srbecky33df0e32021-09-30 14:36:32 +00002405ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(
2406 Thread* self, const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
2407 StackHandleScope<1> hs(self);
2408 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00002409 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002410 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002411 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky33df0e32021-09-30 14:36:32 +00002412 dex_cache->Initialize(&dex_file, h_class_loader.Get());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002413 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002414 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002415}
2416
Vladimir Marko70e2a762019-07-12 16:49:00 +01002417template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002418ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2419 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002420 uint32_t class_size,
2421 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002422 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002423 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002424 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002425 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2426 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002427 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002428 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002429 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002430 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002431 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002432}
2433
Vladimir Marko70e2a762019-07-12 16:49:00 +01002434template <bool kMovable>
2435ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2436 ObjPtr<mirror::Class> java_lang_Class,
2437 uint32_t class_size) {
2438 mirror::Class::InitializeClassVisitor visitor(class_size);
2439 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2440}
2441
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002442ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002443 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002444}
2445
Vladimir Marko70e2a762019-07-12 16:49:00 +01002446void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2447 ClassRoot primitive_root,
2448 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002449 // We make this class non-movable for the unlikely case where it were to be
2450 // moved by a sticky-bit (minor) collection when using the Generational
2451 // Concurrent Copying (CC) collector, potentially creating a stale reference
2452 // in the `klass_` field of one of its instances allocated in the Large-Object
2453 // Space (LOS) -- see the comment about the dirty card scanning logic in
2454 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002455 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2456 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2457 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2458 DCHECK(component_type->IsPrimitive());
2459 array_class->SetComponentType(component_type);
2460 SetClassRoot(array_root, array_class);
2461}
2462
2463void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2464 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2465 array_class->SetSuperClass(java_lang_Object);
2466 array_class->SetVTable(java_lang_Object->GetVTable());
2467 array_class->SetPrimitiveType(Primitive::kPrimNot);
2468 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2469 array_class->SetClassFlags(component_type->IsPrimitive()
2470 ? mirror::kClassFlagNoReferenceFields
2471 : mirror::kClassFlagObjectArray);
2472 array_class->SetClassLoader(component_type->GetClassLoader());
2473 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2474 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2475 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2476 array_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002477 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;
Vladimir Marko70e2a762019-07-12 16:49:00 +01002502
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002503 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002504
Vladimir Markobf121912019-06-04 13:49:05 +01002505 // Array classes are fully initialized either during single threaded startup,
2506 // or from a pre-fence visitor, so visibly initialized.
2507 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002508}
2509
2510void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2511 // Do not hold lock on the array class object, the initialization of
2512 // core array classes is done while the process is still single threaded.
2513 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2514 FinishArrayClassSetup(array_class);
2515
2516 std::string temp;
2517 const char* descriptor = array_class->GetDescriptor(&temp);
2518 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2519 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2520 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002521}
2522
Vladimir Markobcf17522018-06-01 13:14:32 +01002523ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002524 Thread* self,
2525 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002526 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002527 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002528}
2529
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002530ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2531 const char* descriptor,
2532 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002533 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002534 if (kIsDebugBuild) {
2535 StackHandleScope<1> hs(self);
2536 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2537 Thread::PoisonObjectPointersIfDebug();
2538 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002539
2540 // For temporary classes we must wait for them to be retired.
2541 if (init_done_ && klass->IsTemp()) {
2542 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002543 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002544 ThrowEarlierClassFailure(klass);
2545 return nullptr;
2546 }
2547 StackHandleScope<1> hs(self);
2548 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2549 ObjectLock<mirror::Class> lock(self, h_class);
2550 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002551 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002552 lock.WaitIgnoringInterrupts();
2553 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002554 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002555 ThrowEarlierClassFailure(h_class.Get());
2556 return nullptr;
2557 }
2558 CHECK(h_class->IsRetired());
2559 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002560 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002561 }
2562
Brian Carlstromaded5f72011-10-07 17:15:04 -07002563 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002564 size_t index = 0;
2565 // Maximum number of yield iterations until we start sleeping.
2566 static const size_t kNumYieldIterations = 1000;
2567 // How long each sleep is in us.
2568 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002569 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002570 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002571 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002572 {
2573 ObjectTryLock<mirror::Class> lock(self, h_class);
2574 // Can not use a monitor wait here since it may block when returning and deadlock if another
2575 // thread has locked klass.
2576 if (lock.Acquired()) {
2577 // Check for circular dependencies between classes, the lock is required for SetStatus.
2578 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2579 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002580 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002581 return nullptr;
2582 }
2583 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002585 {
2586 // Handle wrapper deals with klass moving.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002587 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002588 if (index < kNumYieldIterations) {
2589 sched_yield();
2590 } else {
2591 usleep(kSleepDurationUS);
2592 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002593 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002594 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002596
Vladimir Marko72ab6842017-01-20 19:32:50 +00002597 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002598 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002599 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002600 }
2601 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002602 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002603 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002604 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002605}
2606
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002607using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002608
2609// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002610ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002611 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002612 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002613 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002614 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002615 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002616 return ClassPathEntry(dex_file, dex_class_def);
2617 }
2618 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002619 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002620}
2621
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002622// Helper macro to make sure each class loader lookup call handles the case the
2623// class loader is not recognized, or the lookup threw an exception.
2624#define RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(call_, result_, thread_) \
2625do { \
2626 auto local_call = call_; \
2627 if (!local_call) { \
2628 return false; \
2629 } \
2630 auto local_result = result_; \
2631 if (local_result != nullptr) { \
2632 return true; \
2633 } \
2634 auto local_thread = thread_; \
2635 if (local_thread->IsExceptionPending()) { \
2636 /* Pending exception means there was an error other than */ \
2637 /* ClassNotFound that must be returned to the caller. */ \
2638 return false; \
2639 } \
2640} while (0)
2641
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002642bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2643 Thread* self,
2644 const char* descriptor,
2645 size_t hash,
2646 Handle<mirror::ClassLoader> class_loader,
2647 /*out*/ ObjPtr<mirror::Class>* result) {
2648 ArtField* field =
2649 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
Brad Stenning9c924e82021-10-11 19:09:00 -07002650 return FindClassInSharedLibrariesHelper(soa, self, descriptor, hash, class_loader, field, result);
2651}
2652
2653bool ClassLinker::FindClassInSharedLibrariesHelper(ScopedObjectAccessAlreadyRunnable& soa,
2654 Thread* self,
2655 const char* descriptor,
2656 size_t hash,
2657 Handle<mirror::ClassLoader> class_loader,
2658 ArtField* field,
2659 /*out*/ ObjPtr<mirror::Class>* result) {
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002660 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2661 if (raw_shared_libraries == nullptr) {
2662 return true;
2663 }
2664
2665 StackHandleScope<2> hs(self);
2666 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2667 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2668 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002669 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2670 temp_loader.Assign(loader);
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002671 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2672 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result),
2673 *result,
2674 self);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002675 }
2676 return true;
2677}
2678
Brad Stenning9c924e82021-10-11 19:09:00 -07002679bool ClassLinker::FindClassInSharedLibrariesAfter(ScopedObjectAccessAlreadyRunnable& soa,
2680 Thread* self,
2681 const char* descriptor,
2682 size_t hash,
2683 Handle<mirror::ClassLoader> class_loader,
2684 /*out*/ ObjPtr<mirror::Class>* result) {
2685 ArtField* field = jni::DecodeArtField(
2686 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
2687 return FindClassInSharedLibrariesHelper(soa, self, descriptor, hash, class_loader, field, result);
2688}
2689
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002690bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2691 Thread* self,
2692 const char* descriptor,
2693 size_t hash,
2694 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002695 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002696 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002697 if (IsBootClassLoader(soa, class_loader.Get())) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002698 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2699 FindClassInBootClassLoaderClassPath(self, descriptor, hash, result), *result, self);
Andreas Gampef865ea92015-04-13 22:14:19 -07002700 return true;
2701 }
2702
David Brazdil05909d82018-12-06 16:25:16 +00002703 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002704 // For regular path or dex class loader the search order is:
2705 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002706 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002707 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002708
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002709 // Create a handle as RegisterDexFile may allocate dex caches (and cause thread suspension).
Calin Juravlecdd49122017-07-05 20:09:53 -07002710 StackHandleScope<1> hs(self);
2711 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002712 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2713 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result),
2714 *result,
2715 self);
2716 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2717 FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result),
2718 *result,
2719 self);
2720 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2721 FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader, result),
2722 *result,
2723 self);
Brad Stenning9c924e82021-10-11 19:09:00 -07002724 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2725 FindClassInSharedLibrariesAfter(soa, self, descriptor, hash, class_loader, result),
2726 *result,
2727 self);
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002728 // We did not find a class, but the class loader chain was recognized, so we
2729 // return true.
2730 return true;
Andreas Gampef865ea92015-04-13 22:14:19 -07002731 }
2732
Calin Juravlecdd49122017-07-05 20:09:53 -07002733 if (IsDelegateLastClassLoader(soa, class_loader)) {
2734 // For delegate last, the search order is:
2735 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002736 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002737 // - class loader dex files
2738 // - parent
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002739 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2740 FindClassInBootClassLoaderClassPath(self, descriptor, hash, result), *result, self);
2741 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2742 FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result),
2743 *result,
2744 self);
2745 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2746 FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader, result),
2747 *result,
2748 self);
Brad Stenning9c924e82021-10-11 19:09:00 -07002749 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2750 FindClassInSharedLibrariesAfter(soa, self, descriptor, hash, class_loader, result),
2751 *result,
2752 self);
Calin Juravlecdd49122017-07-05 20:09:53 -07002753
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002754 // Create a handle as RegisterDexFile may allocate dex caches (and cause thread suspension).
Calin Juravlecdd49122017-07-05 20:09:53 -07002755 StackHandleScope<1> hs(self);
2756 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002757 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2758 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result),
2759 *result,
2760 self);
2761 // We did not find a class, but the class loader chain was recognized, so we
2762 // return true.
2763 return true;
Calin Juravlecdd49122017-07-05 20:09:53 -07002764 }
2765
2766 // Unsupported class loader.
2767 *result = nullptr;
2768 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002769}
2770
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002771#undef RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION
2772
Andreas Gampe501c3b02019-04-17 21:54:27 +00002773namespace {
2774
2775// Matches exceptions caught in DexFile.defineClass.
2776ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2777 ClassLinker* class_linker)
2778 REQUIRES_SHARED(Locks::mutator_lock_) {
2779 return
2780 // ClassNotFoundException.
2781 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2782 class_linker))
2783 ||
2784 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2785 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2786}
2787
2788// Clear exceptions caught in DexFile.defineClass.
2789ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2790 REQUIRES_SHARED(Locks::mutator_lock_) {
2791 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2792 self->ClearException();
2793 }
2794}
2795
2796} // namespace
2797
Calin Juravle415dc3d2017-06-28 11:03:12 -07002798// Finds the class in the boot class loader.
2799// If the class is found the method returns the resolved class. Otherwise it returns null.
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002800bool ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2801 const char* descriptor,
2802 size_t hash,
2803 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002804 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2805 if (pair.second != nullptr) {
2806 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2807 if (klass != nullptr) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002808 *result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002809 } else {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002810 *result = DefineClass(self,
2811 descriptor,
2812 hash,
2813 ScopedNullHandle<mirror::ClassLoader>(),
2814 *pair.first,
2815 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002816 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002817 if (*result == nullptr) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002818 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002819 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002820 }
2821 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002822 // The boot classloader is always a known lookup.
2823 return true;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002824}
Andreas Gampef865ea92015-04-13 22:14:19 -07002825
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002826bool ClassLinker::FindClassInBaseDexClassLoaderClassPath(
Calin Juravle415dc3d2017-06-28 11:03:12 -07002827 ScopedObjectAccessAlreadyRunnable& soa,
2828 const char* descriptor,
2829 size_t hash,
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002830 Handle<mirror::ClassLoader> class_loader,
2831 /*out*/ ObjPtr<mirror::Class>* result) {
David Brazdil05909d82018-12-06 16:25:16 +00002832 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2833 IsInMemoryDexClassLoader(soa, class_loader) ||
2834 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002835 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002836
Vladimir Marko68c07582021-04-19 16:01:15 +00002837 const DexFile* dex_file = nullptr;
2838 const dex::ClassDef* class_def = nullptr;
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002839 ObjPtr<mirror::Class> ret;
Vladimir Marko68c07582021-04-19 16:01:15 +00002840 auto find_class_def = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2841 const dex::ClassDef* cp_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2842 if (cp_class_def != nullptr) {
2843 dex_file = cp_dex_file;
2844 class_def = cp_class_def;
2845 return false; // Found a class definition, stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002846 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002847 return true; // Continue with the next DexFile.
2848 };
Vladimir Marko68c07582021-04-19 16:01:15 +00002849 VisitClassLoaderDexFiles(soa, class_loader, find_class_def);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002850
Vladimir Marko68c07582021-04-19 16:01:15 +00002851 if (class_def != nullptr) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002852 *result = DefineClass(soa.Self(), descriptor, hash, class_loader, *dex_file, *class_def);
2853 if (UNLIKELY(*result == nullptr)) {
Vladimir Marko68c07582021-04-19 16:01:15 +00002854 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2855 FilterDexFileCaughtExceptions(soa.Self(), this);
2856 } else {
2857 DCHECK(!soa.Self()->IsExceptionPending());
2858 }
2859 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002860 // A BaseDexClassLoader is always a known lookup.
2861 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002862}
2863
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002864ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2865 const char* descriptor,
2866 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002867 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002868 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002869 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002870 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002871 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002872 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2873 // for primitive classes that aren't backed by dex files.
2874 return FindPrimitiveClass(descriptor[0]);
2875 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002876 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002877 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002878 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002879 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002880 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002881 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002882 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002883 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002884 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002885 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002886 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002887 return DefineClass(self,
2888 descriptor,
2889 hash,
2890 ScopedNullHandle<mirror::ClassLoader>(),
2891 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002892 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002893 } else {
2894 // The boot class loader is searched ahead of the application class loader, failures are
2895 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2896 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002897 ObjPtr<mirror::Throwable> pre_allocated =
2898 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002899 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002900 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002901 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002902 }
2903 ObjPtr<mirror::Class> result_ptr;
2904 bool descriptor_equals;
2905 if (descriptor[0] == '[') {
2906 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2907 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2908 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2909 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002910 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002911 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002912 bool known_hierarchy =
2913 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2914 if (result_ptr != nullptr) {
2915 // The chain was understood and we found the class. We still need to add the class to
2916 // the class table to protect from racy programs that can try and redefine the path list
2917 // which would change the Class<?> returned for subsequent evaluation of const-class.
2918 DCHECK(known_hierarchy);
2919 DCHECK(result_ptr->DescriptorEquals(descriptor));
2920 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002921 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002922 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002923 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2924 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002925 //
2926 // If the chain was understood but we did not find the class, let the Java-side
2927 // rediscover all this and throw the exception with the right stack trace. Note that
2928 // the Java-side could still succeed for racy programs if another thread is actively
2929 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002930
Alex Light185a4612018-10-04 15:54:25 -07002931 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002932 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002933 // Oops, we can't call into java so we can't run actual class-loader code.
2934 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002935 ObjPtr<mirror::Throwable> pre_allocated =
2936 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2937 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002938 return nullptr;
2939 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002940
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002941 // Inlined DescriptorToDot(descriptor) with extra validation.
2942 //
2943 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2944 // the DescriptorEquals() check below and give a confusing error message. For example,
2945 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2946 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2947 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2948 size_t descriptor_length = strlen(descriptor);
2949 if (UNLIKELY(descriptor[0] != 'L') ||
2950 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2951 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2952 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2953 return nullptr;
2954 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002955
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002956 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2957 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002958 if (known_hierarchy &&
2959 fast_class_not_found_exceptions_ &&
2960 !Runtime::Current()->IsJavaDebuggable()) {
2961 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2962 // debuggable, optimize this path by throwing directly here without going back to Java
2963 // language. This reduces how many ClassNotFoundExceptions happen.
2964 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2965 "%s",
2966 class_name_string.c_str());
2967 } else {
2968 ScopedLocalRef<jobject> class_loader_object(
2969 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2970 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2971 {
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002972 ScopedThreadStateChange tsc(self, ThreadState::kNative);
Andreas Gampe87658f32019-04-18 18:39:02 +00002973 ScopedLocalRef<jobject> class_name_object(
2974 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2975 if (class_name_object.get() == nullptr) {
2976 DCHECK(self->IsExceptionPending()); // OOME.
2977 return nullptr;
2978 }
2979 CHECK(class_loader_object.get() != nullptr);
2980 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2981 WellKnownClasses::java_lang_ClassLoader_loadClass,
2982 class_name_object.get()));
2983 }
2984 if (result.get() == nullptr && !self->IsExceptionPending()) {
2985 // broken loader - throw NPE to be compatible with Dalvik
2986 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2987 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002988 return nullptr;
2989 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002990 result_ptr = soa.Decode<mirror::Class>(result.get());
2991 // Check the name of the returned class.
2992 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002993 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002994 } else {
2995 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002996 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002997 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002998
2999 if (self->IsExceptionPending()) {
3000 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3001 // However, to comply with the RI behavior, first check if another thread succeeded.
3002 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3003 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3004 self->ClearException();
3005 return EnsureResolved(self, descriptor, result_ptr);
3006 }
3007 return nullptr;
3008 }
3009
3010 // Try to insert the class to the class table, checking for mismatch.
3011 ObjPtr<mirror::Class> old;
3012 {
3013 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3014 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3015 old = class_table->Lookup(descriptor, hash);
3016 if (old == nullptr) {
3017 old = result_ptr; // For the comparison below, after releasing the lock.
3018 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003019 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003020 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003021 } // else throw below, after releasing the lock.
3022 }
3023 }
3024 if (UNLIKELY(old != result_ptr)) {
3025 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3026 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003027 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003028 const char* loader_class_name =
3029 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3030 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3031 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3032 << DescriptorToDot(descriptor) << "\").";
3033 return EnsureResolved(self, descriptor, old);
3034 }
3035 if (UNLIKELY(!descriptor_equals)) {
3036 std::string result_storage;
3037 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3038 std::string loader_storage;
3039 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3040 ThrowNoClassDefFoundError(
3041 "Initiating class loader of type %s returned class %s instead of %s.",
3042 DescriptorToDot(loader_class_name).c_str(),
3043 DescriptorToDot(result_name).c_str(),
3044 DescriptorToDot(descriptor).c_str());
3045 return nullptr;
3046 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003047 // Success.
3048 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003049}
3050
Alex Light270db1c2019-12-03 12:20:01 +00003051// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3052// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3053// like pausing class definition.
3054struct ScopedDefiningClass {
3055 public:
3056 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3057 : self_(self), returned_(false) {
3058 Locks::mutator_lock_->AssertSharedHeld(self_);
3059 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3060 self_->IncrDefineClassCount();
3061 }
3062 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3063 Locks::mutator_lock_->AssertSharedHeld(self_);
3064 CHECK(returned_);
3065 }
3066
3067 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3068 REQUIRES_SHARED(Locks::mutator_lock_) {
3069 CHECK(!returned_);
3070 self_->DecrDefineClassCount();
3071 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3072 Thread::PoisonObjectPointersIfDebug();
3073 returned_ = true;
3074 return h_klass.Get();
3075 }
3076
3077 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3078 REQUIRES_SHARED(Locks::mutator_lock_) {
3079 StackHandleScope<1> hs(self_);
3080 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3081 return Finish(h_klass);
3082 }
3083
3084 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3085 REQUIRES_SHARED(Locks::mutator_lock_) {
3086 ScopedNullHandle<mirror::Class> snh;
3087 return Finish(snh);
3088 }
3089
3090 private:
3091 Thread* self_;
3092 bool returned_;
3093};
3094
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003095ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3096 const char* descriptor,
3097 size_t hash,
3098 Handle<mirror::ClassLoader> class_loader,
3099 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003100 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003101 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003102 StackHandleScope<3> hs(self);
Eric Holk74584e62021-02-18 14:39:17 -08003103 metrics::AutoTimer timer{GetMetrics()->ClassLoadingTotalTime()};
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003104 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003105
Brian Carlstromaded5f72011-10-07 17:15:04 -07003106 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003107 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003108 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003109 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003110 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003111 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003112 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003113 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003114 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003115 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003116 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003117 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003118 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003119 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003120 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003121 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003122 }
3123
Calin Juravle33787682019-07-26 14:27:18 -07003124 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3125 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3126 // public class path then we prevent the definition of the class.
3127 //
3128 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3129 // classpath is not checked.
3130 if (class_loader == nullptr &&
3131 Runtime::Current()->IsAotCompiler() &&
3132 DenyAccessBasedOnPublicSdk(descriptor)) {
3133 ObjPtr<mirror::Throwable> pre_allocated =
3134 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3135 self->SetException(pre_allocated);
3136 return sdc.Finish(nullptr);
3137 }
3138
Alex Lighte9f61032018-09-24 16:04:51 -07003139 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3140 // code to be executed. We put it up here so we can avoid all the allocations associated with
3141 // creating the class. This can happen with (eg) jit threads.
3142 if (!self->CanLoadClasses()) {
3143 // Make sure we don't try to load anything, potentially causing an infinite loop.
3144 ObjPtr<mirror::Throwable> pre_allocated =
3145 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3146 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003147 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003148 }
3149
Andreas Gampefa4333d2017-02-14 11:10:34 -08003150 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003151 // Allocate a class with the status of not ready.
3152 // Interface object should get the right size here. Regular class will
3153 // figure out the right size later and be replaced with one of the right
3154 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003155 if (CanAllocClass()) {
3156 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3157 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003158 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003159 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003160 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003161 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003162 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003163 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003164 }
Alex Lightb0f11922017-01-23 14:25:17 -08003165 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3166 // nothing.
3167 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003168 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003169 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3170 // will only be called once.
3171 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3172 klass,
3173 class_loader,
3174 dex_file,
3175 dex_class_def,
3176 &new_dex_file,
3177 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003178 // Check to see if an exception happened during runtime callbacks. Return if so.
3179 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003180 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003181 }
Alex Lightb0f11922017-01-23 14:25:17 -08003182 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003183 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003184 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003185 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003186 }
3187 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003188 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003189
Jeff Hao848f70a2014-01-15 13:49:50 -08003190 // Mark the string class by setting its access flag.
3191 if (UNLIKELY(!init_done_)) {
3192 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3193 klass->SetStringClass();
3194 }
3195 }
3196
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003197 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003198 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003199 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003200 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003201
Mathieu Chartier590fee92013-09-13 13:46:47 -07003202 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003203 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003204 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003205 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3206 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003207 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003208 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003209
Mathieu Chartierc7853442015-03-27 14:35:38 -07003210 // Load the fields and other things after we are inserted in the table. This is so that we don't
3211 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3212 // other reason is that the field roots are only visited from the class table. So we need to be
3213 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003214 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003215 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003216 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003217 // An exception occured during load, set status to erroneous while holding klass' lock in case
3218 // notification is necessary.
3219 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003220 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003221 }
Alex Light270db1c2019-12-03 12:20:01 +00003222 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003223 }
3224
Brian Carlstromaded5f72011-10-07 17:15:04 -07003225 // Finish loading (if necessary) by finding parents
3226 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003227 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003228 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003229 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003230 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003231 }
Alex Light270db1c2019-12-03 12:20:01 +00003232 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003233 }
3234 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003235
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003236 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003237 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003238 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003239
Brian Carlstromaded5f72011-10-07 17:15:04 -07003240 // Link the class (if necessary)
3241 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003242 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003243 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003244
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003245 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003246 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003247 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003248 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003249 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003250 }
Alex Light270db1c2019-12-03 12:20:01 +00003251 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003252 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003253 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003254 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Markof9e82e52021-10-06 08:34:40 +01003255 CHECK(h_new_class->IsResolved()) << descriptor << " " << h_new_class->GetStatus();
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003256
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003257 // Instrumentation may have updated entrypoints for all methods of all
3258 // classes. However it could not update methods of this class while we
3259 // were loading it. Now the class is resolved, we can update entrypoints
3260 // as required by instrumentation.
3261 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3262 // We must be in the kRunnable state to prevent instrumentation from
3263 // suspending all threads to update entrypoints while we are doing it
3264 // for this class.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00003265 DCHECK_EQ(self->GetState(), ThreadState::kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003266 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003267 }
3268
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003269 /*
3270 * We send CLASS_PREPARE events to the debugger from here. The
3271 * definition of "preparation" is creating the static fields for a
3272 * class and initializing them to the standard default values, but not
3273 * executing any code (that comes later, during "initialization").
3274 *
3275 * We did the static preparation in LinkClass.
3276 *
3277 * The class has been prepared and resolved but possibly not yet verified
3278 * at this point.
3279 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003280 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003281
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003282 // Notify native debugger of the new class and its layout.
3283 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3284
Alex Light270db1c2019-12-03 12:20:01 +00003285 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003286}
3287
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003288uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003289 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003290 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003291 size_t num_8 = 0;
3292 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003293 size_t num_32 = 0;
3294 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003295 ClassAccessor accessor(dex_file, dex_class_def);
3296 // We allow duplicate definitions of the same field in a class_data_item
3297 // but ignore the repeated indexes here, b/21868015.
3298 uint32_t last_field_idx = dex::kDexNoIndex;
3299 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3300 uint32_t field_idx = field.GetIndex();
3301 // Ordering enforced by DexFileVerifier.
3302 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3303 if (UNLIKELY(field_idx == last_field_idx)) {
3304 continue;
3305 }
3306 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003307 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003308 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3309 char c = descriptor[0];
3310 switch (c) {
3311 case 'L':
3312 case '[':
3313 num_ref++;
3314 break;
3315 case 'J':
3316 case 'D':
3317 num_64++;
3318 break;
3319 case 'I':
3320 case 'F':
3321 num_32++;
3322 break;
3323 case 'S':
3324 case 'C':
3325 num_16++;
3326 break;
3327 case 'B':
3328 case 'Z':
3329 num_8++;
3330 break;
3331 default:
3332 LOG(FATAL) << "Unknown descriptor: " << c;
3333 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003334 }
3335 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003336 return mirror::Class::ComputeClassSize(false,
3337 0,
3338 num_8,
3339 num_16,
3340 num_32,
3341 num_64,
3342 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003343 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003344}
3345
Vladimir Marko86c87522020-05-11 16:55:55 +01003346void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003347 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003348 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003349 size_t num_direct_methods = klass->NumDirectMethods();
3350 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003351 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003352 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003353 if (UNLIKELY(klass->IsProxyClass())) {
3354 return;
3355 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003356 PointerSize pointer_size = image_pointer_size_;
3357 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3358 klass->GetDirectMethods(pointer_size).end(),
3359 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3360 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3361 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3362 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3363 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3364 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3365 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3366 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3367 lb->first->SetEntryPointFromJni(lb->second);
3368 lb = critical_native_code_with_clinit_check_.erase(lb);
3369 }
3370 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003371 Runtime* runtime = Runtime::Current();
Nicolas Geoffray854af032021-12-21 08:32:42 +00003372 if (runtime->IsAotCompiler()) {
3373 // We should not update entrypoints when running the transactional
3374 // interpreter.
3375 return;
Ian Rogers19846512012-02-24 11:42:47 -08003376 }
Alex Light64ad14d2014-08-19 14:23:13 -07003377
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00003378 instrumentation::Instrumentation* instrumentation = runtime->GetInstrumentation();
Ian Rogers1c829822013-09-30 18:18:50 -07003379 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003380 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3381 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003382 if (!method->IsStatic()) {
3383 // Only update static methods.
3384 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003385 }
Nicolas Geoffray854af032021-12-21 08:32:42 +00003386 instrumentation->UpdateMethodsCode(method, instrumentation->GetCodeForInvoke(method));
Ian Rogers19846512012-02-24 11:42:47 -08003387 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003388 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003389}
3390
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003391// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3392// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003393inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3394 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003395 DCHECK(method != nullptr);
3396 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003397 method->SetEntryPointFromQuickCompiledCodePtrSize(
3398 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3399 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003400}
3401
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003402static void LinkCode(ClassLinker* class_linker,
3403 ArtMethod* method,
3404 const OatFile::OatClass* oat_class,
3405 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003406 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003407 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003408 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003409 // The following code only applies to a non-compiler runtime.
3410 return;
3411 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003412
Ian Rogers62d6c772013-02-27 08:32:07 -08003413 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003414 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray854af032021-12-21 08:32:42 +00003415 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
Jeff Hao16743632013-05-08 10:59:04 -07003416
Alex Light9139e002015-10-09 15:59:48 -07003417 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003418 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003419 return;
3420 }
Ian Rogers19846512012-02-24 11:42:47 -08003421
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003422 const void* quick_code = nullptr;
3423 if (oat_class != nullptr) {
3424 // Every kind of method should at least get an invoke stub from the oat_method.
3425 // non-abstract methods also get their code pointers.
3426 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3427 quick_code = oat_method.GetQuickCode();
3428 }
Nicolas Geoffray854af032021-12-21 08:32:42 +00003429 runtime->GetInstrumentation()->InitializeMethodsCode(method, quick_code);
jeffhao26c0a1a2012-01-17 16:28:33 -08003430
Ian Rogers62d6c772013-02-27 08:32:07 -08003431 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003432 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3433 // as the extra processing for @CriticalNative is not needed yet.
3434 method->SetEntryPointFromJni(
3435 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Brian Carlstrom92827a52011-10-10 15:50:01 -07003436 }
3437}
3438
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003439void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003440 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003441 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003442 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003443 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003444 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003445 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003446 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003447 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003448
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003449 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003450 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003451 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003452 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003453 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003454 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003455 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003456
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003457 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003458 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003459}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003460
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003461LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3462 LinearAlloc* allocator,
3463 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003464 if (length == 0) {
3465 return nullptr;
3466 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003467 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3468 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3469 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003470 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003471 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003472 CHECK(ret != nullptr);
3473 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3474 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003475}
3476
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003477LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3478 LinearAlloc* allocator,
3479 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003480 if (length == 0) {
3481 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003482 }
Vladimir Marko14632852015-08-17 12:07:23 +01003483 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3484 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003485 const size_t storage_size =
3486 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003487 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003488 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003489 CHECK(ret != nullptr);
3490 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003491 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003492 }
3493 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003494}
3495
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003496LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003497 if (class_loader == nullptr) {
3498 return Runtime::Current()->GetLinearAlloc();
3499 }
3500 LinearAlloc* allocator = class_loader->GetAllocator();
3501 DCHECK(allocator != nullptr);
3502 return allocator;
3503}
3504
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003505LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003506 if (class_loader == nullptr) {
3507 return Runtime::Current()->GetLinearAlloc();
3508 }
3509 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3510 LinearAlloc* allocator = class_loader->GetAllocator();
3511 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003512 RegisterClassLoader(class_loader);
3513 allocator = class_loader->GetAllocator();
3514 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003515 }
3516 return allocator;
3517}
3518
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003519void ClassLinker::LoadClass(Thread* self,
3520 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003521 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003522 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003523 ClassAccessor accessor(dex_file,
3524 dex_class_def,
3525 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003526 if (!accessor.HasClassData()) {
3527 return;
3528 }
3529 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003530 {
3531 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3532 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003533 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003534 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003535 // We allow duplicate definitions of the same field in a class_data_item
3536 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003537 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003538 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3539 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003540 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003541 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3542 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003543 accessor.NumInstanceFields());
3544 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003545 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003546 uint32_t last_static_field_idx = 0u;
3547 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003548
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003549 // Methods
3550 bool has_oat_class = false;
3551 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3552 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3553 : OatFile::OatClass::Invalid();
3554 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3555 klass->SetMethodsPtr(
3556 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3557 accessor.NumDirectMethods(),
3558 accessor.NumVirtualMethods());
3559 size_t class_def_method_index = 0;
3560 uint32_t last_dex_method_index = dex::kDexNoIndex;
3561 size_t last_class_def_method_index = 0;
3562
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003563 uint16_t hotness_threshold = runtime->GetJITOptions()->GetWarmupThreshold();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003564 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3565 // methods needs to decode all of the fields.
3566 accessor.VisitFieldsAndMethods([&](
3567 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3568 uint32_t field_idx = field.GetIndex();
3569 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3570 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3571 LoadField(field, klass, &sfields->At(num_sfields));
3572 ++num_sfields;
3573 last_static_field_idx = field_idx;
3574 }
3575 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3576 uint32_t field_idx = field.GetIndex();
3577 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3578 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3579 LoadField(field, klass, &ifields->At(num_ifields));
3580 ++num_ifields;
3581 last_instance_field_idx = field_idx;
3582 }
3583 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3584 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3585 image_pointer_size_);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003586 LoadMethod(dex_file, method, klass.Get(), art_method);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003587 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3588 uint32_t it_method_index = method.GetIndex();
3589 if (last_dex_method_index == it_method_index) {
3590 // duplicate case
3591 art_method->SetMethodIndex(last_class_def_method_index);
3592 } else {
3593 art_method->SetMethodIndex(class_def_method_index);
3594 last_dex_method_index = it_method_index;
3595 last_class_def_method_index = class_def_method_index;
3596 }
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003597 art_method->ResetCounter(hotness_threshold);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003598 ++class_def_method_index;
3599 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3600 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3601 class_def_method_index - accessor.NumDirectMethods(),
3602 image_pointer_size_);
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003603 art_method->ResetCounter(hotness_threshold);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003604 LoadMethod(dex_file, method, klass.Get(), art_method);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003605 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3606 ++class_def_method_index;
3607 });
3608
3609 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003610 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003611 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3612 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3613 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003614 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3615 if (sfields != nullptr) {
3616 sfields->SetSize(num_sfields);
3617 }
3618 if (ifields != nullptr) {
3619 ifields->SetSize(num_ifields);
3620 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003621 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003622 // Set the field arrays.
3623 klass->SetSFieldsPtr(sfields);
3624 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003625 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003626 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003627 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003628 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003629 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003630 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003631}
3632
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003633void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003634 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003635 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003636 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003637 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003638 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003639
David Brazdil85865692018-10-30 17:26:20 +00003640 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3641 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003642}
3643
Mathieu Chartier268764d2016-09-13 12:09:38 -07003644void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003645 const ClassAccessor::Method& method,
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003646 ObjPtr<mirror::Class> klass,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003647 ArtMethod* dst) {
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003648 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
3649
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003650 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003651 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003652 uint32_t name_utf16_length;
3653 const char* method_name = dex_file.StringDataAndUtf16LengthByIdx(method_id.name_idx_,
3654 &name_utf16_length);
3655 std::string_view shorty = dex_file.GetShortyView(dex_file.GetProtoId(method_id.proto_idx_));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003656
Mathieu Chartier66f19252012-09-18 08:57:04 -07003657 dst->SetDexMethodIndex(dex_method_idx);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003658 dst->SetDeclaringClass(klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003659
David Brazdil85865692018-10-30 17:26:20 +00003660 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3661 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003662
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003663 auto has_ascii_name = [method_name, name_utf16_length](const char* ascii_name,
3664 size_t length) ALWAYS_INLINE {
3665 DCHECK_EQ(strlen(ascii_name), length);
3666 return length == name_utf16_length &&
3667 method_name[length] == 0 && // Is `method_name` an ASCII string?
3668 memcmp(ascii_name, method_name, length) == 0;
3669 };
3670 if (UNLIKELY(has_ascii_name("finalize", sizeof("finalize") - 1u))) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003671 // Set finalizable flag on declaring class.
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003672 if (shorty == "V") {
Ian Rogersdfb325e2013-10-30 01:00:44 -07003673 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003674 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003675 klass->SetFinalizable();
3676 } else {
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003677 std::string_view klass_descriptor =
3678 dex_file.GetTypeDescriptorView(dex_file.GetTypeId(klass->GetDexTypeIndex()));
Ian Rogersdfb325e2013-10-30 01:00:44 -07003679 // The Enum class declares a "final" finalize() method to prevent subclasses from
3680 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3681 // subclasses, so we exclude it here.
3682 // We also want to avoid setting the flag on Object, where we know that finalize() is
3683 // empty.
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003684 if (klass_descriptor != "Ljava/lang/Object;" &&
3685 klass_descriptor != "Ljava/lang/Enum;") {
Ian Rogers241b5de2013-10-09 17:58:57 -07003686 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003687 }
3688 }
3689 }
3690 } else if (method_name[0] == '<') {
3691 // Fix broken access flags for initializers. Bug 11157540.
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003692 bool is_init = has_ascii_name("<init>", sizeof("<init>") - 1u);
3693 bool is_clinit = has_ascii_name("<clinit>", sizeof("<clinit>") - 1u);
Ian Rogers241b5de2013-10-09 17:58:57 -07003694 if (UNLIKELY(!is_init && !is_clinit)) {
3695 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3696 } else {
3697 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3698 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003699 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003700 access_flags |= kAccConstructor;
3701 }
3702 }
3703 }
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003704 size_t slow_args_search_start = 1u; // First arg.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003705 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3706 // Check if the native method is annotated with @FastNative or @CriticalNative.
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003707 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3708 access_flags |=
3709 annotations::GetNativeMethodAnnotationAccessFlags(dex_file, class_def, dex_method_idx);
3710 dst->SetAccessFlags(access_flags);
3711 DCHECK(!dst->IsAbstract());
3712 DCHECK(!dst->HasCodeItem());
Nicolas Geoffray47171752020-08-31 15:03:20 +01003713 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003714 dst->SetDataPtrSize(nullptr, image_pointer_size_); // JNI stub/trampoline not linked yet.
3715 } else if ((access_flags & kAccAbstract) != 0u) {
3716 dst->SetAccessFlags(access_flags);
3717 // Must be done after SetAccessFlags since IsAbstract depends on it.
3718 DCHECK(dst->IsAbstract());
3719 if (klass->IsInterface()) {
3720 dst->CalculateAndSetImtIndex();
3721 }
3722 DCHECK(!dst->HasCodeItem());
3723 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3724 dst->SetDataPtrSize(nullptr, image_pointer_size_); // Single implementation not set yet.
3725 } else {
3726 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3727 if (annotations::MethodIsNeverCompile(dex_file, class_def, dex_method_idx)) {
3728 access_flags |= kAccCompileDontBother;
3729 }
3730 dst->SetAccessFlags(access_flags);
3731 DCHECK(!dst->IsAbstract());
3732 DCHECK(dst->HasCodeItem());
3733 uint32_t code_item_offset = method.GetCodeItemOffset();
3734 DCHECK_NE(code_item_offset, 0u);
3735 if (Runtime::Current()->IsAotCompiler()) {
3736 dst->SetDataPtrSize(reinterpret_cast32<void*>(code_item_offset), image_pointer_size_);
3737 } else {
3738 dst->SetCodeItem(dex_file.GetCodeItem(code_item_offset), dex_file.IsCompactDexFile());
3739 }
3740 // Check for nterp entry fast-path based on shorty.
3741 slow_args_search_start = shorty.find_first_not_of('L', 1u);
3742 if (slow_args_search_start == std::string_view::npos) {
3743 dst->SetNterpEntryPointFastPathFlag();
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003744 }
3745 }
3746
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003747 // Check for nterp invoke fast-path based on shorty.
3748 auto is_slow_arg = [](char c) { return c == 'F' || c == 'D' || c == 'J'; };
3749 if ((shorty[0] != 'F' && shorty[0] != 'D') && // Returns reference or integral type.
3750 (slow_args_search_start == std::string_view::npos ||
3751 std::none_of(shorty.begin() + slow_args_search_start, shorty.end(), is_slow_arg))) {
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003752 dst->SetNterpInvokeFastPathFlag();
3753 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003754}
3755
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003756void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
David Srbecky33df0e32021-09-30 14:36:32 +00003757 ObjPtr<mirror::DexCache> dex_cache =
3758 AllocAndInitializeDexCache(self, *dex_file, /* class_loader= */ nullptr);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003759 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003760 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003761}
3762
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003763void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003764 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003765 CHECK(dex_file != nullptr);
3766 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
Nicolas Geoffray7913cf32022-02-16 09:28:21 +00003767 CHECK_EQ(dex_cache->GetDexFile(), dex_file) << dex_file->GetLocation();
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003768 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003769 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003770 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003771}
3772
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003773void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003774 ObjPtr<mirror::DexCache> dex_cache,
3775 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003776 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003777 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003778 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003779 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003780 // For app images, the dex cache location may be a suffix of the dex file location since the
3781 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003782 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3783 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003784 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3785 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003786 // The following paths checks don't work on preopt when using boot dex files, where the dex
3787 // cache location is the one on device, and the dex_file's location is the one on host.
3788 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3789 CHECK_GE(dex_file_location.length(), dex_cache_length)
3790 << dex_cache_location << " " << dex_file.GetLocation();
3791 const std::string dex_file_suffix = dex_file_location.substr(
3792 dex_file_location.length() - dex_cache_length,
3793 dex_cache_length);
3794 // Example dex_cache location is SettingsProvider.apk and
3795 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3796 CHECK_EQ(dex_cache_location, dex_file_suffix);
3797 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003798 const OatFile* oat_file =
3799 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003800 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3801 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3802 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3803 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003804 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003805 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
David Srbecky6fbcc292021-02-23 01:05:32 +00003806 const DexCacheData& data = it->second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003807 if (self->IsJWeakCleared(data.weak_root)) {
3808 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003809 it = dex_caches_.erase(it);
3810 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003811 if (initialize_oat_file_data &&
David Srbecky6fbcc292021-02-23 01:05:32 +00003812 it->first->GetOatDexFile() != nullptr &&
3813 it->first->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003814 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003815 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003816 ++it;
3817 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003818 }
Vladimir Markob066d432018-01-03 13:14:37 +00003819 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003820 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003821 }
David Brazdila5c3a802019-03-08 14:59:41 +00003822 // Let hiddenapi assign a domain to the newly registered dex file.
3823 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3824
Vladimir Markocd556b02017-02-03 11:47:34 +00003825 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003826 DexCacheData data;
3827 data.weak_root = dex_cache_jweak;
Vladimir Markocd556b02017-02-03 11:47:34 +00003828 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky6fbcc292021-02-23 01:05:32 +00003829 AddNativeDebugInfoForDex(self, &dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003830 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003831 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3832 // path dex caches without an image.
3833 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003834 // Make sure that the dex cache holds the classloader live.
3835 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003836 if (class_loader != nullptr) {
3837 // Since we added a strong root to the class table, do the write barrier as required for
3838 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003839 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003840 }
David Srbecky6fbcc292021-02-23 01:05:32 +00003841 bool inserted = dex_caches_.emplace(&dex_file, std::move(data)).second;
3842 CHECK(inserted);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003843}
3844
Alex Light725da8f2020-02-19 14:46:33 -08003845ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3846 return data != nullptr
3847 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003848 : nullptr;
3849}
3850
Alex Light725da8f2020-02-19 14:46:33 -08003851bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003852 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003853 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003854 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003855 CHECK(data != nullptr);
David Srbecky6fbcc292021-02-23 01:05:32 +00003856 DCHECK_EQ(FindDexCacheDataLocked(*dex_cache->GetDexFile()), data);
Alex Light725da8f2020-02-19 14:46:33 -08003857 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003858}
3859
Alex Light07f06212017-06-01 14:01:43 -07003860void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3861 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003862 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003863 Thread* self = Thread::Current();
3864 StackHandleScope<2> hs(self);
3865 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3866 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3867 const DexFile* dex_file = dex_cache->GetDexFile();
3868 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3869 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003870 ReaderMutexLock mu(self, *Locks::dex_lock_);
3871 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3872 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003873 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3874 << "been registered on dex file " << dex_file->GetLocation();
3875 }
3876 ClassTable* table;
3877 {
3878 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3879 table = InsertClassTableForClassLoader(h_class_loader.Get());
3880 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003881 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3882 // a thread holding the dex lock and blocking on a condition variable regarding
3883 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003884 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003885 WriterMutexLock mu(self, *Locks::dex_lock_);
3886 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3887 table->InsertStrongRoot(h_dex_cache.Get());
3888 if (h_class_loader.Get() != nullptr) {
3889 // Since we added a strong root to the class table, do the write barrier as required for
3890 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003891 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003892 }
3893}
3894
Alex Lightde7f8782020-02-24 10:14:22 -08003895static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
3896 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08003897 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08003898 "Attempt to register dex file %s with multiple class loaders",
3899 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08003900}
3901
Vladimir Markocd556b02017-02-03 11:47:34 +00003902ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3903 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003904 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08003905 ObjPtr<mirror::DexCache> old_dex_cache;
3906 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003907 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003908 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003909 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
3910 old_dex_cache = DecodeDexCacheLocked(self, old_data);
3911 if (old_dex_cache != nullptr) {
3912 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
3913 return old_dex_cache;
3914 } else {
3915 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
3916 // be thrown when it's safe to do so to simplify this.
3917 registered_with_another_class_loader = true;
3918 }
3919 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003920 }
Alex Light725da8f2020-02-19 14:46:33 -08003921 // We need to have released the dex_lock_ to allocate safely.
3922 if (registered_with_another_class_loader) {
3923 ThrowDexFileAlreadyRegisteredError(self, dex_file);
3924 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003925 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003926 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003927 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3928 DCHECK(linear_alloc != nullptr);
3929 ClassTable* table;
3930 {
3931 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3932 table = InsertClassTableForClassLoader(class_loader);
3933 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003934 // Don't alloc while holding the lock, since allocation may need to
3935 // suspend all threads and another thread may need the dex_lock_ to
3936 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003937 StackHandleScope<3> hs(self);
3938 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00003939 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003940 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003941 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3942 // a thread holding the dex lock and blocking on a condition variable regarding
3943 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003944 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003945 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003946 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
3947 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003948 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
David Srbecky33df0e32021-09-30 14:36:32 +00003949 // Do Initialize while holding dex lock to make sure two threads don't call it
David Srbecky86d6cd52020-12-02 18:13:10 +00003950 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
3951 // DCHECK that the arrays are null.
David Srbecky33df0e32021-09-30 14:36:32 +00003952 h_dex_cache->Initialize(&dex_file, h_class_loader.Get());
Vladimir Markocd556b02017-02-03 11:47:34 +00003953 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003954 }
Alex Light725da8f2020-02-19 14:46:33 -08003955 if (old_dex_cache != nullptr) {
3956 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3957 // If this thread encountered OOME, ignore it.
3958 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
3959 self->ClearException();
3960 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
3961 // dex_lock_.
3962 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
3963 return old_dex_cache;
3964 } else {
3965 registered_with_another_class_loader = true;
3966 }
3967 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003968 }
Alex Light725da8f2020-02-19 14:46:33 -08003969 if (registered_with_another_class_loader) {
3970 ThrowDexFileAlreadyRegisteredError(self, dex_file);
3971 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00003972 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003973 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003974 self->AssertPendingOOMException();
3975 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003976 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003977 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003978 if (h_class_loader.Get() != nullptr) {
3979 // Since we added a strong root to the class table, do the write barrier as required for
3980 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003981 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003982 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01003983 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
Nicolas Geoffray4f6bb442021-06-02 18:05:51 +01003984 PaletteNotifyDexFileLoaded(dex_file.GetLocation().c_str());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003985 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003986}
3987
Vladimir Markocd556b02017-02-03 11:47:34 +00003988bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003989 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003990 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003991}
3992
Vladimir Markocd556b02017-02-03 11:47:34 +00003993ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3994 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003995 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
3996 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003997 if (dex_cache != nullptr) {
3998 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003999 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004000 // Failure, dump diagnostic and abort.
David Srbecky6fbcc292021-02-23 01:05:32 +00004001 for (const auto& entry : dex_caches_) {
4002 const DexCacheData& data = entry.second;
Alex Light725da8f2020-02-19 14:46:33 -08004003 if (DecodeDexCacheLocked(self, &data) != nullptr) {
David Srbecky6fbcc292021-02-23 01:05:32 +00004004 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << entry.first->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004005 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004006 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004007 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
David Srbecky6fbcc292021-02-23 01:05:32 +00004008 << " " << &dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004009 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004010}
4011
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004012ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const OatDexFile& oat_dex_file) {
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004013 ReaderMutexLock mu(self, *Locks::dex_lock_);
4014 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(oat_dex_file);
4015 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
4016 if (dex_cache != nullptr) {
4017 return dex_cache;
4018 }
4019 // Failure, dump diagnostic and abort.
4020 for (const auto& entry : dex_caches_) {
4021 const DexCacheData& data = entry.second;
4022 if (DecodeDexCacheLocked(self, &data) != nullptr) {
4023 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << entry.first->GetLocation();
4024 }
4025 }
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004026 LOG(FATAL) << "Failed to find DexCache for OatDexFile " << oat_dex_file.GetDexFileLocation()
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004027 << " " << &oat_dex_file;
4028 UNREACHABLE();
4029}
4030
Vladimir Markocd556b02017-02-03 11:47:34 +00004031ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4032 const DexFile* dex_file = dex_cache->GetDexFile();
4033 DCHECK(dex_file != nullptr);
4034 ReaderMutexLock mu(self, *Locks::dex_lock_);
David Srbecky6fbcc292021-02-23 01:05:32 +00004035 auto it = dex_caches_.find(dex_file);
4036 if (it != dex_caches_.end()) {
4037 const DexCacheData& data = it->second;
4038 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
4039 if (registered_dex_cache != nullptr) {
4040 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4041 return data.class_table;
Vladimir Markocd556b02017-02-03 11:47:34 +00004042 }
4043 }
4044 return nullptr;
4045}
4046
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004047const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004048 const OatDexFile& oat_dex_file) {
4049 auto it = std::find_if(dex_caches_.begin(), dex_caches_.end(), [&](const auto& entry) {
4050 return entry.first->GetOatDexFile() == &oat_dex_file;
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004051 });
4052 return it != dex_caches_.end() ? &it->second : nullptr;
4053}
4054
Alex Light725da8f2020-02-19 14:46:33 -08004055const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
David Srbecky6fbcc292021-02-23 01:05:32 +00004056 auto it = dex_caches_.find(&dex_file);
4057 return it != dex_caches_.end() ? &it->second : nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004058}
4059
Vladimir Marko70e2a762019-07-12 16:49:00 +01004060void ClassLinker::CreatePrimitiveClass(Thread* self,
4061 Primitive::Type type,
4062 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004063 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004064 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004065 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4066 // Do not hold lock on the primitive class object, the initialization of
4067 // primitive classes is done while the process is still single threaded.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004068 primitive_class->SetAccessFlagsDuringLinking(kAccPublic | kAccFinal | kAccAbstract);
Vladimir Marko70e2a762019-07-12 16:49:00 +01004069 primitive_class->SetPrimitiveType(type);
4070 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko70e2a762019-07-12 16:49:00 +01004071 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004072 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4073 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004074 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004075 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004076 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004077 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004078 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004079 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004080}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004081
Vladimir Marko02610552018-06-04 14:38:00 +01004082inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4083 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4084}
4085
Brian Carlstrombe977852011-07-19 14:54:54 -07004086// Create an array class (i.e. the class object for the array, not the
4087// array itself). "descriptor" looks like "[C" or "[[[[B" or
4088// "[Ljava/lang/String;".
4089//
4090// If "descriptor" refers to an array of primitives, look up the
4091// primitive type's internally-generated class object.
4092//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004093// "class_loader" is the class loader of the class that's referring to
4094// us. It's used to ensure that we're looking for the element type in
4095// the right context. It does NOT become the class loader for the
4096// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004097//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004098// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004099ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4100 const char* descriptor,
4101 size_t hash,
4102 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004103 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004104 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004105 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004106
4107 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4108 // code to be executed. We put it up here so we can avoid all the allocations associated with
4109 // creating the class. This can happen with (eg) jit threads.
4110 if (!self->CanLoadClasses()) {
4111 // Make sure we don't try to load anything, potentially causing an infinite loop.
4112 ObjPtr<mirror::Throwable> pre_allocated =
4113 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4114 self->SetException(pre_allocated);
4115 return nullptr;
4116 }
4117
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004118 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4119 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004120 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004121 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004122 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004123 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4124 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004125 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004126 DCHECK(self->IsExceptionPending());
4127 return nullptr;
4128 } else {
4129 self->ClearException();
4130 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004131 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004132 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4133 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4134 return nullptr;
4135 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004136 // See if the component type is already loaded. Array classes are
4137 // always associated with the class loader of their underlying
4138 // element type -- an array of Strings goes with the loader for
4139 // java/lang/String -- so we need to look for it there. (The
4140 // caller should have checked for the existence of the class
4141 // before calling here, but they did so with *their* class loader,
4142 // not the component type's loader.)
4143 //
4144 // If we find it, the caller adds "loader" to the class' initiating
4145 // loader list, which should prevent us from going through this again.
4146 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004147 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004148 // are the same, because our caller (FindClass) just did the
4149 // lookup. (Even if we get this wrong we still have correct behavior,
4150 // because we effectively do this lookup again when we add the new
4151 // class to the hash table --- necessary because of possible races with
4152 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004153 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004154 ObjPtr<mirror::Class> new_class =
4155 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004156 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004157 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004158 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004159 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004160 // Core array classes, i.e. Object[], Class[], String[] and primitive
4161 // arrays, have special initialization and they should be found above.
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00004162 DCHECK_IMPLIES(component_type->IsObjectClass(),
4163 // Guard from false positives for errors before setting superclass.
4164 component_type->IsErroneousUnresolved());
Vladimir Marko70e2a762019-07-12 16:49:00 +01004165 DCHECK(!component_type->IsStringClass());
4166 DCHECK(!component_type->IsClassClass());
4167 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004168
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004169 // Fill out the fields in the Class.
4170 //
4171 // It is possible to execute some methods against arrays, because
4172 // all arrays are subclasses of java_lang_Object_, so we need to set
4173 // up a vtable. We can just point at the one in java_lang_Object_.
4174 //
4175 // Array classes are simple enough that we don't need to do a full
4176 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004177 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4178 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4179 size_t usable_size)
4180 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004181 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004182 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4183 init_class(obj, usable_size);
4184 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4185 klass->SetComponentType(component_type.Get());
4186 // Do not hold lock for initialization, the fence issued after the visitor
4187 // returns ensures memory visibility together with the implicit consume
4188 // semantics (for all supported architectures) for any thread that loads
4189 // the array class reference from any memory locations afterwards.
4190 FinishArrayClassSetup(klass);
4191 };
4192 auto new_class = hs.NewHandle<mirror::Class>(
4193 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004194 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004195 self->AssertPendingOOMException();
4196 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004197 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004198
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004199 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004200 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004201 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4202 // duplicate events in case of races. Array classes don't really follow dedicated
4203 // load and prepare, anyways.
4204 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4205 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4206
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004207 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004208 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004209 }
4210 // Another thread must have loaded the class after we
4211 // started but before we finished. Abandon what we've
4212 // done.
4213 //
4214 // (Yes, this happens.)
4215
Vladimir Markobcf17522018-06-01 13:14:32 +01004216 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004217}
4218
Vladimir Marko9186b182018-11-06 14:55:54 +00004219ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4220 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004221 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004222 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4223 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4224 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4225 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4226 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4227 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4228 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4229 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4230 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004231 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004232 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004233 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004234 return GetClassRoot(class_root, this);
4235}
4236
4237ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4238 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4239 if (UNLIKELY(result == nullptr)) {
4240 std::string printable_type(PrintableChar(type));
4241 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4242 }
4243 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004244}
4245
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004246ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4247 ObjPtr<mirror::Class> klass,
4248 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004249 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004250 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004251 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004252 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004253 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004254 source += " from ";
4255 source += dex_cache->GetLocation()->ToModifiedUtf8();
4256 }
4257 LOG(INFO) << "Loaded class " << descriptor << source;
4258 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004259 {
4260 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004261 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004262 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004263 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004264 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004265 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004266 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004267 VerifyObject(klass);
4268 class_table->InsertWithHash(klass, hash);
4269 if (class_loader != nullptr) {
4270 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004271 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004272 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004273 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004274 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004275 }
4276 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004277 if (kIsDebugBuild) {
4278 // Test that copied methods correctly can find their holder.
4279 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4280 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4281 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004282 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004283 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004284}
4285
Vladimir Marko1998cd02017-01-13 13:02:58 +00004286void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004287 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4288 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4289 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4290 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004291 }
4292}
4293
Alex Lighte64300b2015-12-15 15:02:47 -08004294// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004295void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004296 LengthPrefixedArray<ArtMethod>* new_methods) {
4297 klass->SetMethodsPtrUnchecked(new_methods,
4298 klass->NumDirectMethods(),
4299 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004300 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004301 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004302}
4303
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004304ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4305 const char* descriptor,
4306 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004307 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4308}
4309
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004310ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4311 const char* descriptor,
4312 size_t hash,
4313 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004314 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4315 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4316 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004317 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004318 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004319 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004320 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004321 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004322 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004323}
4324
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004325class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4326 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004327 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004328
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004329 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004330 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004331 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004332 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004333 if (class_table != nullptr) {
4334 class_table->FreezeSnapshot();
4335 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004336 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004337};
4338
4339void ClassLinker::MoveClassTableToPreZygote() {
4340 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004341 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004342 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004343 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004344}
4345
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004346// Look up classes by hash and descriptor and put all matching ones in the result array.
4347class LookupClassesVisitor : public ClassLoaderVisitor {
4348 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004349 LookupClassesVisitor(const char* descriptor,
4350 size_t hash,
4351 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004352 : descriptor_(descriptor),
4353 hash_(hash),
4354 result_(result) {}
4355
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004356 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004357 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004358 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004359 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004360 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4361 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004362 result_->push_back(klass);
4363 }
4364 }
4365
4366 private:
4367 const char* const descriptor_;
4368 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004369 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004370};
4371
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004372void ClassLinker::LookupClasses(const char* descriptor,
4373 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004374 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004375 Thread* const self = Thread::Current();
4376 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004377 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004378 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004379 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004380 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004381 result.push_back(klass);
4382 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004383 LookupClassesVisitor visitor(descriptor, hash, &result);
4384 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004385}
4386
Alex Lightf1f10492015-10-07 16:08:36 -07004387bool ClassLinker::AttemptSupertypeVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004388 verifier::VerifierDeps* verifier_deps,
Alex Lightf1f10492015-10-07 16:08:36 -07004389 Handle<mirror::Class> klass,
4390 Handle<mirror::Class> supertype) {
4391 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004392 DCHECK(klass != nullptr);
4393 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004394
Alex Lightf1f10492015-10-07 16:08:36 -07004395 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004396 VerifyClass(self, verifier_deps, supertype);
Alex Lightf1f10492015-10-07 16:08:36 -07004397 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004398
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004399 if (supertype->IsVerified()
4400 || supertype->ShouldVerifyAtRuntime()
4401 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004402 // The supertype is either verified, or we soft failed at AOT time.
4403 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004404 return true;
4405 }
4406 // If we got this far then we have a hard failure.
4407 std::string error_msg =
4408 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004409 klass->PrettyDescriptor().c_str(),
4410 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004411 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004412 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004413 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004414 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004415 // Set during VerifyClass call (if at all).
4416 self->ClearException();
4417 }
4418 // Change into a verify error.
4419 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004420 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004421 self->GetException()->SetCause(cause.Get());
4422 }
4423 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4424 if (Runtime::Current()->IsAotCompiler()) {
4425 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4426 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004427 // Need to grab the lock to change status.
4428 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004429 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004430 return false;
4431}
4432
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004433verifier::FailureKind ClassLinker::VerifyClass(Thread* self,
4434 verifier::VerifierDeps* verifier_deps,
4435 Handle<mirror::Class> klass,
4436 verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004437 {
4438 // TODO: assert that the monitor on the Class is held
4439 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004440
Andreas Gampe884f3b82016-03-30 19:52:58 -07004441 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004442 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004443 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004444 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004445 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4446 // case we may see the same status again. b/62912904. This is why the check is
4447 // greater or equal.
4448 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004449 << "Class '" << klass->PrettyClass()
4450 << "' performed an illegal verification state transition from " << old_status
4451 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004452 old_status = klass->GetStatus();
4453 }
jeffhao98eacac2011-09-14 16:11:53 -07004454
Andreas Gampe884f3b82016-03-30 19:52:58 -07004455 // The class might already be erroneous, for example at compile time if we attempted to verify
4456 // this class as a parent to another.
4457 if (klass->IsErroneous()) {
4458 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004459 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004460 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004461
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004462 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004463 if (klass->IsVerified()) {
Nicolas Geoffray80789962021-04-30 16:50:39 +01004464 if (verifier_deps != nullptr &&
4465 verifier_deps->ContainsDexFile(klass->GetDexFile()) &&
4466 !verifier_deps->HasRecordedVerifiedStatus(klass->GetDexFile(), *klass->GetClassDef()) &&
4467 !Runtime::Current()->IsAotCompiler()) {
4468 // If the klass is verified, but `verifier_deps` did not record it, this
4469 // means we are running background verification of a secondary dex file.
4470 // Re-run the verifier to populate `verifier_deps`.
4471 // No need to run the verification when running on the AOT Compiler, as
4472 // the driver handles those multithreaded cases already.
4473 std::string error_msg;
4474 verifier::FailureKind failure =
4475 PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
4476 // We could have soft failures, so just check that we don't have a hard
4477 // failure.
4478 DCHECK_NE(failure, verifier::FailureKind::kHardFailure) << error_msg;
4479 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004480 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004481 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004482
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004483 if (klass->IsVerifiedNeedsAccessChecks()) {
4484 if (!Runtime::Current()->IsAotCompiler()) {
4485 // Mark the class as having a verification attempt to avoid re-running
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004486 // the verifier.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004487 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4488 }
4489 return verifier::FailureKind::kAccessChecksFailure;
4490 }
4491
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004492 // For AOT, don't attempt to re-verify if we have already found we should
4493 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004494 if (klass->ShouldVerifyAtRuntime()) {
4495 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004496 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004497 }
jeffhao98eacac2011-09-14 16:11:53 -07004498
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004499 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4500 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004501
4502 // Skip verification if disabled.
4503 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004504 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004505 UpdateClassAfterVerification(klass, image_pointer_size_, verifier::FailureKind::kNoFailure);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004506 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004507 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004508 }
4509
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004510 VLOG(class_linker) << "Beginning verification for class: "
4511 << klass->PrettyDescriptor()
4512 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4513
Ian Rogers9ffb0392012-09-10 11:56:50 -07004514 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004515 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004516 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4517 // If we have a superclass and we get a hard verification failure we can return immediately.
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004518 if (supertype != nullptr &&
4519 !AttemptSupertypeVerification(self, verifier_deps, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004520 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004521 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004522 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004523
Alex Lightf1f10492015-10-07 16:08:36 -07004524 // Verify all default super-interfaces.
4525 //
4526 // (1) Don't bother if the superclass has already had a soft verification failure.
4527 //
4528 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4529 // recursive initialization by themselves. This is because when an interface is initialized
4530 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4531 // but choose not to for an optimization. If the interfaces is being verified due to a class
4532 // initialization (which would need all the default interfaces to be verified) the class code
4533 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004534 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004535 && !klass->IsInterface()) { // See (2)
4536 int32_t iftable_count = klass->GetIfTableCount();
4537 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4538 // Loop through all interfaces this class has defined. It doesn't matter the order.
4539 for (int32_t i = 0; i < iftable_count; i++) {
4540 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004541 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004542 // We only care if we have default interfaces and can skip if we are already verified...
4543 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4544 continue;
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004545 } else if (UNLIKELY(!AttemptSupertypeVerification(self, verifier_deps, klass, iface))) {
Alex Lightf1f10492015-10-07 16:08:36 -07004546 // We had a hard failure while verifying this interface. Just return immediately.
4547 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004548 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004549 } else if (UNLIKELY(!iface->IsVerified())) {
4550 // We softly failed to verify the iface. Stop checking and clean up.
4551 // Put the iface into the supertype handle so we know what caused us to fail.
4552 supertype.Assign(iface.Get());
4553 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004554 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004555 }
4556 }
4557
Alex Lightf1f10492015-10-07 16:08:36 -07004558 // At this point if verification failed, then supertype is the "first" supertype that failed
4559 // verification (without a specific order). If verification succeeded, then supertype is either
4560 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004561 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004562 supertype.Get() == klass->GetSuperClass() ||
4563 !supertype->IsVerified());
4564
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004565 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004566 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004567 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004568 bool preverified = VerifyClassUsingOatFile(self, dex_file, klass, oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004569
4570 VLOG(class_linker) << "Class preverified status for class "
4571 << klass->PrettyDescriptor()
4572 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4573 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004574 << preverified
4575 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004576
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004577 // If the oat file says the class had an error, re-run the verifier. That way we will either:
4578 // 1) Be successful at runtime, or
4579 // 2) Get a precise error message.
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00004580 DCHECK_IMPLIES(mirror::Class::IsErroneous(oat_file_class_status), !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004581
Ian Rogers62d6c772013-02-27 08:32:07 -08004582 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004583 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004584 if (!preverified) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004585 verifier_failure = PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004586 } else if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks) {
4587 verifier_failure = verifier::FailureKind::kAccessChecksFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004588 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004589
4590 // Verification is done, grab the lock again.
4591 ObjectLock<mirror::Class> lock(self, klass);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004592 self->AssertNoPendingException();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004593
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004594 if (verifier_failure == verifier::FailureKind::kHardFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004595 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004596 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4597 << " because: " << error_msg;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004598 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004599 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004600 return verifier_failure;
jeffhao5cfd6fb2011-09-27 13:54:29 -07004601 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004602
4603 // Make sure all classes referenced by catch blocks are resolved.
4604 ResolveClassExceptionHandlerTypes(klass);
4605
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004606 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004607 if (supertype != nullptr && supertype->ShouldVerifyAtRuntime()) {
4608 // Regardless of our own verification result, we need to verify the class
4609 // at runtime if the super class is not verified. This is required in case
4610 // we generate an app/boot image.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004611 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4612 } else if (verifier_failure == verifier::FailureKind::kNoFailure) {
4613 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4614 } else if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4615 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
4616 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4617 } else {
4618 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4619 }
4620 // Notify the compiler about the verification status, in case the class
4621 // was verified implicitly (eg super class of a compiled class). When the
4622 // compiler unloads dex file after compilation, we still want to keep
4623 // verification states.
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004624 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4625 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004626 } else {
4627 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004628 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004629
4630 UpdateClassAfterVerification(klass, image_pointer_size_, verifier_failure);
Nicolas Geoffray08025182016-10-25 17:20:18 +01004631 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004632}
4633
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004634verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004635 verifier::VerifierDeps* verifier_deps,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004636 Handle<mirror::Class> klass,
4637 verifier::HardFailLogMode log_level,
4638 std::string* error_msg) {
4639 Runtime* const runtime = Runtime::Current();
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004640 StackHandleScope<2> hs(self);
4641 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4642 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004643 return verifier::ClassVerifier::VerifyClass(self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004644 verifier_deps,
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004645 dex_cache->GetDexFile(),
4646 klass,
4647 dex_cache,
4648 class_loader,
4649 *klass->GetClassDef(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004650 runtime->GetCompilerCallbacks(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004651 log_level,
4652 Runtime::Current()->GetTargetSdkVersion(),
4653 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004654}
4655
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004656bool ClassLinker::VerifyClassUsingOatFile(Thread* self,
4657 const DexFile& dex_file,
4658 Handle<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004659 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004660 // If we're compiling, we can only verify the class using the oat file if
4661 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004662 // the compilation unit (app - dependencies). We will let the compiler callback
4663 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004664 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004665 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004666 // We are compiling an app (not the image).
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004667 if (!callbacks->CanUseOatStatusForVerification(klass.Get())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004668 return false;
4669 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004670 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004671
Andreas Gampeb40d3612018-06-26 15:49:42 -07004672 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004673 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004674 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004675 return false;
4676 }
4677
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004678 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004679 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004680 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004681 return true;
4682 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004683 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4684 // We return that the clas has already been verified, and the caller should
4685 // check the class status to ensure we run with access checks.
4686 return true;
4687 }
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004688
4689 // Check the class status with the vdex file.
4690 const OatFile* oat_file = oat_dex_file->GetOatFile();
4691 if (oat_file != nullptr) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004692 ClassStatus vdex_status = oat_file->GetVdexFile()->ComputeClassStatus(self, klass);
4693 if (vdex_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
Nicolas Geoffray327cfcf2021-10-12 14:13:25 +01004694 VLOG(verifier) << "Vdex verification success for " << klass->PrettyClass();
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004695 oat_file_class_status = vdex_status;
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004696 return true;
4697 }
4698 }
4699
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004700 // If we only verified a subset of the classes at compile time, we can end up with classes that
4701 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004702 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004703 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004704 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004705 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4706 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4707 << klass->PrettyClass() << " " << dex_file.GetLocation();
4708
Vladimir Marko72ab6842017-01-20 19:32:50 +00004709 if (mirror::Class::IsErroneous(oat_file_class_status)) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004710 // Compile time verification failed with a hard error. We'll re-run
4711 // verification, which might be successful at runtime.
jeffhao1ac29442012-03-26 11:37:32 -07004712 return false;
4713 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004714 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004715 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4716 // not loading the class.
4717 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4718 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004719 return false;
4720 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004721 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004722 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004723 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004724 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004725 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004726}
4727
Alex Light5a559862016-01-29 12:24:48 -08004728void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004729 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004730 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004731 }
4732}
4733
Alex Light5a559862016-01-29 12:24:48 -08004734void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004735 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004736 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004737 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004738 return; // native or abstract method
4739 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004740 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004741 return; // nothing to process
4742 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004743 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004744 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004745 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4746 CatchHandlerIterator iterator(handlers_ptr);
4747 for (; iterator.HasNext(); iterator.Next()) {
4748 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4749 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004750 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004751 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004752 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004753 DCHECK(Thread::Current()->IsExceptionPending());
4754 Thread::Current()->ClearException();
4755 }
4756 }
4757 }
4758 handlers_ptr = iterator.EndDataPointer();
4759 }
4760}
4761
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004762ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4763 jstring name,
4764 jobjectArray interfaces,
4765 jobject loader,
4766 jobjectArray methods,
4767 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004768 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004769
4770 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4771 // code to be executed. We put it up here so we can avoid all the allocations associated with
4772 // creating the class. This can happen with (eg) jit-threads.
4773 if (!self->CanLoadClasses()) {
4774 // Make sure we don't try to load anything, potentially causing an infinite loop.
4775 ObjPtr<mirror::Throwable> pre_allocated =
4776 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4777 self->SetException(pre_allocated);
4778 return nullptr;
4779 }
4780
Alex Light133987d2020-03-26 19:22:12 +00004781 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004782 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004783 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004784 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004785 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004786 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004787 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004788 DCHECK(temp_klass->GetClass() != nullptr);
4789 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004790 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4791 // the methods.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004792 temp_klass->SetAccessFlagsDuringLinking(kAccClassIsProxy | kAccPublic | kAccFinal);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004793 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4794 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4795 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004796 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004797 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004798 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004799 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004800 std::string storage;
4801 const char* descriptor = temp_klass->GetDescriptor(&storage);
4802 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004803
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004804 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004805 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004806
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004807 // Insert the class before loading the fields as the field roots
4808 // (ArtField::declaring_class_) are only visited from the class
4809 // table. There can't be any suspend points between inserting the
4810 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004811 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004812 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004813
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004814 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004815 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004816 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004817 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004818
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004819 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4820 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004821 ArtField& interfaces_sfield = sfields->At(0);
4822 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004823 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004824 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004825
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004826 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004827 ArtField& throws_sfield = sfields->At(1);
4828 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004829 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004830 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004831
Ian Rogers466bb252011-10-14 03:29:56 -07004832 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004833 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004834
Alex Light133987d2020-03-26 19:22:12 +00004835 // The array we get passed contains all methods, including private and static
4836 // ones that aren't proxied. We need to filter those out since only interface
4837 // methods (non-private & virtual) are actually proxied.
4838 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4839 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004840 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004841 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004842 // List of the actual virtual methods this class will have.
4843 std::vector<ArtMethod*> proxied_methods;
4844 std::vector<size_t> proxied_throws_idx;
4845 proxied_methods.reserve(h_methods->GetLength());
4846 proxied_throws_idx.reserve(h_methods->GetLength());
4847 // Filter out to only the non-private virtual methods.
4848 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4849 ArtMethod* m = mirror->GetArtMethod();
4850 if (!m->IsPrivate() && !m->IsStatic()) {
4851 proxied_methods.push_back(m);
4852 proxied_throws_idx.push_back(idx);
4853 }
4854 }
4855 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004856 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4857 // contains an array of all the classes each function is declared to throw.
4858 // This is used to wrap unexpected exceptions in a
4859 // UndeclaredThrowableException exception. This array is in the same order as
4860 // the methods array and like the methods array must be filtered to remove any
4861 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004862 const bool has_filtered_methods =
4863 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4864 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4865 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4866 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4867 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4868 (has_filtered_methods)
4869 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4870 self, original_proxied_throws->GetClass(), num_virtual_methods)
4871 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004872 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4873 self->AssertPendingOOMException();
4874 return nullptr;
4875 }
Alex Light133987d2020-03-26 19:22:12 +00004876 if (has_filtered_methods) {
4877 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
4878 DCHECK_LE(new_idx, orig_idx);
4879 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
4880 }
4881 }
Alex Lighte64300b2015-12-15 15:02:47 -08004882
4883 // Create the methods array.
4884 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4885 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004886 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4887 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004888 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004889 self->AssertPendingOOMException();
4890 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004891 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004892 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004893
4894 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004895 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004896
4897 // Create virtual method using specified prototypes.
4898 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004899 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004900 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004901 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004902 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004903 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4904 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004905 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004906
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004907 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004908 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004909 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004910 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004911 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004912
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004913 // At this point the class is loaded. Publish a ClassLoad event.
4914 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4915 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4916
4917 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004918 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004919 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004920 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004921 // Link the fields and virtual methods, creating vtable and iftables.
4922 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004923 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004924 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004925 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Markoa4d28dd2021-06-30 11:28:06 +01004926 if (!temp_klass->IsErroneous()) {
4927 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
4928 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004929 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004930 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004931 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004932 CHECK(temp_klass->IsRetired());
4933 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004934
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004935 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004936 interfaces_sfield.SetObject<false>(
4937 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004938 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004939 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4940 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004941 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00004942 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004943
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004944 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4945
Vladimir Marko305c38b2018-02-14 11:50:07 +00004946 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4947 // See also ClassLinker::EnsureInitialized().
4948 if (kBitstringSubtypeCheckEnabled) {
4949 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4950 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4951 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4952 }
4953
Vladimir Markobf121912019-06-04 13:49:05 +01004954 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004955 {
4956 // Lock on klass is released. Lock new class object.
4957 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Markobf121912019-06-04 13:49:05 +01004958 // Conservatively go through the ClassStatus::kInitialized state.
4959 callback = MarkClassInitialized(self, klass);
4960 }
4961 if (callback != nullptr) {
4962 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07004963 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004964
David Srbecky346fd962020-07-27 16:51:00 +01004965 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07004966 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004967 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004968 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4969
Ian Rogersc2b44472011-12-14 21:17:17 -08004970 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004971 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004972 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08004973 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004974
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004975 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004976 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004977 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004978 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004979 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004980
4981 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004982 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004983 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004984
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004985 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004986 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004987 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00004988 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004989 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004990 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004991}
4992
Mathieu Chartiere401d142015-04-22 13:56:20 -07004993void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4994 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004995 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4996 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004997
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004998 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4999 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005000 ArtMethod* proxy_constructor =
5001 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005002 DCHECK(proxy_constructor != nullptr)
5003 << "Could not find <init> method in java.lang.reflect.Proxy";
5004
Jeff Haodb8a6642014-08-14 17:18:52 -07005005 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5006 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005007 DCHECK(out != nullptr);
5008 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005009 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005010 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005011 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005012 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5013 kAccPublic |
5014 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005015 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005016
5017 // Set the original constructor method.
5018 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005019}
5020
Mathieu Chartiere401d142015-04-22 13:56:20 -07005021void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005022 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005023 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5024 CHECK_STREQ(np->GetName(), "<init>");
5025 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005026 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005027}
5028
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005029void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005030 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005031 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005032 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005033 DCHECK(out != nullptr);
5034 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005035
Alex Lighte9dd04f2016-03-16 16:09:45 -07005036 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005037 out->SetDeclaringClass(klass.Get());
Vladimir Markode0d0de2021-03-18 14:12:35 +00005038 // Clear the abstract and default flags to ensure that defaults aren't picked in
Alex Lighte9dd04f2016-03-16 16:09:45 -07005039 // preference to the invocation handler.
Vladimir Markode0d0de2021-03-18 14:12:35 +00005040 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005041 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005042 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5043 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005044 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5045
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005046 // Set the original interface method.
5047 out->SetDataPtrSize(prototype, image_pointer_size_);
5048
Ian Rogers466bb252011-10-14 03:29:56 -07005049 // At runtime the method looks like a reference and argument saving method, clone the code
5050 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005051 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005052}
Jesse Wilson95caa792011-10-12 18:14:17 -04005053
Mathieu Chartiere401d142015-04-22 13:56:20 -07005054void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005055 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005056 CHECK(!prototype->IsFinal());
5057 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005058 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005059
5060 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5061 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005062 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005063 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005064}
5065
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005066bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005067 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005068 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005069 return true;
5070 }
5071 if (!can_init_statics) {
5072 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005073 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005074 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005075 return false;
5076 }
5077 // Check if there are encoded static values needing initialization.
5078 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005079 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005080 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005081 if (dex_class_def->static_values_off_ != 0) {
5082 return false;
5083 }
5084 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005085 }
5086 // If we are a class we need to initialize all interfaces with default methods when we are
5087 // initialized. Check all of them.
5088 if (!klass->IsInterface()) {
5089 size_t num_interfaces = klass->GetIfTableCount();
5090 for (size_t i = 0; i < num_interfaces; i++) {
5091 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5092 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5093 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005094 return false;
5095 }
5096 }
5097 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005098 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005099 if (klass->IsInterface() || !klass->HasSuperClass()) {
5100 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005101 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005102 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005103 if (super_class->IsInitialized()) {
5104 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005105 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005106 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005107}
5108
Mathieu Chartier23369542020-03-04 08:24:11 -08005109bool ClassLinker::InitializeClass(Thread* self,
5110 Handle<mirror::Class> klass,
5111 bool can_init_statics,
5112 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005113 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5114
5115 // Are we already initialized and therefore done?
5116 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5117 // an initialized class will never change its state.
5118 if (klass->IsInitialized()) {
5119 return true;
5120 }
5121
5122 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005123 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005124 return false;
5125 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005126
Ian Rogers7b078e82014-09-10 14:44:24 -07005127 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005128 Runtime* const runtime = Runtime::Current();
5129 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005130 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005131 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005132 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005133
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005134 // Re-check under the lock in case another thread initialized ahead of us.
5135 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005136 return true;
5137 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005138
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005139 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005140 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005141 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005142 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005143 return false;
5144 }
5145
Vladimir Marko72ab6842017-01-20 19:32:50 +00005146 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5147 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005148
5149 if (!klass->IsVerified()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00005150 VerifyClass(self, /*verifier_deps= */ nullptr, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005151 if (!klass->IsVerified()) {
5152 // We failed to verify, expect either the klass to be erroneous or verification failed at
5153 // compile time.
5154 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005155 // The class is erroneous. This may be a verifier error, or another thread attempted
5156 // verification and/or initialization and failed. We can distinguish those cases by
5157 // whether an exception is already pending.
5158 if (self->IsExceptionPending()) {
5159 // Check that it's a VerifyError.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +01005160 DCHECK(IsVerifyError(self->GetException()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005161 } else {
5162 // Check that another thread attempted initialization.
5163 DCHECK_NE(0, klass->GetClinitThreadId());
5164 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5165 // Need to rethrow the previous failure now.
5166 ThrowEarlierClassFailure(klass.Get(), true);
5167 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005168 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005169 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005170 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005171 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005172 self->AssertNoPendingException();
5173 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005174 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005175 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005176 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005177 } else {
5178 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005179 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005180
5181 // A separate thread could have moved us all the way to initialized. A "simple" example
5182 // involves a subclass of the current class being initialized at the same time (which
5183 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005184 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005185 if (klass->IsInitialized()) {
5186 return true;
5187 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005188 }
5189
Vladimir Marko2c64a832018-01-04 11:31:56 +00005190 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005191 // initializing higher up the stack or another thread has beat us
5192 // to initializing and we need to wait. Either way, this
5193 // invocation of InitializeClass will not be responsible for
5194 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005195 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005196 // Could have got an exception during verification.
5197 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005198 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005199 return false;
5200 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005201 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005202 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005203 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005204 return true;
5205 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005206 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005207 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005208 }
5209
Jeff Haoe2e40342017-07-19 10:45:18 -07005210 // Try to get the oat class's status for this class if the oat file is present. The compiler
5211 // tries to validate superclass descriptors, and writes the result into the oat file.
5212 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5213 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5214 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005215 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005216 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5217 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5218 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005219 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005220 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005221 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005222 return false;
5223 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005224 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005225
Vladimir Marko2c64a832018-01-04 11:31:56 +00005226 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005227 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005228
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005229 // From here out other threads may observe that we're initializing and so changes of state
5230 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005231 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005232 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005233
Mathieu Chartier23369542020-03-04 08:24:11 -08005234 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005235 }
5236
Andreas Gampeaf864702019-07-23 14:05:35 -07005237 uint64_t t_sub = 0;
5238
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005239 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005240 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005241 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005242 if (!super_class->IsInitialized()) {
5243 CHECK(!super_class->IsInterface());
5244 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005245 StackHandleScope<1> hs(self);
5246 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005247 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005248 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005249 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005250 if (!super_initialized) {
5251 // The super class was verified ahead of entering initializing, we should only be here if
5252 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005253 // For the case of aot compiler, the super class might also be initializing but we don't
5254 // want to process circular dependencies in pre-compile.
5255 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005256 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005257 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005258 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005259 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005260 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005261 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005262 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005263 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005264 return false;
5265 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005266 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005267 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005268 }
5269
Alex Lighteb7c1442015-08-31 13:17:42 -07005270 if (!klass->IsInterface()) {
5271 // Initialize interfaces with default methods for the JLS.
5272 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005273 // Only setup the (expensive) handle scope if we actually need to.
5274 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005275 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005276 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5277 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005278 handle_scope_iface.Assign(klass->GetDirectInterface(i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005279 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005280 CHECK(handle_scope_iface->IsInterface());
5281 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5282 // We have already done this for this interface. Skip it.
5283 continue;
5284 }
5285 // We cannot just call initialize class directly because we need to ensure that ALL
5286 // interfaces with default methods are initialized. Non-default interface initialization
5287 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005288 // This is not very precise, misses all walking.
5289 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005290 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5291 handle_scope_iface,
5292 can_init_statics,
5293 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005294 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005295 if (!iface_initialized) {
5296 ObjectLock<mirror::Class> lock(self, klass);
5297 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005298 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005299 return false;
5300 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005301 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005302 }
5303 }
5304 }
5305
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005306 const size_t num_static_fields = klass->NumStaticFields();
5307 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005308 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005309 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005310 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005311 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005312 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005313
5314 // Eagerly fill in static fields so that the we don't have to do as many expensive
5315 // Class::FindStaticField in ResolveField.
5316 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005317 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005318 const uint32_t field_idx = field->GetDexFieldIndex();
David Srbecky5de5efe2021-02-15 21:23:00 +00005319 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005320 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005321 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005322 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5323 field,
5324 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5325 hiddenapi::AccessMethod::kNone));
David Srbecky5de5efe2021-02-15 21:23:00 +00005326 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005327 } else {
5328 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005329 }
5330 }
5331
Vladimir Markoe11dd502017-12-08 14:09:45 +00005332 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5333 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005334 this,
5335 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005336 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005337
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005338 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005339 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005340 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005341 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5342 if (!value_it.HasNext()) {
5343 break;
5344 }
5345 ArtField* art_field = ResolveField(field.GetIndex(),
5346 dex_cache,
5347 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005348 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005349 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005350 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005351 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005352 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005353 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005354 if (self->IsExceptionPending()) {
5355 break;
5356 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005357 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005358 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005359 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005360 }
5361 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005362
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005363
Mathieu Chartierda595be2016-08-10 13:57:39 -07005364 if (!self->IsExceptionPending()) {
5365 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5366 if (clinit != nullptr) {
5367 CHECK(can_init_statics);
5368 JValue result;
5369 clinit->Invoke(self, nullptr, 0, &result, "V");
5370 }
5371 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005372 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005373 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005374
Vladimir Markobf121912019-06-04 13:49:05 +01005375 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005376 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005377 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005378 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005379
5380 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005381 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005382 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005383 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005384 } else if (Runtime::Current()->IsTransactionAborted()) {
5385 // The exception thrown when the transaction aborted has been caught and cleared
5386 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005387 VLOG(compiler) << "Return from class initializer of "
5388 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005389 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005390 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005391 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005392 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005393 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005394 if (stats_enabled) {
5395 RuntimeStats* global_stats = runtime->GetStats();
5396 RuntimeStats* thread_stats = self->GetStats();
5397 ++global_stats->class_init_count;
5398 ++thread_stats->class_init_count;
5399 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5400 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5401 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005402 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005403 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005404 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005405 std::string temp;
5406 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005407 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005408 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005409 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005410 }
Vladimir Markobf121912019-06-04 13:49:05 +01005411 if (callback != nullptr) {
5412 callback->MakeVisible(self);
5413 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005414 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005415}
5416
Alex Lighteb7c1442015-08-31 13:17:42 -07005417// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5418// and perform the initialization only on those interfaces that contain default methods.
5419bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5420 Handle<mirror::Class> iface,
5421 bool can_init_statics,
5422 bool can_init_parents) {
5423 CHECK(iface->IsInterface());
5424 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005425 // Only create the (expensive) handle scope if we need it.
5426 if (UNLIKELY(num_direct_ifaces > 0)) {
5427 StackHandleScope<1> hs(self);
5428 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5429 // First we initialize all of iface's super-interfaces recursively.
5430 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005431 ObjPtr<mirror::Class> super_iface = iface->GetDirectInterface(i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005432 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005433 if (!super_iface->HasBeenRecursivelyInitialized()) {
5434 // Recursive step
5435 handle_super_iface.Assign(super_iface);
5436 if (!InitializeDefaultInterfaceRecursive(self,
5437 handle_super_iface,
5438 can_init_statics,
5439 can_init_parents)) {
5440 return false;
5441 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005442 }
5443 }
5444 }
5445
5446 bool result = true;
5447 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5448 // initialize if we don't have default methods.
5449 if (iface->HasDefaultMethods()) {
5450 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5451 }
5452
5453 // Mark that this interface has undergone recursive default interface initialization so we know we
5454 // can skip it on any later class initializations. We do this even if we are not a default
5455 // interface since we can still avoid the traversal. This is purely a performance optimization.
5456 if (result) {
5457 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005458 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5459 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5460 // initialization is a performance optimization (to avoid another idempotent visit
5461 // for other implementing classes/interfaces), and can be revisited later.
5462 ObjectTryLock<mirror::Class> lock(self, iface);
5463 if (lock.Acquired()) {
5464 iface->SetRecursivelyInitialized();
5465 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005466 }
5467 return result;
5468}
5469
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005470bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5471 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005472 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005473 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005474 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005475 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005476 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005477 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005478
5479 // When we wake up, repeat the test for init-in-progress. If
5480 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005481 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005482 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005483 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005484 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005485 return false;
5486 }
5487 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005488 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005489 continue;
5490 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005491 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005492 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005493 // Compile time initialization failed.
5494 return false;
5495 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005496 if (klass->IsErroneous()) {
5497 // The caller wants an exception, but it was thrown in a
5498 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005499 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005500 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005501 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005502 return false;
5503 }
5504 if (klass->IsInitialized()) {
5505 return true;
5506 }
David Sehr709b0702016-10-13 09:12:37 -07005507 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005508 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005509 }
Ian Rogers07140832014-09-30 15:43:59 -07005510 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005511}
5512
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005513static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5514 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005515 ArtMethod* method,
5516 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005517 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005518 DCHECK(Thread::Current()->IsExceptionPending());
5519 DCHECK(!m->IsProxyMethod());
5520 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005521 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5522 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005523 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005524 std::string return_type = dex_file->PrettyType(return_type_idx);
5525 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005526 ThrowWrappedLinkageError(klass.Get(),
5527 "While checking class %s method %s signature against %s %s: "
5528 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005529 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5530 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005531 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005532 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005533 return_type.c_str(), class_loader.c_str());
5534}
5535
5536static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5537 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005538 ArtMethod* method,
5539 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005540 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005541 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005542 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005543 DCHECK(Thread::Current()->IsExceptionPending());
5544 DCHECK(!m->IsProxyMethod());
5545 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005546 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5547 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005548 ThrowWrappedLinkageError(klass.Get(),
5549 "While checking class %s method %s signature against %s %s: "
5550 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005551 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5552 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005553 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005554 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005555 index, arg_type.c_str(), class_loader.c_str());
5556}
5557
5558static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5559 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005560 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005561 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005562 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005563 ThrowLinkageError(klass.Get(),
5564 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005565 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5566 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005567 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005568 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005569 error_msg.c_str());
5570}
5571
Ian Rogersb5fb2072014-12-02 17:22:02 -08005572static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005573 Handle<mirror::Class> klass,
5574 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005575 ArtMethod* method1,
5576 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005577 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005578 {
5579 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005580 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005581 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005582 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005583 return false;
5584 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005585 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005586 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005587 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005588 return false;
5589 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005590 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005591 ThrowSignatureMismatch(klass, super_klass, method1,
5592 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005593 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005594 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005595 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005596 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005597 return false;
5598 }
5599 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005600 const dex::TypeList* types1 = method1->GetParameterTypeList();
5601 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005602 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005603 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005604 ThrowSignatureMismatch(klass, super_klass, method1,
5605 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005606 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005607 return false;
5608 }
5609 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005610 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005611 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005612 ThrowSignatureMismatch(klass, super_klass, method1,
5613 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005614 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005615 return false;
5616 }
5617 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005618 }
5619 uint32_t num_types = types1->Size();
5620 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005621 ThrowSignatureMismatch(klass, super_klass, method1,
5622 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005623 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005624 return false;
5625 }
5626 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005627 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005628 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005629 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005630 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005631 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005632 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005633 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005634 return false;
5635 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005636 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005637 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005638 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005639 if (UNLIKELY(other_param_type == nullptr)) {
5640 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005641 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005642 return false;
5643 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005644 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005645 ThrowSignatureMismatch(klass, super_klass, method1,
5646 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5647 i,
David Sehr709b0702016-10-13 09:12:37 -07005648 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005649 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005650 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005651 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005652 return false;
5653 }
5654 }
5655 return true;
5656}
5657
5658
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005659bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005660 if (klass->IsInterface()) {
5661 return true;
5662 }
Ian Rogers151f2212014-05-06 11:27:27 -07005663 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005664 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005665 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005666 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005667 if (klass->HasSuperClass() &&
5668 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005669 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005670 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005671 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5672 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5673 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005674 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5675 klass,
5676 super_klass,
5677 m,
5678 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005679 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005680 return false;
5681 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005682 }
5683 }
5684 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005685 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005686 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5687 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5688 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005689 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005690 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5691 j, image_pointer_size_);
5692 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5693 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005694 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5695 klass,
5696 super_klass,
5697 m,
5698 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005699 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005700 return false;
5701 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005702 }
5703 }
5704 }
5705 }
5706 return true;
5707}
5708
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005709bool ClassLinker::EnsureInitialized(Thread* self,
5710 Handle<mirror::Class> c,
5711 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005712 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005713 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005714
Mathieu Chartier524507a2014-08-27 15:28:28 -07005715 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005716 // If we've seen an initialized but not visibly initialized class
5717 // many times, request visible initialization.
5718 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5719 // Thanks to the x86 memory model classes skip the initialized status.
5720 DCHECK(c->IsVisiblyInitialized());
5721 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5722 if (self->IncrementMakeVisiblyInitializedCounter()) {
5723 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5724 }
5725 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07005726 return true;
5727 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005728 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5729 //
5730 // Ensure the bitstring is initialized before any of the class initialization
5731 // logic occurs. Once a class initializer starts running, objects can
5732 // escape into the heap and use the subtype checking code.
5733 //
5734 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5735 // can be used as a source for the IsSubClass check, and that all ancestors
5736 // of the class are Assigned (can be used as a target for IsSubClass check)
5737 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005738 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005739 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005740 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005741 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5742 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005743 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005744 if (!success) {
5745 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005746 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Vladimir Markoac576912021-03-31 11:16:22 +01005747 } else {
5748 // There may or may not be an exception pending. If there is, clear it.
5749 // We propagate the exception only if we can initialize fields and parents.
5750 self->ClearException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005751 }
5752 } else {
5753 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005754 }
5755 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005756}
5757
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005758void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5759 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005760 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005761 for (ArtField& field : new_class->GetIFields()) {
5762 if (field.GetDeclaringClass() == temp_class) {
5763 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005764 }
5765 }
5766
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005767 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005768 for (ArtField& field : new_class->GetSFields()) {
5769 if (field.GetDeclaringClass() == temp_class) {
5770 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005771 }
5772 }
5773
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005774 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005775 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005776 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005777 if (method.GetDeclaringClass() == temp_class) {
5778 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005779 }
5780 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005781
5782 // Make sure the remembered set and mod-union tables know that we updated some of the native
5783 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005784 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005785}
5786
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005787void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005788 CHECK(class_loader->GetAllocator() == nullptr);
5789 CHECK(class_loader->GetClassTable() == nullptr);
5790 Thread* const self = Thread::Current();
5791 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005792 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005793 // Create and set the class table.
5794 data.class_table = new ClassTable;
5795 class_loader->SetClassTable(data.class_table);
5796 // Create and set the linear allocator.
5797 data.allocator = Runtime::Current()->CreateLinearAlloc();
5798 class_loader->SetAllocator(data.allocator);
5799 // Add to the list so that we know to free the data later.
5800 class_loaders_.push_back(data);
5801}
5802
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005803ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005804 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005805 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005806 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005807 ClassTable* class_table = class_loader->GetClassTable();
5808 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005809 RegisterClassLoader(class_loader);
5810 class_table = class_loader->GetClassTable();
5811 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005812 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005813 return class_table;
5814}
5815
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005816ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005817 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005818}
5819
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005820static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005821 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005822 while (klass->HasSuperClass()) {
5823 klass = klass->GetSuperClass();
5824 if (klass->ShouldHaveImt()) {
5825 return klass->GetImt(pointer_size);
5826 }
5827 }
5828 return nullptr;
5829}
5830
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005831bool ClassLinker::LinkClass(Thread* self,
5832 const char* descriptor,
5833 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005834 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005835 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005836 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005837
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005838 if (!LinkSuperClass(klass)) {
5839 return false;
5840 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005841 ArtMethod* imt_data[ImTable::kSize];
5842 // If there are any new conflicts compared to super class.
5843 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005844 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005845 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005846 return false;
5847 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005848 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005849 return false;
5850 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005851 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005852 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005853 return false;
5854 }
5855 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005856 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005857
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005858 ImTable* imt = nullptr;
5859 if (klass->ShouldHaveImt()) {
5860 // If there are any new conflicts compared to the super class we can not make a copy. There
5861 // can be cases where both will have a conflict method at the same slot without having the same
5862 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5863 // will possibly create a table that is incorrect for either of the classes.
5864 // Same IMT with new_conflict does not happen very often.
5865 if (!new_conflict) {
5866 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5867 if (super_imt != nullptr) {
5868 bool imt_equals = true;
5869 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5870 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5871 }
5872 if (imt_equals) {
5873 imt = super_imt;
5874 }
5875 }
5876 }
5877 if (imt == nullptr) {
5878 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5879 imt = reinterpret_cast<ImTable*>(
5880 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5881 if (imt == nullptr) {
5882 return false;
5883 }
5884 imt->Populate(imt_data, image_pointer_size_);
5885 }
5886 }
5887
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005888 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5889 // We don't need to retire this class as it has no embedded tables or it was created the
5890 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005891 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005892
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005893 if (klass->ShouldHaveEmbeddedVTable()) {
5894 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005895 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005896 if (klass->ShouldHaveImt()) {
5897 klass->SetImt(imt, image_pointer_size_);
5898 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005899
5900 // Update CHA info based on whether we override methods.
5901 // Have to do this before setting the class as resolved which allows
5902 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005903 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005904 cha_->UpdateAfterLoadingOf(klass);
5905 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005906
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005907 // This will notify waiters on klass that saw the not yet resolved
5908 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005909 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005910 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005911 } else {
5912 CHECK(!klass->IsResolved());
5913 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005914 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01005915 Handle<mirror::Class> h_new_class =
5916 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005917 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5918 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5919 // may not see any references to the target space and clean the card for a class if another
5920 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005921 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005922 klass->SetSFieldsPtrUnchecked(nullptr);
5923 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005924 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005925 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005926 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005927 return false;
5928 }
5929
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005930 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5931 ObjectLock<mirror::Class> lock(self, h_new_class);
5932 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005933
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005934 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005935 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005936 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005937 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005938 const ObjPtr<mirror::Class> existing =
5939 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005940 if (class_loader != nullptr) {
5941 // We updated the class in the class table, perform the write barrier so that the GC knows
5942 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005943 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005944 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005945 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005946 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005947 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5948 }
5949 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005950
Mingyao Yang063fc772016-08-02 11:02:54 -07005951 // Update CHA info based on whether we override methods.
5952 // Have to do this before setting the class as resolved which allows
5953 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005954 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005955 cha_->UpdateAfterLoadingOf(h_new_class);
5956 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005957
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005958 // This will notify waiters on temp class that saw the not yet resolved class in the
5959 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005960 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005961
Vladimir Marko2c64a832018-01-04 11:31:56 +00005962 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005963 // This will notify waiters on new_class that saw the not yet resolved
5964 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005965 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005966 // Return the new class.
5967 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005968 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005969 return true;
5970}
5971
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005972bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005973 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005974 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005975 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5976 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005977 // Check that a class does not inherit from itself directly.
5978 //
5979 // TODO: This is a cheap check to detect the straightforward case
5980 // of a class extending itself (b/28685551), but we should do a
5981 // proper cycle detection on loaded classes, to detect all cases
5982 // of class circularity errors (b/28830038).
5983 if (super_class_idx == class_def.class_idx_) {
5984 ThrowClassCircularityError(klass.Get(),
5985 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005986 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005987 return false;
5988 }
5989
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005990 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005991 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005992 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005993 return false;
5994 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005995 // Verify
5996 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005997 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005998 super_class->PrettyDescriptor().c_str(),
5999 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006000 return false;
6001 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006002 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006003 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006004 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006005 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006006 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006007 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006008 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006009 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006010 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006011 DCHECK(Thread::Current()->IsExceptionPending());
6012 return false;
6013 }
6014 // Verify
6015 if (!klass->CanAccess(interface)) {
6016 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006017 ThrowIllegalAccessError(klass.Get(),
6018 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006019 interface->PrettyDescriptor().c_str(),
6020 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006021 return false;
6022 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006023 }
6024 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006025 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006026 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006027 return true;
6028}
6029
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006030bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006031 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006032 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006033 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6034 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006035 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006036 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006037 return false;
6038 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006039 return true;
6040 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006041 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006042 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006043 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006044 return false;
6045 }
6046 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006047 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006048 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6049 return false;
6050 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006051 if (super->IsFinal()) {
6052 ThrowVerifyError(klass.Get(),
6053 "Superclass %s of %s is declared final",
6054 super->PrettyDescriptor().c_str(),
6055 klass->PrettyDescriptor().c_str());
6056 return false;
6057 }
6058 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006059 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006060 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006061 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006062 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006063 return false;
6064 }
6065 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006066 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006067 super->PrettyDescriptor().c_str(),
6068 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006069 return false;
6070 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006071
Brian Carlstromf3632832014-05-20 15:36:53 -07006072 // Inherit kAccClassIsFinalizable from the superclass in case this
6073 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006074 if (super->IsFinalizable()) {
6075 klass->SetFinalizable();
6076 }
6077
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006078 // Inherit class loader flag form super class.
6079 if (super->IsClassLoaderClass()) {
6080 klass->SetClassLoaderClass();
6081 }
6082
Elliott Hughes2da50362011-10-10 16:57:08 -07006083 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006084 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006085 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006086 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006087 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006088 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006089 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006090 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006091 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006092 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006093 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006094 return false;
6095 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006096
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006097 if (kIsDebugBuild) {
6098 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006099 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006100 CHECK(super->IsResolved());
6101 super = super->GetSuperClass();
6102 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006103 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006104 return true;
6105}
6106
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006107// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6108// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6109// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006110class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006111 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006112 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006113 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006114 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006115 name_view_() {
David Sehr709b0702016-10-13 09:12:37 -07006116 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006117 }
6118
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006119 ALWAYS_INLINE std::string_view GetNameView() {
6120 if (name_view_.empty()) {
6121 name_view_ = dex_file_->StringViewByIdx(mid_->name_idx_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006122 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006123 return name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006124 }
6125
Mathieu Chartiere401d142015-04-22 13:56:20 -07006126 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006127 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006128 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006129 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006130 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006131 if (dex_file_ == other_dex_file) {
6132 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6133 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006134 return GetNameView() == other_dex_file->StringViewByIdx(other_mid.name_idx_) &&
6135 dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006136 }
6137
6138 private:
6139 // Dex file for the method to compare against.
6140 const DexFile* const dex_file_;
6141 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006142 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006143 // Lazily computed name from the dex file's strings.
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006144 std::string_view name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006145};
6146
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006147ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006148 ArtMethod* conflict_method,
6149 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006150 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006151 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006152 Runtime* const runtime = Runtime::Current();
6153 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006154
6155 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006156 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006157 ? runtime->CreateImtConflictMethod(linear_alloc)
6158 : conflict_method;
6159
6160 // Allocate a new table. Note that we will leak this table at the next conflict,
6161 // but that's a tradeoff compared to making the table fixed size.
6162 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006163 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6164 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006165 if (data == nullptr) {
6166 LOG(ERROR) << "Failed to allocate conflict table";
6167 return conflict_method;
6168 }
6169 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6170 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006171 method,
6172 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006173
6174 // Do a fence to ensure threads see the data in the table before it is assigned
6175 // to the conflict method.
6176 // Note that there is a race in the presence of multiple threads and we may leak
6177 // memory from the LinearAlloc, but that's a tradeoff compared to using
6178 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006179 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006180 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006181 return new_conflict_method;
6182}
6183
6184void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6185 ArtMethod* imt_conflict_method,
6186 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006187 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006188 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006189 // Place method in imt if entry is empty, place conflict otherwise.
6190 if (*imt_ref == unimplemented_method) {
6191 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006192 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006193 // If we are not a conflict and we have the same signature and name as the imt
6194 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006195 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6196 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006197 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006198 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006199 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006200 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006201 *imt_ref = current_method;
6202 } else {
Alex Light9139e002015-10-09 15:59:48 -07006203 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006204 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006205 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006206 } else {
6207 // Place the default conflict method. Note that there may be an existing conflict
6208 // method in the IMT, but it could be one tailored to the super class, with a
6209 // specific ImtConflictTable.
6210 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006211 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006212 }
6213}
6214
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006215void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006216 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6217 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006218 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006219 Runtime* const runtime = Runtime::Current();
6220 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6221 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006222 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006223 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006224 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006225 FillIMTFromIfTable(klass->GetIfTable(),
6226 unimplemented_method,
6227 conflict_method,
6228 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006229 /*create_conflict_tables=*/true,
6230 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006231 &new_conflict,
6232 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006233 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006234 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6235 // we can just use the same pointer.
6236 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006237 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006238 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6239 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6240 bool same = true;
6241 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6242 ArtMethod* method = imt_data[i];
6243 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6244 if (method != super_method) {
6245 bool is_conflict_table = method->IsRuntimeMethod() &&
6246 method != unimplemented_method &&
6247 method != conflict_method;
6248 // Verify conflict contents.
6249 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6250 super_method != unimplemented_method &&
6251 super_method != conflict_method;
6252 if (!is_conflict_table || !super_conflict_table) {
6253 same = false;
6254 } else {
6255 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6256 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6257 same = same && table1->Equals(table2, image_pointer_size_);
6258 }
6259 }
6260 }
6261 if (same) {
6262 imt = super_imt;
6263 }
6264 }
6265 if (imt == nullptr) {
6266 imt = klass->GetImt(image_pointer_size_);
6267 DCHECK(imt != nullptr);
6268 imt->Populate(imt_data, image_pointer_size_);
6269 } else {
6270 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006271 }
6272}
6273
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006274ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6275 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006276 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006277 void* data = linear_alloc->Alloc(Thread::Current(),
6278 ImtConflictTable::ComputeSize(count,
6279 image_pointer_size));
6280 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6281}
6282
6283ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6284 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6285}
6286
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006287void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006288 ArtMethod* unimplemented_method,
6289 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006290 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006291 bool create_conflict_tables,
6292 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006293 /*out*/bool* new_conflict,
6294 /*out*/ArtMethod** imt) {
6295 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006296 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006297 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006298 const size_t num_virtuals = interface->NumVirtualMethods();
6299 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6300 // Virtual methods can be larger than the if table methods if there are default methods.
6301 DCHECK_GE(num_virtuals, method_array_count);
6302 if (kIsDebugBuild) {
6303 if (klass->IsInterface()) {
6304 DCHECK_EQ(method_array_count, 0u);
6305 } else {
6306 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6307 }
6308 }
6309 if (method_array_count == 0) {
6310 continue;
6311 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006312 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006313 for (size_t j = 0; j < method_array_count; ++j) {
6314 ArtMethod* implementation_method =
6315 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6316 if (ignore_copied_methods && implementation_method->IsCopied()) {
6317 continue;
6318 }
6319 DCHECK(implementation_method != nullptr);
6320 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6321 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6322 // or interface methods in the IMT here they will not create extra conflicts since we compare
6323 // names and signatures in SetIMTRef.
6324 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006325 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006326
6327 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6328 // the same implementation method, keep track of this to avoid creating a conflict table in
6329 // this case.
6330
6331 // Conflict table size for each IMT slot.
6332 ++conflict_counts[imt_index];
6333
6334 SetIMTRef(unimplemented_method,
6335 imt_conflict_method,
6336 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006337 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006338 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006339 }
6340 }
6341
6342 if (create_conflict_tables) {
6343 // Create the conflict tables.
6344 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006345 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006346 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006347 if (imt[i] == imt_conflict_method) {
6348 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6349 if (new_table != nullptr) {
6350 ArtMethod* new_conflict_method =
6351 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6352 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6353 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006354 } else {
6355 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006356 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006357 }
6358 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006359 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006360 }
6361 }
6362
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006363 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006364 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006365 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6366 // Virtual methods can be larger than the if table methods if there are default methods.
6367 if (method_array_count == 0) {
6368 continue;
6369 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006370 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006371 for (size_t j = 0; j < method_array_count; ++j) {
6372 ArtMethod* implementation_method =
6373 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6374 if (ignore_copied_methods && implementation_method->IsCopied()) {
6375 continue;
6376 }
6377 DCHECK(implementation_method != nullptr);
6378 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006379 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006380 if (!imt[imt_index]->IsRuntimeMethod() ||
6381 imt[imt_index] == unimplemented_method ||
6382 imt[imt_index] == imt_conflict_method) {
6383 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006384 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006385 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6386 const size_t num_entries = table->NumEntries(image_pointer_size_);
6387 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6388 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006389 }
6390 }
6391 }
6392}
6393
Vladimir Marko78f62d82022-01-10 16:25:19 +00006394namespace {
6395
Alex Lighteb7c1442015-08-31 13:17:42 -07006396// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6397// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006398static bool NotSubinterfaceOfAny(
Vladimir Marko78f62d82022-01-10 16:25:19 +00006399 const ScopedArenaHashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006400 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006401 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006402 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006403 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006404 for (ObjPtr<mirror::Class> c : classes) {
6405 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006406 return false;
6407 }
6408 }
6409 return true;
6410}
6411
Vladimir Marko78f62d82022-01-10 16:25:19 +00006412// We record new interfaces by the index of the direct interface and the index in the
6413// direct interface's `IfTable`, or `dex::kDexNoIndex` if it's the direct interface itself.
6414struct NewInterfaceReference {
6415 uint32_t direct_interface_index;
6416 uint32_t direct_interface_iftable_index;
6417};
6418
6419class ProxyInterfacesAccessor {
6420 public:
6421 explicit ProxyInterfacesAccessor(Handle<mirror::ObjectArray<mirror::Class>> interfaces)
6422 REQUIRES_SHARED(Locks::mutator_lock_)
6423 : interfaces_(interfaces) {}
6424
6425 size_t GetLength() REQUIRES_SHARED(Locks::mutator_lock_) {
6426 return interfaces_->GetLength();
6427 }
6428
6429 ObjPtr<mirror::Class> GetInterface(size_t index) REQUIRES_SHARED(Locks::mutator_lock_) {
6430 DCHECK_LT(index, GetLength());
6431 return interfaces_->GetWithoutChecks(index);
6432 }
6433
6434 private:
6435 Handle<mirror::ObjectArray<mirror::Class>> interfaces_;
6436};
6437
6438class NonProxyInterfacesAccessor {
6439 public:
6440 NonProxyInterfacesAccessor(ClassLinker* class_linker, Handle<mirror::Class> klass)
6441 REQUIRES_SHARED(Locks::mutator_lock_)
6442 : interfaces_(klass->GetInterfaceTypeList()),
6443 class_linker_(class_linker),
6444 klass_(klass) {
6445 DCHECK(!klass->IsProxyClass());
6446 }
6447
6448 size_t GetLength() REQUIRES_SHARED(Locks::mutator_lock_) {
6449 return (interfaces_ != nullptr) ? interfaces_->Size() : 0u;
6450 }
6451
6452 ObjPtr<mirror::Class> GetInterface(size_t index) REQUIRES_SHARED(Locks::mutator_lock_) {
6453 DCHECK_LT(index, GetLength());
6454 dex::TypeIndex type_index = interfaces_->GetTypeItem(index).type_idx_;
6455 return class_linker_->LookupResolvedType(type_index, klass_.Get());
6456 }
6457
6458 private:
6459 const dex::TypeList* interfaces_;
6460 ClassLinker* class_linker_;
6461 Handle<mirror::Class> klass_;
6462};
6463
6464// Finds new interfaces to add to the interface table in addition to superclass interfaces.
Alex Lighteb7c1442015-08-31 13:17:42 -07006465//
Vladimir Marko78f62d82022-01-10 16:25:19 +00006466// Interfaces in the interface table must satisfy the following constraint:
6467// all I, J: Interface | I <: J implies J precedes I
6468// (note A <: B means that A is a subtype of B). We order this backwards so that we do not need
6469// to reorder superclass interfaces when new interfaces are added in subclass's interface tables.
Alex Lighteb7c1442015-08-31 13:17:42 -07006470//
Vladimir Marko78f62d82022-01-10 16:25:19 +00006471// This function returns a list of references for all interfaces in the transitive
6472// closure of the direct interfaces that are not in the superclass interfaces.
6473// The entries in the list are ordered to satisfy the interface table ordering
6474// constraint and therefore the interface table formed by appending them to the
6475// superclass interface table shall also satisfy that constraint.
6476template <typename InterfaceAccessor>
6477ALWAYS_INLINE
6478static ArrayRef<const NewInterfaceReference> FindNewIfTableInterfaces(
6479 ObjPtr<mirror::IfTable> super_iftable,
6480 size_t super_ifcount,
6481 ScopedArenaAllocator* allocator,
6482 InterfaceAccessor&& interfaces,
6483 ArrayRef<NewInterfaceReference> initial_storage,
6484 /*out*/ScopedArenaVector<NewInterfaceReference>* supplemental_storage)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006485 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00006486 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006487
Vladimir Marko782fb712020-12-23 12:47:31 +00006488 // This is the set of all classes already in the iftable. Used to make checking
6489 // if a class has already been added quicker.
6490 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
6491 mirror::Class* buffer[kBufferSize];
Vladimir Marko78f62d82022-01-10 16:25:19 +00006492 ScopedArenaHashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize, allocator->Adapter());
Alex Lighteb7c1442015-08-31 13:17:42 -07006493 // The first super_ifcount elements are from the superclass. We note that they are already added.
6494 for (size_t i = 0; i < super_ifcount; i++) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00006495 ObjPtr<mirror::Class> iface = super_iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006496 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006497 classes_in_iftable.Put(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07006498 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006499
6500 ArrayRef<NewInterfaceReference> current_storage = initial_storage;
6501 DCHECK_NE(current_storage.size(), 0u);
6502 size_t num_new_interfaces = 0u;
6503 auto insert_reference = [&](uint32_t direct_interface_index,
6504 uint32_t direct_interface_iface_index) {
6505 if (UNLIKELY(num_new_interfaces == current_storage.size())) {
6506 bool copy = current_storage.data() != supplemental_storage->data();
6507 supplemental_storage->resize(2u * num_new_interfaces);
6508 if (copy) {
6509 std::copy_n(current_storage.data(), num_new_interfaces, supplemental_storage->data());
6510 }
6511 current_storage = ArrayRef<NewInterfaceReference>(*supplemental_storage);
6512 }
6513 current_storage[num_new_interfaces] = {direct_interface_index, direct_interface_iface_index};
6514 ++num_new_interfaces;
6515 };
6516
6517 for (size_t i = 0, num_interfaces = interfaces.GetLength(); i != num_interfaces; ++i) {
6518 ObjPtr<mirror::Class> interface = interfaces.GetInterface(i);
Vladimir Marko782fb712020-12-23 12:47:31 +00006519
Alex Lighteb7c1442015-08-31 13:17:42 -07006520 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6521 // At this point in the loop current-iface-list has the invariant that:
6522 // for every pair of interfaces I,J within it:
6523 // if index_of(I) < index_of(J) then I is not a subtype of J
6524
6525 // If we have already seen this element then all of its super-interfaces must already be in the
6526 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00006527 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006528 // We haven't seen this interface so add all of its super-interfaces onto the
6529 // current-iface-list, skipping those already on it.
6530 int32_t ifcount = interface->GetIfTableCount();
6531 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006532 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006533 if (classes_in_iftable.find(super_interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006534 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006535 classes_in_iftable.Put(super_interface.Ptr());
6536 insert_reference(i, j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006537 }
6538 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006539 // Add this interface reference after all of its super-interfaces.
Alex Lighteb7c1442015-08-31 13:17:42 -07006540 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006541 classes_in_iftable.Put(interface.Ptr());
6542 insert_reference(i, dex::kDexNoIndex);
Alex Lighteb7c1442015-08-31 13:17:42 -07006543 } else if (kIsDebugBuild) {
6544 // Check all super-interfaces are already in the list.
6545 int32_t ifcount = interface->GetIfTableCount();
6546 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006547 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006548 DCHECK(classes_in_iftable.find(super_interface.Ptr()) != classes_in_iftable.end())
David Sehr709b0702016-10-13 09:12:37 -07006549 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6550 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006551 }
6552 }
6553 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006554 return ArrayRef<const NewInterfaceReference>(current_storage.data(), num_new_interfaces);
6555}
6556
6557template <typename InterfaceAccessor>
6558static ObjPtr<mirror::IfTable> SetupInterfaceLookupTable(
6559 Thread* self,
6560 Handle<mirror::Class> klass,
6561 ScopedArenaAllocator* allocator,
6562 InterfaceAccessor&& interfaces)
6563 REQUIRES_SHARED(Locks::mutator_lock_) {
6564 DCHECK(klass->HasSuperClass());
6565 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Vladimir Marko0441d202022-02-18 13:55:15 +00006566 DCHECK(super_iftable != nullptr);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006567 const size_t num_interfaces = interfaces.GetLength();
6568
Vladimir Marko0441d202022-02-18 13:55:15 +00006569 // If there are no new interfaces, return the interface table from superclass.
6570 // If any implementation methods are overridden, we shall copy the table and
6571 // the method arrays that contain any differences (copy-on-write).
6572 if (num_interfaces == 0) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00006573 return super_iftable;
6574 }
6575
6576 // Check that every class being implemented is an interface.
6577 for (size_t i = 0; i != num_interfaces; ++i) {
6578 ObjPtr<mirror::Class> interface = interfaces.GetInterface(i);
6579 DCHECK(interface != nullptr);
6580 if (UNLIKELY(!interface->IsInterface())) {
6581 ThrowIncompatibleClassChangeError(klass.Get(),
6582 "Class %s implements non-interface class %s",
6583 klass->PrettyDescriptor().c_str(),
6584 interface->PrettyDescriptor().c_str());
6585 return nullptr;
6586 }
6587 }
6588
6589 static constexpr size_t kMaxStackReferences = 16;
6590 NewInterfaceReference initial_storage[kMaxStackReferences];
6591 ScopedArenaVector<NewInterfaceReference> supplemental_storage(allocator->Adapter());
Vladimir Marko0441d202022-02-18 13:55:15 +00006592 const size_t super_ifcount = super_iftable->Count();
Vladimir Marko78f62d82022-01-10 16:25:19 +00006593 ArrayRef<const NewInterfaceReference> new_interface_references =
6594 FindNewIfTableInterfaces(
6595 super_iftable,
6596 super_ifcount,
6597 allocator,
6598 interfaces,
6599 ArrayRef<NewInterfaceReference>(initial_storage),
6600 &supplemental_storage);
6601
Vladimir Marko0441d202022-02-18 13:55:15 +00006602 // If all declared interfaces were already present in superclass interface table,
6603 // return the interface table from superclass. See above.
6604 if (UNLIKELY(new_interface_references.empty())) {
6605 return super_iftable;
Vladimir Marko78f62d82022-01-10 16:25:19 +00006606 }
6607
6608 // Create the interface table.
6609 size_t ifcount = super_ifcount + new_interface_references.size();
6610 ObjPtr<mirror::IfTable> iftable = AllocIfTable(self, ifcount, super_iftable->GetClass());
6611 if (UNLIKELY(iftable == nullptr)) {
6612 self->AssertPendingOOMException();
6613 return nullptr;
6614 }
6615 // Fill in table with superclass's iftable.
6616 if (super_ifcount != 0) {
6617 // Reload `super_iftable` as it may have been clobbered by the allocation.
6618 super_iftable = klass->GetSuperClass()->GetIfTable();
Vladimir Marko0441d202022-02-18 13:55:15 +00006619 for (size_t i = 0; i != super_ifcount; i++) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00006620 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Vladimir Marko0441d202022-02-18 13:55:15 +00006621 DCHECK(super_interface != nullptr);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006622 iftable->SetInterface(i, super_interface);
Vladimir Marko0441d202022-02-18 13:55:15 +00006623 ObjPtr<mirror::PointerArray> method_array = super_iftable->GetMethodArrayOrNull(i);
6624 if (method_array != nullptr) {
6625 iftable->SetMethodArray(i, method_array);
6626 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006627 }
6628 }
6629 // Fill in the table with additional interfaces.
6630 size_t current_index = super_ifcount;
6631 for (NewInterfaceReference ref : new_interface_references) {
6632 ObjPtr<mirror::Class> direct_interface = interfaces.GetInterface(ref.direct_interface_index);
6633 ObjPtr<mirror::Class> new_interface = (ref.direct_interface_iftable_index != dex::kDexNoIndex)
6634 ? direct_interface->GetIfTable()->GetInterface(ref.direct_interface_iftable_index)
6635 : direct_interface;
6636 iftable->SetInterface(current_index, new_interface);
6637 ++current_index;
6638 }
6639 DCHECK_EQ(current_index, ifcount);
6640
Alex Lighteb7c1442015-08-31 13:17:42 -07006641 if (kIsDebugBuild) {
6642 // Check that the iftable is ordered correctly.
Vladimir Marko78f62d82022-01-10 16:25:19 +00006643 for (size_t i = 0; i < ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006644 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006645 for (size_t j = i + 1; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006646 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006647 // !(if_a <: if_b)
6648 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006649 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6650 << ") extends "
6651 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006652 << "interface list.";
6653 }
6654 }
6655 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006656
Vladimir Marko78f62d82022-01-10 16:25:19 +00006657 return iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006658}
6659
Alex Light1f3925d2016-09-07 12:04:20 -07006660// Check that all vtable entries are present in this class's virtuals or are the same as a
6661// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006662void CheckClassOwnsVTableEntries(Thread* self,
6663 Handle<mirror::Class> klass,
6664 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006665 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006666 StackHandleScope<2> hs(self);
6667 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006668 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006669 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006670 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006671 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6672 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6673 CHECK(m != nullptr);
6674
Alex Lighta41a30782017-03-29 11:33:19 -07006675 if (m->GetMethodIndexDuringLinking() != i) {
6676 LOG(WARNING) << m->PrettyMethod()
6677 << " has an unexpected method index for its spot in the vtable for class"
6678 << klass->PrettyClass();
6679 }
Alex Lighte64300b2015-12-15 15:02:47 -08006680 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6681 auto is_same_method = [m] (const ArtMethod& meth) {
6682 return &meth == m;
6683 };
Alex Light3f980532017-03-17 15:10:32 -07006684 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6685 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6686 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6687 << klass->PrettyClass() << " or any of its superclasses!";
6688 }
Alex Lighte64300b2015-12-15 15:02:47 -08006689 }
6690}
6691
Alex Light1f3925d2016-09-07 12:04:20 -07006692// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6693// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08006694template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006695void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07006696 REQUIRES_SHARED(Locks::mutator_lock_) {
6697 StackHandleScope<1> hs(self);
6698 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6699 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006700
6701 // Observations:
6702 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
6703 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
6704 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
6705 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
6706 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
6707 // * The single-pass algorithm will trade memory for speed, but that is OK.
6708
6709 CHECK_GT(num_entries, 0);
6710
6711 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
6712 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
6713 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
6714 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6715 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
6716 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
6717 << m2->PrettyMethod() << " (0x" << std::hex
6718 << reinterpret_cast<uintptr_t>(m2) << ")";
6719 };
6720 struct BaseHashType {
6721 static size_t HashCombine(size_t seed, size_t val) {
6722 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
6723 }
6724 };
6725
6726 // Check assuming all entries come from the same dex file.
6727 {
6728 // Find the first interesting method and its dex file.
6729 int32_t start = 0;
6730 for (; start < num_entries; ++start) {
6731 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
6732 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
6733 // maybe).
6734 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6735 vtable_entry->GetAccessFlags())) {
6736 continue;
6737 }
6738 break;
6739 }
6740 if (start == num_entries) {
6741 return;
6742 }
6743 const DexFile* dex_file =
6744 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
6745 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
6746
6747 // Helper function to avoid logging if we have to run the cross-file checks.
6748 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
6749 // Use a map to store seen entries, as the storage space is too large for a bitvector.
6750 using PairType = std::pair<uint32_t, uint16_t>;
6751 struct PairHash : BaseHashType {
6752 size_t operator()(const PairType& key) const {
6753 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
6754 }
6755 };
Vladimir Marko782fb712020-12-23 12:47:31 +00006756 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006757 seen.reserve(2 * num_entries);
6758 bool need_slow_path = false;
6759 bool found_dup = false;
6760 for (int i = start; i < num_entries; ++i) {
6761 // Can use Unchecked here as the start loop already ensured that the arrays are correct
6762 // wrt/ kPointerSize.
6763 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
6764 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6765 vtable_entry->GetAccessFlags())) {
6766 continue;
6767 }
6768 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
6769 if (dex_file != m->GetDexFile()) {
6770 need_slow_path = true;
6771 break;
6772 }
6773 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
6774 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
6775 auto it = seen.find(pair);
6776 if (it != seen.end()) {
6777 found_dup = true;
6778 if (log_warn) {
6779 log_fn(it->second, i);
6780 }
6781 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00006782 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006783 }
6784 }
6785 return std::make_pair(need_slow_path, found_dup);
6786 };
6787 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
6788 if (!result.first) {
6789 if (result.second) {
6790 check_fn(/* log_warn= */ true);
6791 }
6792 return;
6793 }
6794 }
6795
6796 // Need to check across dex files.
6797 struct Entry {
6798 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00006799 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006800 const char* name = nullptr;
6801 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006802
Vladimir Marko782fb712020-12-23 12:47:31 +00006803 Entry() = default;
6804 Entry(const Entry& other) = default;
6805 Entry& operator=(const Entry& other) = default;
6806
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006807 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00006808 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
6809 // This call writes `name_len` and it is therefore necessary that the
6810 // initializer for `name_len` comes before it, otherwise the value
6811 // from the call would be overwritten by that initializer.
6812 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006813 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00006814 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
6815 if (name[name_len] != 0) {
6816 name_len += strlen(name + name_len);
6817 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006818 }
6819
6820 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00006821 return name_len == other.name_len &&
6822 memcmp(name, other.name, name_len) == 0 &&
6823 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006824 }
6825 };
6826 struct EntryHash {
6827 size_t operator()(const Entry& key) const {
6828 return key.cached_hash;
6829 }
6830 };
Vladimir Marko782fb712020-12-23 12:47:31 +00006831 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006832 for (int32_t i = 0; i < num_entries; ++i) {
6833 // Can use Unchecked here as the first loop already ensured that the arrays are correct
6834 // wrt/ kPointerSize.
6835 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
6836 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
6837 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07006838 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6839 vtable_entry->GetAccessFlags())) {
6840 continue;
6841 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006842 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
6843 const DexFile* dex_file = m->GetDexFile();
6844 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
6845
6846 Entry e(dex_file, mid);
6847
6848 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
6849 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
6850 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
6851 sig_hash);
6852
6853 auto it = map.find(e);
6854 if (it != map.end()) {
6855 log_fn(it->second, i);
6856 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00006857 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07006858 }
6859 }
6860}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006861
6862void CheckVTableHasNoDuplicates(Thread* self,
6863 Handle<mirror::Class> klass,
6864 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08006865 REQUIRES_SHARED(Locks::mutator_lock_) {
6866 switch (pointer_size) {
6867 case PointerSize::k64:
6868 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
6869 break;
6870 case PointerSize::k32:
6871 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
6872 break;
6873 }
6874}
Alex Light1f3925d2016-09-07 12:04:20 -07006875
Orion Hodson5880c772020-07-28 20:12:08 +01006876static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07006877 REQUIRES_SHARED(Locks::mutator_lock_) {
6878 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6879 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6880}
6881
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006882} // namespace
6883
Vladimir Markob91402f2021-12-21 15:55:06 +00006884template <PointerSize kPointerSize>
Vladimir Markobc893672021-11-10 15:25:46 +00006885class ClassLinker::LinkMethodsHelper {
Vladimir Marko921094a2017-01-12 18:37:06 +00006886 public:
Vladimir Markobc893672021-11-10 15:25:46 +00006887 LinkMethodsHelper(ClassLinker* class_linker,
6888 Handle<mirror::Class> klass,
6889 Thread* self,
6890 Runtime* runtime)
Vladimir Marko921094a2017-01-12 18:37:06 +00006891 : class_linker_(class_linker),
6892 klass_(klass),
Vladimir Marko921094a2017-01-12 18:37:06 +00006893 self_(self),
Vladimir Marko78f62d82022-01-10 16:25:19 +00006894 runtime_(runtime),
Vladimir Marko921094a2017-01-12 18:37:06 +00006895 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6896 allocator_(&stack_),
Vladimir Marko19366b82022-01-18 10:41:28 +00006897 copied_method_records_(copied_method_records_initial_buffer_,
6898 kCopiedMethodRecordInitialBufferSize,
6899 allocator_.Adapter()),
6900 num_new_copied_methods_(0u) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006901 }
6902
Vladimir Marko78f62d82022-01-10 16:25:19 +00006903 // Links the virtual and interface methods for the given class.
Vladimir Markobc893672021-11-10 15:25:46 +00006904 //
6905 // Arguments:
6906 // * self - The current thread.
6907 // * klass - class, whose vtable will be filled in.
Vladimir Marko78f62d82022-01-10 16:25:19 +00006908 // * interfaces - implemented interfaces for a proxy class, otherwise null.
6909 // * out_new_conflict - whether there is a new conflict compared to the superclass.
6910 // * out_imt - interface method table to fill.
6911 bool LinkMethods(
Vladimir Markobc893672021-11-10 15:25:46 +00006912 Thread* self,
6913 Handle<mirror::Class> klass,
Vladimir Marko78f62d82022-01-10 16:25:19 +00006914 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Vladimir Markobc893672021-11-10 15:25:46 +00006915 bool* out_new_conflict,
6916 ArtMethod** out_imt)
6917 REQUIRES_SHARED(Locks::mutator_lock_);
6918
6919 private:
Vladimir Marko0441d202022-02-18 13:55:15 +00006920 // Allocate a pointer array.
6921 static ObjPtr<mirror::PointerArray> AllocPointerArray(Thread* self, size_t length)
6922 REQUIRES_SHARED(Locks::mutator_lock_);
6923
6924 // Allocate method arrays for interfaces.
6925 bool AllocateIfTableMethodArrays(Thread* self,
6926 Handle<mirror::Class> klass,
6927 Handle<mirror::IfTable> iftable)
6928 REQUIRES_SHARED(Locks::mutator_lock_);
6929
Vladimir Marko8670e042021-12-21 17:55:48 +00006930 // Assign vtable indexes to declared virtual methods for a non-interface class other
6931 // than `java.lang.Object`. Returns the number of vtable entries on success, 0 on failure.
Vladimir Marko19366b82022-01-18 10:41:28 +00006932 // This function also assigns vtable indexes for interface methods in new interfaces
6933 // and records data for copied methods which shall be referenced by the vtable.
Vladimir Markobed84ef2022-01-21 13:57:14 +00006934 size_t AssignVTableIndexes(ObjPtr<mirror::Class> klass,
Vladimir Marko8670e042021-12-21 17:55:48 +00006935 ObjPtr<mirror::Class> super_class,
Vladimir Marko51718132022-02-07 16:31:08 +00006936 bool is_super_abstract,
Vladimir Marko19366b82022-01-18 10:41:28 +00006937 size_t num_virtual_methods,
6938 ObjPtr<mirror::IfTable> iftable)
6939 REQUIRES_SHARED(Locks::mutator_lock_);
6940
6941 bool FindCopiedMethodsForInterface(ObjPtr<mirror::Class> klass,
6942 size_t num_virtual_methods,
6943 ObjPtr<mirror::IfTable> iftable)
Vladimir Marko8670e042021-12-21 17:55:48 +00006944 REQUIRES_SHARED(Locks::mutator_lock_);
6945
Vladimir Marko78f62d82022-01-10 16:25:19 +00006946 bool LinkJavaLangObjectMethods(Thread* self, Handle<mirror::Class> klass)
Vladimir Markob91402f2021-12-21 15:55:06 +00006947 REQUIRES_SHARED(Locks::mutator_lock_) COLD_ATTR;
6948
Vladimir Marko19366b82022-01-18 10:41:28 +00006949 void ReallocMethods(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko0441d202022-02-18 13:55:15 +00006950 bool FinalizeIfTable(Handle<mirror::Class> klass,
6951 MutableHandle<mirror::IfTable> iftable,
6952 Handle<mirror::PointerArray> vtable,
Vladimir Marko51718132022-02-07 16:31:08 +00006953 bool is_klass_abstract,
6954 bool is_super_abstract,
Vladimir Marko19366b82022-01-18 10:41:28 +00006955 bool* out_new_conflict,
6956 ArtMethod** out_imt)
Vladimir Marko78f62d82022-01-10 16:25:19 +00006957 REQUIRES_SHARED(Locks::mutator_lock_);
6958
Vladimir Marko921094a2017-01-12 18:37:06 +00006959 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6960 LengthPrefixedArray<ArtMethod>* methods) {
Vladimir Marko19366b82022-01-18 10:41:28 +00006961 if (kIsDebugBuild && old_methods != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006962 CHECK(methods != nullptr);
6963 // Put some random garbage in old methods to help find stale pointers.
Vladimir Marko19366b82022-01-18 10:41:28 +00006964 if (methods != old_methods) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006965 // Need to make sure the GC is not running since it could be scanning the methods we are
6966 // about to overwrite.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00006967 ScopedThreadStateChange tsc(self_, ThreadState::kSuspended);
Vladimir Marko921094a2017-01-12 18:37:06 +00006968 gc::ScopedGCCriticalSection gcs(self_,
6969 gc::kGcCauseClassLinker,
6970 gc::kCollectorTypeClassLinker);
6971 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
Vladimir Markob91402f2021-12-21 15:55:06 +00006972 kMethodSize,
6973 kMethodAlignment);
Vladimir Marko921094a2017-01-12 18:37:06 +00006974 memset(old_methods, 0xFEu, old_size);
6975 }
6976 }
6977 }
6978
Vladimir Marko19366b82022-01-18 10:41:28 +00006979 NO_INLINE
6980 void LogNewVirtuals(LengthPrefixedArray<ArtMethod>* methods) const
6981 REQUIRES_SHARED(Locks::mutator_lock_) {
6982 ObjPtr<mirror::Class> klass = klass_.Get();
6983 size_t num_new_copied_methods = num_new_copied_methods_;
6984 size_t old_method_count = methods->size() - num_new_copied_methods;
6985 size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6986 size_t num_miranda_methods = 0u;
6987 size_t num_overriding_default_methods = 0u;
6988 size_t num_default_methods = 0u;
6989 size_t num_overriding_default_conflict_methods = 0u;
6990 size_t num_default_conflict_methods = 0u;
6991 for (size_t i = 0; i != num_new_copied_methods; ++i) {
6992 ArtMethod& m = methods->At(old_method_count + i, kMethodSize, kMethodAlignment);
6993 if (m.IsDefault()) {
6994 if (m.GetMethodIndexDuringLinking() < super_vtable_length) {
6995 ++num_overriding_default_methods;
6996 } else {
6997 ++num_default_methods;
6998 }
6999 } else if (m.IsDefaultConflicting()) {
7000 if (m.GetMethodIndexDuringLinking() < super_vtable_length) {
7001 ++num_overriding_default_conflict_methods;
7002 } else {
7003 ++num_default_conflict_methods;
7004 }
7005 } else {
7006 DCHECK(m.IsMiranda());
7007 ++num_miranda_methods;
7008 }
Vladimir Marko5cfb7bb2022-01-28 11:12:17 +00007009 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007010 VLOG(class_linker) << klass->PrettyClass() << ": miranda_methods=" << num_miranda_methods
7011 << " default_methods=" << num_default_methods
7012 << " overriding_default_methods=" << num_overriding_default_methods
7013 << " default_conflict_methods=" << num_default_conflict_methods
Vladimir Marko921094a2017-01-12 18:37:06 +00007014 << " overriding_default_conflict_methods="
Vladimir Marko19366b82022-01-18 10:41:28 +00007015 << num_overriding_default_conflict_methods;
Vladimir Marko921094a2017-01-12 18:37:06 +00007016 }
7017
Vladimir Marko8670e042021-12-21 17:55:48 +00007018 class MethodIndexEmptyFn {
7019 public:
7020 void MakeEmpty(uint32_t& item) const {
7021 item = dex::kDexNoIndex;
7022 }
7023 bool IsEmpty(const uint32_t& item) const {
7024 return item == dex::kDexNoIndex;
7025 }
7026 };
7027
Vladimir Marko7ddae992022-01-18 14:27:20 +00007028 class VTableIndexCheckerDebug {
7029 protected:
7030 explicit VTableIndexCheckerDebug(size_t vtable_length)
7031 : vtable_length_(vtable_length) {}
Vladimir Marko8670e042021-12-21 17:55:48 +00007032
Vladimir Marko7ddae992022-01-18 14:27:20 +00007033 void CheckIndex(uint32_t index) const {
7034 CHECK_LT(index, vtable_length_);
Vladimir Marko8670e042021-12-21 17:55:48 +00007035 }
7036
7037 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007038 uint32_t vtable_length_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007039 };
7040
Vladimir Marko7ddae992022-01-18 14:27:20 +00007041 class VTableIndexCheckerRelease {
7042 protected:
7043 explicit VTableIndexCheckerRelease(size_t vtable_length ATTRIBUTE_UNUSED) {}
7044 void CheckIndex(uint32_t index ATTRIBUTE_UNUSED) const {}
7045 };
Vladimir Marko8670e042021-12-21 17:55:48 +00007046
Vladimir Marko7ddae992022-01-18 14:27:20 +00007047 using VTableIndexChecker =
7048 std::conditional_t<kIsDebugBuild, VTableIndexCheckerDebug, VTableIndexCheckerRelease>;
7049
7050 class VTableAccessor : private VTableIndexChecker {
7051 public:
7052 VTableAccessor(uint8_t* raw_vtable, size_t vtable_length)
7053 REQUIRES_SHARED(Locks::mutator_lock_)
7054 : VTableIndexChecker(vtable_length),
7055 raw_vtable_(raw_vtable) {}
Vladimir Marko8670e042021-12-21 17:55:48 +00007056
7057 ArtMethod* GetVTableEntry(uint32_t index) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko7ddae992022-01-18 14:27:20 +00007058 this->CheckIndex(index);
7059 uint8_t* entry = raw_vtable_ + static_cast<size_t>(kPointerSize) * index;
7060 if (kPointerSize == PointerSize::k64) {
7061 return reinterpret_cast64<ArtMethod*>(*reinterpret_cast<uint64_t*>(entry));
7062 } else {
7063 return reinterpret_cast32<ArtMethod*>(*reinterpret_cast<uint32_t*>(entry));
7064 }
Vladimir Marko8670e042021-12-21 17:55:48 +00007065 }
7066
7067 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007068 uint8_t* raw_vtable_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007069 };
7070
Vladimir Marko8670e042021-12-21 17:55:48 +00007071 class VTableSignatureHash {
7072 public:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007073 explicit VTableSignatureHash(VTableAccessor accessor)
Vladimir Marko8670e042021-12-21 17:55:48 +00007074 REQUIRES_SHARED(Locks::mutator_lock_)
7075 : accessor_(accessor) {}
7076
7077 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7078 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7079 return ComputeMethodHash(method);
7080 }
7081
7082 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7083 size_t operator()(uint32_t index) const NO_THREAD_SAFETY_ANALYSIS {
7084 return ComputeMethodHash(accessor_.GetVTableEntry(index));
7085 }
7086
7087 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007088 VTableAccessor accessor_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007089 };
7090
Vladimir Marko8670e042021-12-21 17:55:48 +00007091 class VTableSignatureEqual {
7092 public:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007093 explicit VTableSignatureEqual(VTableAccessor accessor)
Vladimir Marko8670e042021-12-21 17:55:48 +00007094 REQUIRES_SHARED(Locks::mutator_lock_)
7095 : accessor_(accessor) {}
7096
7097 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7098 bool operator()(uint32_t lhs_index, ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
Vladimir Markobed84ef2022-01-21 13:57:14 +00007099 return MethodSignatureEquals(accessor_.GetVTableEntry(lhs_index), rhs);
Vladimir Marko8670e042021-12-21 17:55:48 +00007100 }
7101
7102 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7103 bool operator()(uint32_t lhs_index, uint32_t rhs_index) const NO_THREAD_SAFETY_ANALYSIS {
7104 return (*this)(lhs_index, accessor_.GetVTableEntry(rhs_index));
7105 }
7106
7107 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007108 VTableAccessor accessor_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007109 };
7110
Vladimir Marko7ddae992022-01-18 14:27:20 +00007111 using VTableSignatureSet =
7112 ScopedArenaHashSet<uint32_t, MethodIndexEmptyFn, VTableSignatureHash, VTableSignatureEqual>;
Vladimir Marko8670e042021-12-21 17:55:48 +00007113
Vladimir Marko19366b82022-01-18 10:41:28 +00007114 class DeclaredVirtualSignatureHash {
7115 public:
7116 explicit DeclaredVirtualSignatureHash(ObjPtr<mirror::Class> klass)
7117 REQUIRES_SHARED(Locks::mutator_lock_)
7118 : klass_(klass) {}
7119
7120 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7121 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7122 return ComputeMethodHash(method);
7123 }
7124
7125 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7126 size_t operator()(uint32_t index) const NO_THREAD_SAFETY_ANALYSIS {
7127 DCHECK_LT(index, klass_->NumDeclaredVirtualMethods());
7128 ArtMethod* method = klass_->GetVirtualMethodDuringLinking(index, kPointerSize);
7129 return ComputeMethodHash(method->GetInterfaceMethodIfProxy(kPointerSize));
7130 }
7131
7132 private:
7133 ObjPtr<mirror::Class> klass_;
7134 };
7135
7136 class DeclaredVirtualSignatureEqual {
7137 public:
7138 explicit DeclaredVirtualSignatureEqual(ObjPtr<mirror::Class> klass)
7139 REQUIRES_SHARED(Locks::mutator_lock_)
7140 : klass_(klass) {}
7141
7142 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7143 bool operator()(uint32_t lhs_index, ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
7144 DCHECK_LT(lhs_index, klass_->NumDeclaredVirtualMethods());
7145 ArtMethod* lhs = klass_->GetVirtualMethodDuringLinking(lhs_index, kPointerSize);
7146 return MethodSignatureEquals(lhs->GetInterfaceMethodIfProxy(kPointerSize), rhs);
7147 }
7148
7149 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7150 bool operator()(uint32_t lhs_index, uint32_t rhs_index) const NO_THREAD_SAFETY_ANALYSIS {
7151 DCHECK_LT(lhs_index, klass_->NumDeclaredVirtualMethods());
7152 DCHECK_LT(rhs_index, klass_->NumDeclaredVirtualMethods());
7153 return lhs_index == rhs_index;
7154 }
7155
7156 private:
7157 ObjPtr<mirror::Class> klass_;
7158 };
7159
7160 using DeclaredVirtualSignatureSet = ScopedArenaHashSet<uint32_t,
7161 MethodIndexEmptyFn,
7162 DeclaredVirtualSignatureHash,
7163 DeclaredVirtualSignatureEqual>;
7164
7165 // Helper class to keep records for determining the correct copied method to create.
7166 class CopiedMethodRecord {
7167 public:
7168 enum class State : uint32_t {
7169 // Note: The `*Single` values are used when we know that there is only one interface
7170 // method with the given signature that's not masked; that method is the main method.
7171 // We use this knowledge for faster masking check, otherwise we need to search for
7172 // a masking method through methods of all interfaces that could potentially mask it.
7173 kAbstractSingle,
7174 kDefaultSingle,
7175 kAbstract,
7176 kDefault,
7177 kDefaultConflict,
7178 kUseSuperMethod,
7179 };
7180
7181 CopiedMethodRecord()
7182 : main_method_(nullptr),
7183 method_index_(0u),
7184 state_(State::kAbstractSingle) {}
7185
7186 CopiedMethodRecord(ArtMethod* main_method, size_t vtable_index)
7187 : main_method_(main_method),
7188 method_index_(vtable_index),
7189 state_(State::kAbstractSingle) {}
7190
7191 // Set main method. The new main method must be more specific implementation.
7192 void SetMainMethod(ArtMethod* main_method) {
7193 DCHECK(main_method_ != nullptr);
7194 main_method_ = main_method;
7195 }
7196
7197 // The main method is the first encountered default method if any,
7198 // otherwise the first encountered abstract method.
7199 ArtMethod* GetMainMethod() const {
7200 return main_method_;
7201 }
7202
7203 void SetMethodIndex(size_t method_index) {
7204 DCHECK_NE(method_index, dex::kDexNoIndex);
7205 method_index_ = method_index;
7206 }
7207
7208 size_t GetMethodIndex() const {
7209 DCHECK_NE(method_index_, dex::kDexNoIndex);
7210 return method_index_;
7211 }
7212
7213 void SetState(State state) {
7214 state_ = state;
7215 }
7216
7217 State GetState() const {
7218 return state_;
7219 }
7220
7221 ALWAYS_INLINE
7222 void UpdateStateForInterface(ObjPtr<mirror::Class> iface,
7223 ArtMethod* interface_method,
7224 ObjPtr<mirror::IfTable> iftable,
7225 size_t ifcount,
7226 size_t index)
7227 REQUIRES_SHARED(Locks::mutator_lock_) {
7228 DCHECK_EQ(ifcount, iftable->Count());
7229 DCHECK_LT(index, ifcount);
7230 DCHECK(iface == interface_method->GetDeclaringClass());
7231 DCHECK(iface == iftable->GetInterface(index));
7232 DCHECK(interface_method->IsDefault());
7233 if (GetState() != State::kDefaultConflict) {
7234 DCHECK(GetState() == State::kDefault);
7235 // We do not record all overriding methods, so we need to walk over all
7236 // interfaces that could mask the `interface_method`.
7237 if (ContainsOverridingMethodOf(iftable, index + 1, ifcount, iface, interface_method)) {
7238 return; // Found an overriding method that masks `interface_method`.
7239 }
7240 // We have a new default method that's not masked by any other method.
7241 SetState(State::kDefaultConflict);
7242 }
7243 }
7244
7245 ALWAYS_INLINE
7246 void UpdateState(ObjPtr<mirror::Class> iface,
7247 ArtMethod* interface_method,
7248 size_t vtable_index,
7249 ObjPtr<mirror::IfTable> iftable,
7250 size_t ifcount,
7251 size_t index)
7252 REQUIRES_SHARED(Locks::mutator_lock_) {
7253 DCHECK_EQ(ifcount, iftable->Count());
7254 DCHECK_LT(index, ifcount);
7255 if (kIsDebugBuild) {
7256 if (interface_method->IsCopied()) {
7257 // Called from `FinalizeState()` for a default method from superclass.
7258 // The `index` points to the last interface inherited from the superclass
7259 // as we need to search only the new interfaces for masking methods.
7260 DCHECK(interface_method->IsDefault());
7261 } else {
7262 DCHECK(iface == interface_method->GetDeclaringClass());
7263 DCHECK(iface == iftable->GetInterface(index));
7264 }
7265 }
7266 DCHECK_EQ(vtable_index, method_index_);
7267 auto slow_is_masked = [=]() REQUIRES_SHARED(Locks::mutator_lock_) {
7268 return ContainsImplementingMethod(iftable, index + 1, ifcount, iface, vtable_index);
7269 };
7270 UpdateStateImpl(iface, interface_method, slow_is_masked);
7271 }
7272
7273 ALWAYS_INLINE
7274 void FinalizeState(ArtMethod* super_method,
7275 size_t vtable_index,
7276 ObjPtr<mirror::IfTable> iftable,
7277 size_t ifcount,
7278 ObjPtr<mirror::IfTable> super_iftable,
7279 size_t super_ifcount)
7280 REQUIRES_SHARED(Locks::mutator_lock_) {
7281 DCHECK(super_method->IsCopied());
7282 DCHECK_EQ(vtable_index, method_index_);
7283 DCHECK_EQ(vtable_index, super_method->GetMethodIndex());
7284 DCHECK_NE(super_ifcount, 0u);
7285 if (super_method->IsDefault()) {
7286 if (UNLIKELY(super_method->IsDefaultConflicting())) {
7287 // Some of the default methods that contributed to the conflict in the superclass
7288 // may be masked by new interfaces. Walk over all the interfaces and update state
7289 // as long as the current state is not `kDefaultConflict`.
7290 size_t i = super_ifcount;
7291 while (GetState() != State::kDefaultConflict && i != 0u) {
7292 --i;
7293 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
7294 DCHECK(iface == super_iftable->GetInterface(i));
7295 auto [found, index] =
7296 MethodArrayContains(super_iftable->GetMethodArrayOrNull(i), super_method);
7297 if (found) {
7298 ArtMethod* interface_method = iface->GetVirtualMethod(index, kPointerSize);
7299 auto slow_is_masked = [=]() REQUIRES_SHARED(Locks::mutator_lock_) {
7300 // Note: The `iftable` has method arrays in range [super_ifcount, ifcount) filled
7301 // with vtable indexes but the range [0, super_ifcount) is empty, so we need to
7302 // use the `super_iftable` filled with implementation methods for that range.
7303 return ContainsImplementingMethod(
7304 super_iftable, i + 1u, super_ifcount, iface, super_method) ||
7305 ContainsImplementingMethod(
7306 iftable, super_ifcount, ifcount, iface, vtable_index);
7307 };
7308 UpdateStateImpl(iface, interface_method, slow_is_masked);
7309 }
7310 }
7311 if (GetState() == State::kDefaultConflict) {
7312 SetState(State::kUseSuperMethod);
7313 }
7314 } else {
7315 // There was exactly one default method in superclass interfaces that was
7316 // not masked by subinterfaces. Use `UpdateState()` to process it and pass
7317 // `super_ifcount - 1` as index for checking if it's been masked by new interfaces.
7318 ObjPtr<mirror::Class> iface = super_method->GetDeclaringClass();
7319 UpdateState(
7320 iface, super_method, vtable_index, iftable, ifcount, /*index=*/ super_ifcount - 1u);
7321 if (GetMainMethod() == super_method) {
7322 DCHECK(GetState() == State::kDefault) << enum_cast<uint32_t>(GetState());
7323 SetState(State::kUseSuperMethod);
7324 }
7325 }
7326 } else {
7327 DCHECK(super_method->IsMiranda());
7328 // Any default methods with this signature in superclass interfaces have been
7329 // masked by subinterfaces. Check if we can reuse the miranda method.
7330 if (GetState() == State::kAbstractSingle || GetState() == State::kAbstract) {
7331 SetState(State::kUseSuperMethod);
7332 }
7333 }
7334 }
7335
7336 private:
7337 template <typename Predicate>
7338 ALWAYS_INLINE
7339 void UpdateStateImpl(ObjPtr<mirror::Class> iface,
7340 ArtMethod* interface_method,
7341 Predicate&& slow_is_masked)
7342 REQUIRES_SHARED(Locks::mutator_lock_) {
7343 bool have_default = false;
7344 switch (GetState()) {
7345 case State::kDefaultSingle:
7346 have_default = true;
7347 FALLTHROUGH_INTENDED;
7348 case State::kAbstractSingle:
7349 if (GetMainMethod()->GetDeclaringClass()->Implements(iface)) {
7350 return; // The main method masks the `interface_method`.
7351 }
7352 if (!interface_method->IsDefault()) {
7353 SetState(have_default ? State::kDefault : State::kAbstract);
7354 return;
7355 }
7356 break;
7357 case State::kDefault:
7358 have_default = true;
7359 FALLTHROUGH_INTENDED;
7360 case State::kAbstract:
7361 if (!interface_method->IsDefault()) {
7362 return; // Keep the same state. We do not need to check for masking.
7363 }
7364 // We do not record all overriding methods, so we need to walk over all
7365 // interfaces that could mask the `interface_method`. The provided
7366 // predicate `slow_is_masked()` does that.
7367 if (slow_is_masked()) {
7368 return; // Found an overriding method that masks `interface_method`.
7369 }
7370 break;
7371 case State::kDefaultConflict:
7372 return; // The state cannot change anymore.
7373 default:
7374 LOG(FATAL) << "Unexpected state: " << enum_cast<uint32_t>(GetState());
7375 UNREACHABLE();
7376 }
7377 // We have a new default method that's not masked by any other method.
7378 DCHECK(interface_method->IsDefault());
7379 if (have_default) {
7380 SetState(State::kDefaultConflict);
7381 } else {
7382 SetMainMethod(interface_method);
7383 SetState(State::kDefault);
7384 }
7385 }
7386
7387 // Determine if the given `iftable` contains in the given range a subinterface of `iface`
7388 // that declares a method with the same name and signature as 'interface_method'.
7389 //
7390 // Arguments
7391 // - iftable: The iftable we are searching for an overriding method.
7392 // - begin: The start of the range to search.
7393 // - end: The end of the range to search.
7394 // - iface: The interface we are checking to see if anything overrides.
7395 // - interface_method:
7396 // The interface method providing a name and signature we're searching for.
7397 //
7398 // Returns whether an overriding method was found in any subinterface of `iface`.
7399 static bool ContainsOverridingMethodOf(ObjPtr<mirror::IfTable> iftable,
7400 size_t begin,
7401 size_t end,
7402 ObjPtr<mirror::Class> iface,
7403 ArtMethod* interface_method)
7404 REQUIRES_SHARED(Locks::mutator_lock_) {
7405 for (size_t i = begin; i != end; ++i) {
7406 ObjPtr<mirror::Class> current_iface = iftable->GetInterface(i);
7407 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(kPointerSize)) {
7408 if (MethodSignatureEquals(&current_method, interface_method)) {
7409 // Check if the i'th interface is a subtype of this one.
7410 if (current_iface->Implements(iface)) {
7411 return true;
7412 }
7413 break;
7414 }
7415 }
7416 }
7417 return false;
7418 }
7419
7420 // Determine if the given `iftable` contains in the given range a subinterface of `iface`
7421 // that declares a method implemented by 'target'. This is an optimized version of
7422 // `ContainsOverridingMethodOf()` that searches implementation method arrays instead
7423 // of comparing signatures for declared interface methods.
7424 //
7425 // Arguments
7426 // - iftable: The iftable we are searching for an overriding method.
7427 // - begin: The start of the range to search.
7428 // - end: The end of the range to search.
7429 // - iface: The interface we are checking to see if anything overrides.
7430 // - target: The implementation method we're searching for.
7431 // Note that the new `iftable` is filled with vtable indexes for new interfaces,
7432 // so this needs to be the vtable index if we're searching that range.
7433 //
7434 // Returns whether the `target` was found in a method array for any subinterface of `iface`.
7435 template <typename TargetType>
7436 static bool ContainsImplementingMethod(ObjPtr<mirror::IfTable> iftable,
7437 size_t begin,
7438 size_t end,
7439 ObjPtr<mirror::Class> iface,
7440 TargetType target)
7441 REQUIRES_SHARED(Locks::mutator_lock_) {
7442 for (size_t i = begin; i != end; ++i) {
7443 if (MethodArrayContains(iftable->GetMethodArrayOrNull(i), target).first &&
7444 iftable->GetInterface(i)->Implements(iface)) {
7445 return true;
7446 }
7447 }
7448 return false;
7449 }
7450
7451 template <typename TargetType>
7452 static std::pair<bool, size_t> MethodArrayContains(ObjPtr<mirror::PointerArray> method_array,
7453 TargetType target)
7454 REQUIRES_SHARED(Locks::mutator_lock_) {
7455 size_t num_methods = (method_array != nullptr) ? method_array->GetLength() : 0u;
7456 for (size_t j = 0; j != num_methods; ++j) {
7457 if (method_array->GetElementPtrSize<TargetType, kPointerSize>(j) == target) {
7458 return {true, j};
7459 }
7460 }
7461 return {false, 0};
7462 }
7463
7464 ArtMethod* main_method_;
7465 uint32_t method_index_;
7466 State state_;
7467 };
7468
7469 class CopiedMethodRecordEmptyFn {
7470 public:
7471 void MakeEmpty(CopiedMethodRecord& item) const {
7472 item = CopiedMethodRecord();
7473 }
7474 bool IsEmpty(const CopiedMethodRecord& item) const {
7475 return item.GetMainMethod() == nullptr;
7476 }
7477 };
7478
7479 class CopiedMethodRecordHash {
7480 public:
7481 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7482 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7483 DCHECK(method != nullptr);
7484 return ComputeMethodHash(method);
7485 }
7486
7487 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7488 size_t operator()(const CopiedMethodRecord& record) const NO_THREAD_SAFETY_ANALYSIS {
7489 return (*this)(record.GetMainMethod());
7490 }
7491 };
7492
7493 class CopiedMethodRecordEqual {
7494 public:
7495 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7496 bool operator()(const CopiedMethodRecord& lhs_record,
7497 ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
7498 ArtMethod* lhs = lhs_record.GetMainMethod();
7499 DCHECK(lhs != nullptr);
7500 DCHECK(rhs != nullptr);
7501 return MethodSignatureEquals(lhs, rhs);
7502 }
7503
7504 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7505 bool operator()(const CopiedMethodRecord& lhs_record,
7506 const CopiedMethodRecord& rhs_record) const NO_THREAD_SAFETY_ANALYSIS {
7507 return (*this)(lhs_record, rhs_record.GetMainMethod());
7508 }
7509 };
7510
7511 using CopiedMethodRecordSet = ScopedArenaHashSet<CopiedMethodRecord,
7512 CopiedMethodRecordEmptyFn,
7513 CopiedMethodRecordHash,
7514 CopiedMethodRecordEqual>;
7515
Vladimir Markob91402f2021-12-21 15:55:06 +00007516 static constexpr size_t kMethodAlignment = ArtMethod::Alignment(kPointerSize);
7517 static constexpr size_t kMethodSize = ArtMethod::Size(kPointerSize);
7518
Vladimir Marko921094a2017-01-12 18:37:06 +00007519 ClassLinker* class_linker_;
7520 Handle<mirror::Class> klass_;
Vladimir Marko921094a2017-01-12 18:37:06 +00007521 Thread* const self_;
Vladimir Marko78f62d82022-01-10 16:25:19 +00007522 Runtime* const runtime_;
Vladimir Marko921094a2017-01-12 18:37:06 +00007523
7524 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7525 // the virtual methods array.
7526 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7527 // during cross compilation.
7528 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7529 ArenaStack stack_;
7530 ScopedArenaAllocator allocator_;
7531
Vladimir Marko19366b82022-01-18 10:41:28 +00007532 // Avoid large allocation for a few copied method records.
Vladimir Markobc893672021-11-10 15:25:46 +00007533 // Keep the initial buffer on the stack to avoid arena allocations
7534 // if there are no special cases (the first arena allocation is costly).
Vladimir Marko19366b82022-01-18 10:41:28 +00007535 static constexpr size_t kCopiedMethodRecordInitialBufferSize = 16u;
7536 CopiedMethodRecord copied_method_records_initial_buffer_[kCopiedMethodRecordInitialBufferSize];
7537 CopiedMethodRecordSet copied_method_records_;
7538 size_t num_new_copied_methods_;
Vladimir Marko921094a2017-01-12 18:37:06 +00007539};
7540
Vladimir Markob91402f2021-12-21 15:55:06 +00007541template <PointerSize kPointerSize>
Vladimir Marko19366b82022-01-18 10:41:28 +00007542NO_INLINE
7543void ClassLinker::LinkMethodsHelper<kPointerSize>::ReallocMethods(ObjPtr<mirror::Class> klass) {
7544 // There should be no thread suspension in this function,
7545 // native allocations do not cause thread suspension.
7546 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Marko921094a2017-01-12 18:37:06 +00007547
Vladimir Marko19366b82022-01-18 10:41:28 +00007548 size_t num_new_copied_methods = num_new_copied_methods_;
7549 DCHECK_NE(num_new_copied_methods, 0u);
7550 const size_t old_method_count = klass->NumMethods();
7551 const size_t new_method_count = old_method_count + num_new_copied_methods;
Vladimir Marko921094a2017-01-12 18:37:06 +00007552
7553 // Attempt to realloc to save RAM if possible.
Vladimir Marko19366b82022-01-18 10:41:28 +00007554 LengthPrefixedArray<ArtMethod>* old_methods = klass->GetMethodsPtr();
Vladimir Marko921094a2017-01-12 18:37:06 +00007555 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7556 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7557 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7558 // CopyFrom has internal read barriers.
7559 //
7560 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7561 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
Vladimir Markob91402f2021-12-21 15:55:06 +00007562 kMethodSize,
7563 kMethodAlignment);
Vladimir Marko921094a2017-01-12 18:37:06 +00007564 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
Vladimir Markob91402f2021-12-21 15:55:06 +00007565 kMethodSize,
7566 kMethodAlignment);
Vladimir Marko921094a2017-01-12 18:37:06 +00007567 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7568 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Vladimir Marko19366b82022-01-18 10:41:28 +00007569 class_linker_->GetAllocatorForClassLoader(klass->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007570 self_, old_methods, old_methods_ptr_size, new_size));
7571 CHECK(methods != nullptr); // Native allocation failure aborts.
7572
Vladimir Marko921094a2017-01-12 18:37:06 +00007573 if (methods != old_methods) {
Vladimir Markob91402f2021-12-21 15:55:06 +00007574 StrideIterator<ArtMethod> out = methods->begin(kMethodSize, kMethodAlignment);
Vladimir Marko19366b82022-01-18 10:41:28 +00007575 // Copy over the old methods. The `ArtMethod::CopyFrom()` is only necessary to not miss
7576 // read barriers since `LinearAlloc::Realloc()` won't do read barriers when it copies.
7577 for (auto& m : klass->GetMethods(kPointerSize)) {
Vladimir Markob91402f2021-12-21 15:55:06 +00007578 out->CopyFrom(&m, kPointerSize);
Vladimir Marko921094a2017-01-12 18:37:06 +00007579 ++out;
7580 }
7581 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007582
7583 // Collect and sort copied method records by the vtable index. This places overriding
7584 // copied methods first, sorted by the vtable index already assigned in the superclass,
7585 // followed by copied methods with new signatures in the order in which we encountered
7586 // them when going over virtual methods of new interfaces.
7587 // This order is deterministic but implementation-defined.
7588 //
7589 // Avoid arena allocation for a few records (the first arena allocation is costly).
7590 constexpr size_t kSortedRecordsBufferSize = 16;
7591 CopiedMethodRecord* sorted_records_buffer[kSortedRecordsBufferSize];
7592 CopiedMethodRecord** sorted_records = (num_new_copied_methods <= kSortedRecordsBufferSize)
7593 ? sorted_records_buffer
7594 : allocator_.AllocArray<CopiedMethodRecord*>(num_new_copied_methods);
7595 size_t filled_sorted_records = 0u;
7596 for (CopiedMethodRecord& record : copied_method_records_) {
7597 if (record.GetState() != CopiedMethodRecord::State::kUseSuperMethod) {
7598 DCHECK_LT(filled_sorted_records, num_new_copied_methods);
7599 sorted_records[filled_sorted_records] = &record;
7600 ++filled_sorted_records;
Vladimir Marko921094a2017-01-12 18:37:06 +00007601 }
7602 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007603 DCHECK_EQ(filled_sorted_records, num_new_copied_methods);
7604 std::sort(sorted_records,
7605 sorted_records + num_new_copied_methods,
7606 [](const CopiedMethodRecord* lhs, const CopiedMethodRecord* rhs) {
7607 return lhs->GetMethodIndex() < rhs->GetMethodIndex();
7608 });
7609
7610 if (klass->IsInterface()) {
7611 // Some records may have been pruned. Update method indexes in collected records.
7612 size_t interface_method_index = klass->NumDeclaredVirtualMethods();
7613 for (size_t i = 0; i != num_new_copied_methods; ++i) {
7614 CopiedMethodRecord* record = sorted_records[i];
7615 DCHECK_LE(interface_method_index, record->GetMethodIndex());
7616 record->SetMethodIndex(interface_method_index);
7617 ++interface_method_index;
Vladimir Marko921094a2017-01-12 18:37:06 +00007618 }
7619 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007620
7621 // Add copied methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007622 methods->SetSize(new_method_count);
Vladimir Marko19366b82022-01-18 10:41:28 +00007623 for (size_t i = 0; i != num_new_copied_methods; ++i) {
7624 const CopiedMethodRecord* record = sorted_records[i];
7625 ArtMethod* interface_method = record->GetMainMethod();
7626 DCHECK(!interface_method->IsCopied());
7627 ArtMethod& new_method = methods->At(old_method_count + i, kMethodSize, kMethodAlignment);
7628 new_method.CopyFrom(interface_method, kPointerSize);
7629 new_method.SetMethodIndex(dchecked_integral_cast<uint16_t>(record->GetMethodIndex()));
7630 switch (record->GetState()) {
7631 case CopiedMethodRecord::State::kAbstractSingle:
7632 case CopiedMethodRecord::State::kAbstract: {
7633 DCHECK(!klass->IsInterface()); // We do not create miranda methods for interfaces.
7634 uint32_t access_flags = new_method.GetAccessFlags();
7635 DCHECK_EQ(access_flags & (kAccAbstract | kAccIntrinsic | kAccDefault), kAccAbstract)
7636 << "Miranda method should be abstract but not intrinsic or default!";
7637 new_method.SetAccessFlags(access_flags | kAccCopied);
7638 break;
7639 }
7640 case CopiedMethodRecord::State::kDefaultSingle:
7641 case CopiedMethodRecord::State::kDefault: {
7642 DCHECK(!klass->IsInterface()); // We do not copy default methods for interfaces.
7643 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7644 // verified yet it shouldn't have methods that are skipping access checks.
7645 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7646 // methods are skip_access_checks.
7647 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
7648 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7649 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7650 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7651 break;
7652 }
7653 case CopiedMethodRecord::State::kDefaultConflict: {
7654 // This is a type of default method (there are default method impls, just a conflict)
7655 // so mark this as a default. We use the `kAccAbstract` flag to distinguish it from
7656 // invokable copied default method without using a separate access flag but the default
7657 // conflicting method is technically not abstract and ArtMethod::IsAbstract() shall
7658 // return false. Also clear the kAccSkipAccessChecks bit since this class hasn't been
7659 // verified yet it shouldn't have methods that are skipping access checks. Also clear
7660 // potential kAccSingleImplementation to avoid CHA trying to inline the default method.
7661 uint32_t access_flags = new_method.GetAccessFlags();
7662 DCHECK_EQ(access_flags & (kAccNative | kAccIntrinsic), 0u);
7663 constexpr uint32_t kSetFlags = kAccDefault | kAccAbstract | kAccCopied;
7664 constexpr uint32_t kMaskFlags = ~(kAccSkipAccessChecks | kAccSingleImplementation);
7665 new_method.SetAccessFlags((access_flags | kSetFlags) & kMaskFlags);
7666 DCHECK(new_method.IsDefaultConflicting());
7667 DCHECK(!new_method.IsAbstract());
7668 // The actual method might or might not be marked abstract since we just copied it from
7669 // a (possibly default) interface method. We need to set its entry point to be the bridge
7670 // so that the compiler will not invoke the implementation of whatever method we copied
7671 // from.
7672 EnsureThrowsInvocationError(class_linker_, &new_method);
7673 break;
7674 }
7675 default:
7676 LOG(FATAL) << "Unexpected state: " << enum_cast<uint32_t>(record->GetState());
7677 UNREACHABLE();
7678 }
7679 }
7680
7681 if (VLOG_IS_ON(class_linker)) {
7682 LogNewVirtuals(methods);
7683 }
7684
7685 class_linker_->UpdateClassMethods(klass, methods);
Vladimir Marko921094a2017-01-12 18:37:06 +00007686}
7687
Vladimir Markob91402f2021-12-21 15:55:06 +00007688template <PointerSize kPointerSize>
Vladimir Marko0441d202022-02-18 13:55:15 +00007689bool ClassLinker::LinkMethodsHelper<kPointerSize>::FinalizeIfTable(
7690 Handle<mirror::Class> klass,
7691 MutableHandle<mirror::IfTable> iftable,
7692 Handle<mirror::PointerArray> vtable,
Vladimir Marko51718132022-02-07 16:31:08 +00007693 bool is_klass_abstract,
7694 bool is_super_abstract,
Vladimir Marko19366b82022-01-18 10:41:28 +00007695 bool* out_new_conflict,
7696 ArtMethod** out_imt) {
Vladimir Marko19366b82022-01-18 10:41:28 +00007697 size_t ifcount = iftable->Count();
Vladimir Marko0441d202022-02-18 13:55:15 +00007698 // We do not need a read barrier here as the length is constant, both from-space and
7699 // to-space `IfTable`s shall yield the same result. See also `Class::GetIfTableCount()`.
7700 size_t super_ifcount =
7701 klass->GetSuperClass<kDefaultVerifyFlags, kWithoutReadBarrier>()->GetIfTableCount();
Vladimir Marko921094a2017-01-12 18:37:06 +00007702
Vladimir Marko0441d202022-02-18 13:55:15 +00007703 ClassLinker* class_linker = nullptr;
Vladimir Marko51718132022-02-07 16:31:08 +00007704 ArtMethod* unimplemented_method = nullptr;
7705 ArtMethod* imt_conflict_method = nullptr;
7706 uintptr_t imt_methods_begin = 0u;
7707 size_t imt_methods_size = 0u;
7708 DCHECK_EQ(klass->ShouldHaveImt(), !is_klass_abstract);
7709 DCHECK_EQ(klass->GetSuperClass()->ShouldHaveImt(), !is_super_abstract);
7710 if (!is_klass_abstract) {
Vladimir Marko0441d202022-02-18 13:55:15 +00007711 class_linker = class_linker_;
Vladimir Marko51718132022-02-07 16:31:08 +00007712 unimplemented_method = runtime_->GetImtUnimplementedMethod();
7713 imt_conflict_method = runtime_->GetImtConflictMethod();
7714 if (is_super_abstract) {
7715 // There was no IMT in superclass to copy to `out_imt[]`, so we need
7716 // to fill it with all implementation methods from superclass.
7717 DCHECK_EQ(imt_methods_begin, 0u);
7718 imt_methods_size = std::numeric_limits<size_t>::max(); // No method at the last byte.
7719 } else {
7720 // If the superclass has IMT, we have already copied it to `out_imt[]` and
7721 // we do not need to call `SetIMTRef()` for interfaces from superclass when
7722 // the implementation method is already in the superclass, only for new methods.
7723 // For simplicity, use the entire method array including direct methods.
7724 LengthPrefixedArray<ArtMethod>* const new_methods = klass->GetMethodsPtr();
7725 if (new_methods != nullptr) {
7726 DCHECK_NE(new_methods->size(), 0u);
7727 imt_methods_begin = reinterpret_cast<uintptr_t>(&new_methods->At(0));
7728 imt_methods_size = new_methods->size() * kMethodSize;
7729 }
7730 }
7731 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007732
Vladimir Marko0441d202022-02-18 13:55:15 +00007733 auto update_imt = [=](ObjPtr<mirror::Class> iface, size_t j, ArtMethod* implementation)
7734 REQUIRES_SHARED(Locks::mutator_lock_) {
7735 // Place method in imt if entry is empty, place conflict otherwise.
7736 ArtMethod** imt_ptr = &out_imt[iface->GetVirtualMethod(j, kPointerSize)->GetImtIndex()];
7737 class_linker->SetIMTRef(unimplemented_method,
7738 imt_conflict_method,
7739 implementation,
7740 /*out*/out_new_conflict,
7741 /*out*/imt_ptr);
7742 };
7743
Vladimir Marko19366b82022-01-18 10:41:28 +00007744 // For interfaces inherited from superclass, the new method arrays are empty,
7745 // so use vtable indexes from implementation methods from the superclass method array.
7746 for (size_t i = 0; i != super_ifcount; ++i) {
7747 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
Vladimir Marko0441d202022-02-18 13:55:15 +00007748 DCHECK(method_array == klass->GetSuperClass()->GetIfTable()->GetMethodArrayOrNull(i));
Vladimir Marko19366b82022-01-18 10:41:28 +00007749 if (method_array == nullptr) {
7750 continue;
7751 }
7752 size_t num_methods = method_array->GetLength();
7753 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Vladimir Marko0441d202022-02-18 13:55:15 +00007754 size_t j = 0;
7755 // First loop has method array shared with the super class.
7756 for (; j != num_methods; ++j) {
Vladimir Marko19366b82022-01-18 10:41:28 +00007757 ArtMethod* super_implementation =
Vladimir Marko0441d202022-02-18 13:55:15 +00007758 method_array->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7759 size_t vtable_index = super_implementation->GetMethodIndex();
7760 ArtMethod* implementation =
7761 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(vtable_index);
7762 // Check if we need to update IMT with this method, see above.
7763 if (reinterpret_cast<uintptr_t>(implementation) - imt_methods_begin < imt_methods_size) {
7764 update_imt(iface, j, implementation);
7765 }
7766 if (implementation != super_implementation) {
7767 // Copy-on-write and move to the next loop.
7768 Thread* self = self_;
7769 StackHandleScope<2u> hs(self);
7770 Handle<mirror::PointerArray> old_method_array = hs.NewHandle(method_array);
7771 HandleWrapperObjPtr<mirror::Class> h_iface = hs.NewHandleWrapper(&iface);
7772 if (ifcount == super_ifcount && iftable.Get() == klass->GetSuperClass()->GetIfTable()) {
7773 ObjPtr<mirror::IfTable> new_iftable = ObjPtr<mirror::IfTable>::DownCast(
7774 mirror::ObjectArray<mirror::Object>::CopyOf(
7775 iftable, self, ifcount * mirror::IfTable::kMax));
7776 if (new_iftable == nullptr) {
7777 return false;
7778 }
7779 iftable.Assign(new_iftable);
7780 }
7781 method_array = ObjPtr<mirror::PointerArray>::DownCast(
7782 mirror::Array::CopyOf(old_method_array, self, num_methods));
7783 if (method_array == nullptr) {
7784 return false;
7785 }
7786 iftable->SetMethodArray(i, method_array);
7787 method_array->SetElementPtrSize(j, implementation, kPointerSize);
7788 ++j;
7789 break;
7790 }
7791 }
7792 // Second loop (if non-empty) has method array different from the superclass.
7793 for (; j != num_methods; ++j) {
7794 ArtMethod* super_implementation =
7795 method_array->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
Vladimir Marko19366b82022-01-18 10:41:28 +00007796 size_t vtable_index = super_implementation->GetMethodIndex();
7797 ArtMethod* implementation =
7798 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(vtable_index);
7799 method_array->SetElementPtrSize(j, implementation, kPointerSize);
Vladimir Marko51718132022-02-07 16:31:08 +00007800 // Check if we need to update IMT with this method, see above.
7801 if (reinterpret_cast<uintptr_t>(implementation) - imt_methods_begin < imt_methods_size) {
Vladimir Marko0441d202022-02-18 13:55:15 +00007802 update_imt(iface, j, implementation);
Vladimir Marko51718132022-02-07 16:31:08 +00007803 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007804 }
7805 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007806
Vladimir Marko19366b82022-01-18 10:41:28 +00007807 // New interface method arrays contain vtable indexes. Translate them to methods.
Vladimir Marko51718132022-02-07 16:31:08 +00007808 DCHECK_EQ(klass->ShouldHaveImt(), !is_klass_abstract);
Vladimir Marko19366b82022-01-18 10:41:28 +00007809 for (size_t i = super_ifcount; i != ifcount; ++i) {
7810 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
7811 if (method_array == nullptr) {
7812 continue;
Vladimir Marko921094a2017-01-12 18:37:06 +00007813 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007814 size_t num_methods = method_array->GetLength();
7815 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
7816 for (size_t j = 0; j != num_methods; ++j) {
7817 size_t vtable_index = method_array->GetElementPtrSize<size_t, kPointerSize>(j);
7818 ArtMethod* implementation =
7819 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(vtable_index);
7820 method_array->SetElementPtrSize(j, implementation, kPointerSize);
Vladimir Marko51718132022-02-07 16:31:08 +00007821 if (!is_klass_abstract) {
Vladimir Marko0441d202022-02-18 13:55:15 +00007822 update_imt(iface, j, implementation);
Vladimir Marko51718132022-02-07 16:31:08 +00007823 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007824 }
7825 }
Vladimir Marko0441d202022-02-18 13:55:15 +00007826
7827 return true;
Vladimir Marko921094a2017-01-12 18:37:06 +00007828}
7829
Vladimir Marko19366b82022-01-18 10:41:28 +00007830NO_INLINE
7831static void ThrowIllegalAccessErrorForImplementingMethod(ObjPtr<mirror::Class> klass,
7832 ArtMethod* vtable_method,
7833 ArtMethod* interface_method)
7834 REQUIRES_SHARED(Locks::mutator_lock_) {
7835 DCHECK(!vtable_method->IsAbstract());
7836 DCHECK(!vtable_method->IsPublic());
7837 ThrowIllegalAccessError(
7838 klass,
7839 "Method '%s' implementing interface method '%s' is not public",
7840 vtable_method->PrettyMethod().c_str(),
7841 interface_method->PrettyMethod().c_str());
Vladimir Marko921094a2017-01-12 18:37:06 +00007842}
7843
Vladimir Markob91402f2021-12-21 15:55:06 +00007844template <PointerSize kPointerSize>
Vladimir Marko0441d202022-02-18 13:55:15 +00007845ObjPtr<mirror::PointerArray> ClassLinker::LinkMethodsHelper<kPointerSize>::AllocPointerArray(
7846 Thread* self, size_t length) {
7847 using PointerArrayType = std::conditional_t<
7848 kPointerSize == PointerSize::k64, mirror::LongArray, mirror::IntArray>;
7849 ObjPtr<mirror::Array> array = PointerArrayType::Alloc(self, length);
7850 return ObjPtr<mirror::PointerArray>::DownCast(array);
7851}
7852
7853template <PointerSize kPointerSize>
7854bool ClassLinker::LinkMethodsHelper<kPointerSize>::AllocateIfTableMethodArrays(
7855 Thread* self,
7856 Handle<mirror::Class> klass,
7857 Handle<mirror::IfTable> iftable) {
7858 DCHECK(!klass->IsInterface());
7859 DCHECK(klass_->HasSuperClass());
7860 const size_t ifcount = iftable->Count();
7861 // We do not need a read barrier here as the length is constant, both from-space and
7862 // to-space `IfTable`s shall yield the same result. See also `Class::GetIfTableCount()`.
7863 size_t super_ifcount =
7864 klass->GetSuperClass<kDefaultVerifyFlags, kWithoutReadBarrier>()->GetIfTableCount();
7865 if (ifcount == super_ifcount) {
7866 DCHECK(iftable.Get() == klass_->GetSuperClass()->GetIfTable());
7867 return true;
7868 }
7869
7870 if (kIsDebugBuild) {
7871 // The method array references for superclass interfaces have been copied.
7872 // We shall allocate new arrays if needed (copy-on-write) in `FinalizeIfTable()`.
7873 ObjPtr<mirror::IfTable> super_iftable = klass_->GetSuperClass()->GetIfTable();
7874 for (size_t i = 0; i != super_ifcount; ++i) {
7875 CHECK(iftable->GetInterface(i) == super_iftable->GetInterface(i));
7876 CHECK(iftable->GetMethodArrayOrNull(i) == super_iftable->GetMethodArrayOrNull(i));
7877 }
7878 }
7879
7880 for (size_t i = super_ifcount; i < ifcount; ++i) {
7881 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
7882 if (num_methods > 0) {
7883 ObjPtr<mirror::PointerArray> method_array = AllocPointerArray(self, num_methods);
7884 if (UNLIKELY(method_array == nullptr)) {
7885 self->AssertPendingOOMException();
7886 return false;
7887 }
7888 iftable->SetMethodArray(i, method_array);
7889 }
7890 }
7891 return true;
7892}
7893
7894template <PointerSize kPointerSize>
Vladimir Markobed84ef2022-01-21 13:57:14 +00007895size_t ClassLinker::LinkMethodsHelper<kPointerSize>::AssignVTableIndexes(
Vladimir Marko19366b82022-01-18 10:41:28 +00007896 ObjPtr<mirror::Class> klass,
7897 ObjPtr<mirror::Class> super_class,
Vladimir Marko51718132022-02-07 16:31:08 +00007898 bool is_super_abstract,
Vladimir Marko19366b82022-01-18 10:41:28 +00007899 size_t num_virtual_methods,
7900 ObjPtr<mirror::IfTable> iftable) {
Vladimir Marko8670e042021-12-21 17:55:48 +00007901 DCHECK(!klass->IsInterface());
7902 DCHECK(klass->HasSuperClass());
7903 DCHECK(klass->GetSuperClass() == super_class);
Vladimir Marko8670e042021-12-21 17:55:48 +00007904
7905 // There should be no thread suspension unless we want to throw an exception.
Vladimir Marko7ddae992022-01-18 14:27:20 +00007906 // (We are using `ObjPtr<>` and raw vtable pointers that are invalidated by thread suspension.)
Vladimir Marko8670e042021-12-21 17:55:48 +00007907 std::optional<ScopedAssertNoThreadSuspension> sants(__FUNCTION__);
7908
7909 // Prepare a hash table with virtual methods from the superclass.
7910 // For the unlikely cases that there are multiple methods with the same signature
7911 // but different vtable indexes, keep an array with indexes of the previous
7912 // methods with the same signature (walked as singly-linked lists).
Vladimir Marko7ddae992022-01-18 14:27:20 +00007913 uint8_t* raw_super_vtable;
7914 size_t super_vtable_length;
Vladimir Marko51718132022-02-07 16:31:08 +00007915 if (is_super_abstract) {
7916 DCHECK(!super_class->ShouldHaveEmbeddedVTable());
Vladimir Marko7ddae992022-01-18 14:27:20 +00007917 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTableDuringLinking();
7918 DCHECK(super_vtable != nullptr);
7919 raw_super_vtable = reinterpret_cast<uint8_t*>(super_vtable.Ptr()) +
7920 mirror::Array::DataOffset(static_cast<size_t>(kPointerSize)).Uint32Value();
7921 super_vtable_length = super_vtable->GetLength();
Vladimir Marko51718132022-02-07 16:31:08 +00007922 } else {
7923 DCHECK(super_class->ShouldHaveEmbeddedVTable());
7924 raw_super_vtable = reinterpret_cast<uint8_t*>(super_class.Ptr()) +
7925 mirror::Class::EmbeddedVTableOffset(kPointerSize).Uint32Value();
7926 super_vtable_length = super_class->GetEmbeddedVTableLength();
Vladimir Marko7ddae992022-01-18 14:27:20 +00007927 }
7928 VTableAccessor super_vtable_accessor(raw_super_vtable, super_vtable_length);
Vladimir Marko8670e042021-12-21 17:55:48 +00007929 static constexpr double kMinLoadFactor = 0.3;
7930 static constexpr double kMaxLoadFactor = 0.5;
Vladimir Marko19366b82022-01-18 10:41:28 +00007931 static constexpr size_t kMaxStackBuferSize = 256;
7932 const size_t super_vtable_buffer_size = super_vtable_length * 3;
7933 const size_t declared_virtuals_buffer_size = num_virtual_methods * 3;
7934 const size_t total_buffer_size = super_vtable_buffer_size + declared_virtuals_buffer_size;
7935 uint32_t* super_vtable_buffer_ptr = (total_buffer_size <= kMaxStackBuferSize)
7936 ? reinterpret_cast<uint32_t*>(alloca(total_buffer_size * sizeof(uint32_t)))
7937 : allocator_.AllocArray<uint32_t>(total_buffer_size);
7938 uint32_t* declared_virtuals_buffer_ptr = super_vtable_buffer_ptr + super_vtable_buffer_size;
Vladimir Marko7ddae992022-01-18 14:27:20 +00007939 VTableSignatureSet super_vtable_signatures(
Vladimir Marko8670e042021-12-21 17:55:48 +00007940 kMinLoadFactor,
7941 kMaxLoadFactor,
Vladimir Marko7ddae992022-01-18 14:27:20 +00007942 VTableSignatureHash(super_vtable_accessor),
7943 VTableSignatureEqual(super_vtable_accessor),
Vladimir Marko19366b82022-01-18 10:41:28 +00007944 super_vtable_buffer_ptr,
7945 super_vtable_buffer_size,
Vladimir Marko8670e042021-12-21 17:55:48 +00007946 allocator_.Adapter());
Vladimir Markobed84ef2022-01-21 13:57:14 +00007947 ArrayRef<uint32_t> same_signature_vtable_lists;
Vladimir Marko8670e042021-12-21 17:55:48 +00007948 // Insert the first `mirror::Object::kVTableLength` indexes with pre-calculated hashes.
7949 DCHECK_GE(super_vtable_length, mirror::Object::kVTableLength);
7950 for (uint32_t i = 0; i != mirror::Object::kVTableLength; ++i) {
7951 size_t hash = class_linker_->object_virtual_method_hashes_[i];
Vladimir Marko163ebe22022-01-07 12:35:36 +00007952 // There are no duplicate signatures in `java.lang.Object`, so use `HashSet<>::PutWithHash()`.
7953 // This avoids equality comparison for the three `java.lang.Object.wait()` overloads.
7954 super_vtable_signatures.PutWithHash(i, hash);
Vladimir Marko8670e042021-12-21 17:55:48 +00007955 }
7956 // Insert the remaining indexes, check for duplicate signatures.
7957 if (super_vtable_length > mirror::Object::kVTableLength) {
7958 for (size_t i = mirror::Object::kVTableLength; i < super_vtable_length; ++i) {
7959 // Use `super_vtable_accessor` for getting the method for hash calculation.
7960 // Letting `HashSet<>::insert()` use the internal accessor copy in the hash
7961 // function prevents the compiler from optimizing this properly because the
7962 // compiler cannot prove that the accessor copy is immutable.
7963 size_t hash = ComputeMethodHash(super_vtable_accessor.GetVTableEntry(i));
7964 auto [it, inserted] = super_vtable_signatures.InsertWithHash(i, hash);
7965 if (UNLIKELY(!inserted)) {
Vladimir Markobed84ef2022-01-21 13:57:14 +00007966 if (same_signature_vtable_lists.empty()) {
7967 same_signature_vtable_lists = ArrayRef<uint32_t>(
7968 allocator_.AllocArray<uint32_t>(super_vtable_length), super_vtable_length);
7969 std::fill_n(same_signature_vtable_lists.data(), super_vtable_length, dex::kDexNoIndex);
Vladimir Marko8670e042021-12-21 17:55:48 +00007970 }
7971 DCHECK_LT(*it, i);
Vladimir Markobed84ef2022-01-21 13:57:14 +00007972 same_signature_vtable_lists[i] = *it;
Vladimir Marko8670e042021-12-21 17:55:48 +00007973 *it = i;
7974 }
7975 }
7976 }
7977
7978 // For each declared virtual method, look for a superclass virtual method
7979 // to override and assign a new vtable index if no method was overridden.
Vladimir Marko19366b82022-01-18 10:41:28 +00007980 DeclaredVirtualSignatureSet declared_virtual_signatures(
7981 kMinLoadFactor,
7982 kMaxLoadFactor,
7983 DeclaredVirtualSignatureHash(klass),
7984 DeclaredVirtualSignatureEqual(klass),
7985 declared_virtuals_buffer_ptr,
7986 declared_virtuals_buffer_size,
7987 allocator_.Adapter());
Vladimir Marko8670e042021-12-21 17:55:48 +00007988 const bool is_proxy_class = klass->IsProxyClass();
7989 size_t vtable_length = super_vtable_length;
Vladimir Marko19366b82022-01-18 10:41:28 +00007990 for (size_t i = 0; i != num_virtual_methods; ++i) {
Vladimir Marko8670e042021-12-21 17:55:48 +00007991 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
Vladimir Marko19366b82022-01-18 10:41:28 +00007992 DCHECK(!virtual_method->IsStatic()) << virtual_method->PrettyMethod();
Vladimir Marko8670e042021-12-21 17:55:48 +00007993 ArtMethod* signature_method = UNLIKELY(is_proxy_class)
7994 ? virtual_method->GetInterfaceMethodForProxyUnchecked(kPointerSize)
7995 : virtual_method;
7996 size_t hash = ComputeMethodHash(signature_method);
Vladimir Marko19366b82022-01-18 10:41:28 +00007997 declared_virtual_signatures.PutWithHash(i, hash);
Vladimir Marko8670e042021-12-21 17:55:48 +00007998 auto it = super_vtable_signatures.FindWithHash(signature_method, hash);
7999 if (it != super_vtable_signatures.end()) {
8000 size_t super_index = *it;
8001 DCHECK_LT(super_index, super_vtable_length);
8002 ArtMethod* super_method = super_vtable_accessor.GetVTableEntry(super_index);
8003 // Historical note: Before Android 4.1, an inaccessible package-private
8004 // superclass method would have been incorrectly overridden.
8005 bool overrides = klass->CanAccessMember(super_method->GetDeclaringClass(),
8006 super_method->GetAccessFlags());
Vladimir Markobed84ef2022-01-21 13:57:14 +00008007 if (UNLIKELY(!same_signature_vtable_lists.empty())) {
Vladimir Marko8670e042021-12-21 17:55:48 +00008008 // We override only the first accessible virtual method from superclass.
8009 // TODO: Override all methods that need to be overridden according to JLS. b/211854716
8010 size_t current_index = super_index;
Vladimir Markobed84ef2022-01-21 13:57:14 +00008011 while (same_signature_vtable_lists[current_index] != dex::kDexNoIndex) {
8012 DCHECK_LT(same_signature_vtable_lists[current_index], current_index);
8013 current_index = same_signature_vtable_lists[current_index];
Vladimir Marko8670e042021-12-21 17:55:48 +00008014 ArtMethod* current_method = super_vtable_accessor.GetVTableEntry(current_index);
8015 if (klass->CanAccessMember(current_method->GetDeclaringClass(),
8016 current_method->GetAccessFlags())) {
8017 overrides = true;
8018 super_index = current_index;
8019 super_method = current_method;
8020 }
8021 }
8022 }
8023 if (overrides) {
8024 if (super_method->IsFinal()) {
8025 sants.reset();
8026 ThrowLinkageError(klass, "Method %s overrides final method in class %s",
8027 virtual_method->PrettyMethod().c_str(),
8028 super_method->GetDeclaringClassDescriptor());
8029 return 0u;
8030 }
8031 virtual_method->SetMethodIndex(super_index);
8032 continue;
8033 }
8034 }
8035 // The method does not override any method from superclass, so it needs a new vtable index.
8036 virtual_method->SetMethodIndex(vtable_length);
8037 ++vtable_length;
8038 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008039
8040 // Assign vtable indexes for interface methods in new interfaces and store them
8041 // in implementation method arrays. These shall be replaced by actual method
8042 // pointers later. We do not need to do this for superclass interfaces as we can
8043 // get these vtable indexes from implementation methods in superclass iftable.
8044 // Record data for copied methods which shall be referenced by the vtable.
8045 const size_t ifcount = iftable->Count();
8046 ObjPtr<mirror::IfTable> super_iftable = super_class->GetIfTable();
8047 const size_t super_ifcount = super_iftable->Count();
8048 for (size_t i = ifcount; i != super_ifcount; ) {
8049 --i;
8050 DCHECK_LT(i, ifcount);
8051 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
8052 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
8053 size_t num_methods = (method_array != nullptr) ? method_array->GetLength() : 0u;
8054 for (size_t j = 0; j != num_methods; ++j) {
8055 ArtMethod* interface_method = iface->GetVirtualMethod(j, kPointerSize);
8056 size_t hash = ComputeMethodHash(interface_method);
8057 ArtMethod* vtable_method = nullptr;
8058 bool found = false;
8059 auto it1 = declared_virtual_signatures.FindWithHash(interface_method, hash);
8060 if (it1 != declared_virtual_signatures.end()) {
8061 vtable_method = klass->GetVirtualMethodDuringLinking(*it1, kPointerSize);
8062 found = true;
8063 } else {
8064 auto it2 = super_vtable_signatures.FindWithHash(interface_method, hash);
8065 if (it2 != super_vtable_signatures.end()) {
8066 // FIXME: If there are multiple vtable methods with the same signature, the one
8067 // with the highest vtable index is not nessarily the one in most-derived class.
8068 // However, we're preserving old behavior for now. b/211854716
8069 vtable_method = super_vtable_accessor.GetVTableEntry(*it2);
8070 found = true;
8071 }
8072 }
8073 uint32_t vtable_index = vtable_length;
8074 if (found) {
8075 DCHECK(vtable_method != nullptr);
8076 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
8077 sants.reset();
8078 ThrowIllegalAccessErrorForImplementingMethod(klass, vtable_method, interface_method);
8079 return 0u;
8080 }
8081 vtable_index = vtable_method->GetMethodIndexDuringLinking();
8082 if (!vtable_method->IsOverridableByDefaultMethod()) {
8083 method_array->SetElementPtrSize(j, vtable_index, kPointerSize);
8084 continue;
8085 }
8086 }
8087
8088 auto [it, inserted] = copied_method_records_.InsertWithHash(
8089 CopiedMethodRecord(interface_method, vtable_index), hash);
8090 if (found) {
8091 DCHECK_EQ(vtable_index, it->GetMethodIndex());
8092 } else if (inserted) {
8093 DCHECK_EQ(vtable_index, it->GetMethodIndex());
8094 DCHECK_EQ(vtable_index, vtable_length);
8095 ++vtable_length;
8096 } else {
8097 vtable_index = it->GetMethodIndex();
8098 }
8099 method_array->SetElementPtrSize(j, it->GetMethodIndex(), kPointerSize);
8100 if (inserted) {
8101 it->SetState(interface_method->IsAbstract() ? CopiedMethodRecord::State::kAbstractSingle
8102 : CopiedMethodRecord::State::kDefaultSingle);
8103 } else {
8104 it->UpdateState(iface, interface_method, vtable_index, iftable, ifcount, i);
8105 }
8106 }
8107 }
8108 // Finalize copied method records and check if we can reuse some methods from superclass vtable.
8109 size_t num_new_copied_methods = copied_method_records_.size();
8110 for (CopiedMethodRecord& record : copied_method_records_) {
8111 uint32_t vtable_index = record.GetMethodIndex();
8112 if (vtable_index < super_vtable_length) {
8113 ArtMethod* super_method = super_vtable_accessor.GetVTableEntry(record.GetMethodIndex());
8114 DCHECK(super_method->IsOverridableByDefaultMethod());
8115 record.FinalizeState(
8116 super_method, vtable_index, iftable, ifcount, super_iftable, super_ifcount);
8117 if (record.GetState() == CopiedMethodRecord::State::kUseSuperMethod) {
8118 --num_new_copied_methods;
8119 }
8120 }
8121 }
8122 num_new_copied_methods_ = num_new_copied_methods;
8123
Vladimir Marko8670e042021-12-21 17:55:48 +00008124 if (UNLIKELY(!IsUint<16>(vtable_length))) {
8125 sants.reset();
8126 ThrowClassFormatError(klass, "Too many methods defined on class: %zd", vtable_length);
8127 return 0u;
8128 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008129
Vladimir Marko8670e042021-12-21 17:55:48 +00008130 return vtable_length;
8131}
8132
8133template <PointerSize kPointerSize>
Vladimir Marko19366b82022-01-18 10:41:28 +00008134bool ClassLinker::LinkMethodsHelper<kPointerSize>::FindCopiedMethodsForInterface(
8135 ObjPtr<mirror::Class> klass,
8136 size_t num_virtual_methods,
8137 ObjPtr<mirror::IfTable> iftable) {
8138 DCHECK(klass->IsInterface());
8139 DCHECK(klass->HasSuperClass());
8140 DCHECK(klass->GetSuperClass()->IsObjectClass());
8141 DCHECK_EQ(klass->GetSuperClass()->GetIfTableCount(), 0);
8142
8143 // There should be no thread suspension unless we want to throw an exception.
8144 // (We are using `ObjPtr<>`s that are invalidated by thread suspension.)
8145 std::optional<ScopedAssertNoThreadSuspension> sants(__FUNCTION__);
8146
8147 // Prepare a `HashSet<>` with the declared virtual methods. These mask any methods
8148 // from superinterfaces, so we can filter out matching superinterface methods.
8149 static constexpr double kMinLoadFactor = 0.3;
8150 static constexpr double kMaxLoadFactor = 0.5;
8151 static constexpr size_t kMaxStackBuferSize = 256;
8152 const size_t declared_virtuals_buffer_size = num_virtual_methods * 3;
8153 uint32_t* declared_virtuals_buffer_ptr = (declared_virtuals_buffer_size <= kMaxStackBuferSize)
8154 ? reinterpret_cast<uint32_t*>(alloca(declared_virtuals_buffer_size * sizeof(uint32_t)))
8155 : allocator_.AllocArray<uint32_t>(declared_virtuals_buffer_size);
8156 DeclaredVirtualSignatureSet declared_virtual_signatures(
8157 kMinLoadFactor,
8158 kMaxLoadFactor,
8159 DeclaredVirtualSignatureHash(klass),
8160 DeclaredVirtualSignatureEqual(klass),
8161 declared_virtuals_buffer_ptr,
8162 declared_virtuals_buffer_size,
8163 allocator_.Adapter());
8164 for (size_t i = 0; i != num_virtual_methods; ++i) {
8165 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
8166 DCHECK(!virtual_method->IsStatic()) << virtual_method->PrettyMethod();
8167 size_t hash = ComputeMethodHash(virtual_method);
8168 declared_virtual_signatures.PutWithHash(i, hash);
8169 }
8170
8171 // We do not create miranda methods for interface classes, so we do not need to track
8172 // non-default (abstract) interface methods. The downside is that we cannot use the
8173 // optimized code paths with `CopiedMethodRecord::State::kDefaultSingle` and since
8174 // we do not fill method arrays for interfaces, the method search actually has to
8175 // compare signatures instead of searching for the implementing method.
8176 const size_t ifcount = iftable->Count();
8177 size_t new_method_index = num_virtual_methods;
8178 for (size_t i = ifcount; i != 0u; ) {
8179 --i;
8180 DCHECK_LT(i, ifcount);
8181 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
8182 if (!iface->HasDefaultMethods()) {
8183 continue; // No default methods to process.
8184 }
8185 size_t num_methods = iface->NumDeclaredVirtualMethods();
8186 for (size_t j = 0; j != num_methods; ++j) {
8187 ArtMethod* interface_method = iface->GetVirtualMethod(j, kPointerSize);
8188 if (!interface_method->IsDefault()) {
8189 continue; // Do not process this non-default method.
8190 }
8191 size_t hash = ComputeMethodHash(interface_method);
8192 auto it1 = declared_virtual_signatures.FindWithHash(interface_method, hash);
8193 if (it1 != declared_virtual_signatures.end()) {
8194 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(*it1, kPointerSize);
8195 if (!virtual_method->IsAbstract() && !virtual_method->IsPublic()) {
8196 sants.reset();
8197 ThrowIllegalAccessErrorForImplementingMethod(klass, virtual_method, interface_method);
8198 return false;
8199 }
8200 continue; // This default method is masked by a method declared in this interface.
8201 }
8202
8203 CopiedMethodRecord new_record(interface_method, new_method_index);
8204 auto it = copied_method_records_.FindWithHash(new_record, hash);
8205 if (it == copied_method_records_.end()) {
8206 // Pretend that there is another default method and try to update the state.
8207 // If the `interface_method` is not masked, the state shall change to
8208 // `kDefaultConflict`; if it is masked, the state remains `kDefault`.
8209 new_record.SetState(CopiedMethodRecord::State::kDefault);
8210 new_record.UpdateStateForInterface(iface, interface_method, iftable, ifcount, i);
8211 if (new_record.GetState() == CopiedMethodRecord::State::kDefaultConflict) {
8212 // Insert the new record with the state `kDefault`.
8213 new_record.SetState(CopiedMethodRecord::State::kDefault);
8214 copied_method_records_.PutWithHash(new_record, hash);
8215 DCHECK_EQ(new_method_index, new_record.GetMethodIndex());
8216 ++new_method_index;
8217 }
8218 } else {
8219 it->UpdateStateForInterface(iface, interface_method, iftable, ifcount, i);
8220 }
8221 }
8222 }
8223
8224 // Prune records without conflict. (Method indexes are updated in `ReallocMethods()`.)
8225 // We do not copy normal default methods to subinterfaces, instead we find the
8226 // default method with `Class::FindVirtualMethodForInterfaceSuper()` when needed.
8227 size_t num_new_copied_methods = copied_method_records_.size();
8228 for (CopiedMethodRecord& record : copied_method_records_) {
8229 if (record.GetState() != CopiedMethodRecord::State::kDefaultConflict) {
8230 DCHECK(record.GetState() == CopiedMethodRecord::State::kDefault);
8231 record.SetState(CopiedMethodRecord::State::kUseSuperMethod);
8232 --num_new_copied_methods;
8233 }
8234 }
8235 num_new_copied_methods_ = num_new_copied_methods;
8236
8237 return true;
8238}
8239
8240
8241template <PointerSize kPointerSize>
Vladimir Markob91402f2021-12-21 15:55:06 +00008242FLATTEN
Vladimir Marko78f62d82022-01-10 16:25:19 +00008243bool ClassLinker::LinkMethodsHelper<kPointerSize>::LinkMethods(
Vladimir Markobc893672021-11-10 15:25:46 +00008244 Thread* self,
Vladimir Marko78f62d82022-01-10 16:25:19 +00008245 Handle<mirror::Class> klass,
8246 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
8247 bool* out_new_conflict,
8248 ArtMethod** out_imt) {
Vladimir Markobc893672021-11-10 15:25:46 +00008249 const size_t num_virtual_methods = klass->NumVirtualMethods();
8250 if (klass->IsInterface()) {
8251 // No vtable.
8252 if (!IsUint<16>(num_virtual_methods)) {
8253 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
8254 return false;
8255 }
8256 bool has_defaults = false;
8257 // Assign each method an IMT index and set the default flag.
8258 for (size_t i = 0; i < num_virtual_methods; ++i) {
Vladimir Markob91402f2021-12-21 15:55:06 +00008259 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
Vladimir Markobc893672021-11-10 15:25:46 +00008260 m->SetMethodIndex(i);
8261 if (!m->IsAbstract()) {
8262 // If the dex file does not support default methods, throw ClassFormatError.
8263 // This check is necessary to protect from odd cases, such as native default
8264 // methods, that the dex file verifier permits for old dex file versions. b/157170505
8265 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
8266 // currently running CTS tests for default methods with dex file version 035 which
8267 // does not support default methods. So, we limit this to native methods. b/157718952
8268 if (m->IsNative()) {
8269 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
8270 ThrowClassFormatError(klass.Get(),
8271 "Dex file does not support default method '%s'",
8272 m->PrettyMethod().c_str());
8273 return false;
8274 }
Vladimir Markofd0aec42022-01-27 14:27:24 +00008275 if (!m->IsPublic()) {
8276 // The verifier should have caught the non-public method for dex version 37.
8277 // Just warn and skip it since this is from before default-methods so we don't
8278 // really need to care that it has code.
8279 LOG(WARNING) << "Default interface method " << m->PrettyMethod() << " is not public! "
8280 << "This will be a fatal error in subsequent versions of android. "
8281 << "Continuing anyway.";
8282 }
Vladimir Markobc893672021-11-10 15:25:46 +00008283 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
8284 has_defaults = true;
8285 }
8286 }
8287 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
8288 // during initialization. This is a performance optimization. We could simply traverse the
8289 // virtual_methods_ array again during initialization.
8290 if (has_defaults) {
8291 klass->SetHasDefaultMethods();
8292 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008293 ObjPtr<mirror::IfTable> iftable = SetupInterfaceLookupTable(
8294 self, klass, &allocator_, NonProxyInterfacesAccessor(class_linker_, klass));
8295 if (UNLIKELY(iftable == nullptr)) {
8296 self->AssertPendingException();
8297 return false;
8298 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008299 size_t ifcount = iftable->Count();
8300 bool have_super_with_defaults = false;
8301 for (size_t i = 0; i != ifcount; ++i) {
8302 if (iftable->GetInterface(i)->HasDefaultMethods()) {
8303 have_super_with_defaults = true;
8304 break;
8305 }
8306 }
8307 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8308 if (have_super_with_defaults) {
8309 if (!FindCopiedMethodsForInterface(klass.Get(), num_virtual_methods, iftable)) {
8310 self->AssertPendingException();
8311 return false;
8312 }
8313 if (num_new_copied_methods_ != 0u) {
8314 // Re-check the number of methods.
8315 size_t final_num_virtual_methods = num_virtual_methods + num_new_copied_methods_;
8316 if (!IsUint<16>(final_num_virtual_methods)) {
8317 ThrowClassFormatError(
8318 klass.Get(), "Too many methods on interface: %zu", final_num_virtual_methods);
8319 return false;
8320 }
8321 ReallocMethods(klass.Get());
8322 }
8323 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008324 klass->SetIfTable(iftable);
Vladimir Marko19366b82022-01-18 10:41:28 +00008325 if (kIsDebugBuild) {
8326 // May cause thread suspension, so do this after we're done with `ObjPtr<> iftable`.
8327 ClobberOldMethods(old_methods, klass->GetMethodsPtr());
8328 }
8329 return true;
Vladimir Markob91402f2021-12-21 15:55:06 +00008330 } else if (LIKELY(klass->HasSuperClass())) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00008331 // We set up the interface lookup table now because we need it to determine if we need
8332 // to update any vtable entries with new default method implementations.
Vladimir Markobc893672021-11-10 15:25:46 +00008333 StackHandleScope<3> hs(self);
Vladimir Marko0441d202022-02-18 13:55:15 +00008334 MutableHandle<mirror::IfTable> iftable = hs.NewHandle(UNLIKELY(klass->IsProxyClass())
Vladimir Marko78f62d82022-01-10 16:25:19 +00008335 ? SetupInterfaceLookupTable(self, klass, &allocator_, ProxyInterfacesAccessor(interfaces))
8336 : SetupInterfaceLookupTable(
8337 self, klass, &allocator_, NonProxyInterfacesAccessor(class_linker_, klass)));
8338 if (UNLIKELY(iftable == nullptr)) {
8339 self->AssertPendingException();
8340 return false;
8341 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008342
Vladimir Marko51718132022-02-07 16:31:08 +00008343 // Copy the IMT from superclass if present and needed. Update with new methods later.
Vladimir Marko0441d202022-02-18 13:55:15 +00008344 Handle<mirror::Class> super_class = hs.NewHandle(klass->GetSuperClass());
Vladimir Marko51718132022-02-07 16:31:08 +00008345 bool is_klass_abstract = klass->IsAbstract();
8346 bool is_super_abstract = super_class->IsAbstract();
8347 DCHECK_EQ(klass->ShouldHaveImt(), !is_klass_abstract);
8348 DCHECK_EQ(super_class->ShouldHaveImt(), !is_super_abstract);
8349 if (!is_klass_abstract && !is_super_abstract) {
8350 ImTable* super_imt = super_class->GetImt(kPointerSize);
8351 for (size_t i = 0; i < ImTable::kSize; ++i) {
8352 out_imt[i] = super_imt->Get(i, kPointerSize);
8353 }
8354 }
8355
8356 // If there are no new virtual methods and no new interfaces, we can simply reuse
8357 // the vtable from superclass. We may need to make a copy if it's embedded.
Vladimir Marko0441d202022-02-18 13:55:15 +00008358 const size_t super_vtable_length = super_class->GetVTableLength();
Vladimir Marko0f71b192022-02-02 17:20:12 +00008359 if (num_virtual_methods == 0 && iftable.Get() == super_class->GetIfTable()) {
Vladimir Marko51718132022-02-07 16:31:08 +00008360 DCHECK_EQ(is_super_abstract, !super_class->ShouldHaveEmbeddedVTable());
8361 if (is_super_abstract) {
8362 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
8363 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
8364 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
8365 klass->SetVTable(super_vtable);
8366 // No IMT in the super class, we need to reconstruct it from the iftable.
8367 if (!is_klass_abstract && iftable->Count() != 0) {
8368 class_linker_->FillIMTFromIfTable(iftable.Get(),
8369 runtime_->GetImtUnimplementedMethod(),
8370 runtime_->GetImtConflictMethod(),
8371 klass.Get(),
8372 /*create_conflict_tables=*/false,
8373 /*ignore_copied_methods=*/false,
8374 out_new_conflict,
8375 out_imt);
8376 }
8377 } else {
Vladimir Marko0441d202022-02-18 13:55:15 +00008378 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, super_vtable_length);
Vladimir Marko8670e042021-12-21 17:55:48 +00008379 if (UNLIKELY(vtable == nullptr)) {
8380 self->AssertPendingOOMException();
Vladimir Markobc893672021-11-10 15:25:46 +00008381 return false;
8382 }
Vladimir Marko8670e042021-12-21 17:55:48 +00008383 for (size_t i = 0; i < super_vtable_length; i++) {
8384 vtable->SetElementPtrSize(
8385 i, super_class->GetEmbeddedVTableEntry(i, kPointerSize), kPointerSize);
8386 }
8387 klass->SetVTable(vtable);
Vladimir Marko51718132022-02-07 16:31:08 +00008388 // The IMT was already copied from superclass if `klass` is not abstract.
Vladimir Marko8670e042021-12-21 17:55:48 +00008389 }
Vladimir Markobed84ef2022-01-21 13:57:14 +00008390 klass->SetIfTable(iftable.Get());
Vladimir Marko8670e042021-12-21 17:55:48 +00008391 return true;
8392 }
8393
Vladimir Markobed84ef2022-01-21 13:57:14 +00008394 // Allocate method arrays, so that we can link interface methods without thread suspension,
8395 // otherwise GC could miss visiting newly allocated copied methods.
8396 // TODO: Do not allocate copied methods during linking, store only records about what
8397 // we need to allocate and allocate it at the end. Start with superclass iftable and
8398 // perform copy-on-write when needed to facilitate maximum memory sharing.
Vladimir Marko0441d202022-02-18 13:55:15 +00008399 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8400 self->AssertPendingOOMException();
Vladimir Markobed84ef2022-01-21 13:57:14 +00008401 return false;
8402 }
8403
Vladimir Marko51718132022-02-07 16:31:08 +00008404 size_t final_vtable_size = AssignVTableIndexes(
8405 klass.Get(), super_class.Get(), is_super_abstract, num_virtual_methods, iftable.Get());
Vladimir Marko8670e042021-12-21 17:55:48 +00008406 if (final_vtable_size == 0u) {
8407 self->AssertPendingException();
8408 return false;
8409 }
8410 DCHECK(IsUint<16>(final_vtable_size));
8411
8412 // Allocate the new vtable.
Vladimir Marko0441d202022-02-18 13:55:15 +00008413 Handle<mirror::PointerArray> vtable = hs.NewHandle(AllocPointerArray(self, final_vtable_size));
Vladimir Marko8670e042021-12-21 17:55:48 +00008414 if (UNLIKELY(vtable == nullptr)) {
8415 self->AssertPendingOOMException();
8416 return false;
8417 }
8418
Vladimir Marko19366b82022-01-18 10:41:28 +00008419 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8420 if (num_new_copied_methods_ != 0u) {
8421 ReallocMethods(klass.Get());
8422 }
8423
Vladimir Marko8670e042021-12-21 17:55:48 +00008424 // Store new virtual methods in the new vtable.
8425 for (ArtMethod& virtual_method : klass->GetVirtualMethodsSliceUnchecked(kPointerSize)) {
8426 int32_t vtable_index = virtual_method.GetMethodIndexDuringLinking();
8427 vtable->SetElementPtrSize(vtable_index, &virtual_method, kPointerSize);
8428 }
8429
8430 // For non-overridden vtable slots, copy a method from `super_class`.
8431 for (size_t j = 0; j != super_vtable_length; ++j) {
Vladimir Marko19366b82022-01-18 10:41:28 +00008432 if (vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j) == nullptr) {
8433 ArtMethod* super_method = super_class->GetVTableEntry(j, kPointerSize);
8434 vtable->SetElementPtrSize(j, super_method, kPointerSize);
Vladimir Markobc893672021-11-10 15:25:46 +00008435 }
8436 }
Vladimir Marko8670e042021-12-21 17:55:48 +00008437
Vladimir Marko51718132022-02-07 16:31:08 +00008438 // Update the `iftable` (and IMT) with finalized virtual methods.
Vladimir Marko0441d202022-02-18 13:55:15 +00008439 if (!FinalizeIfTable(klass,
8440 iftable,
8441 vtable,
8442 is_klass_abstract,
8443 is_super_abstract,
8444 out_new_conflict,
8445 out_imt)) {
8446 self->AssertPendingOOMException();
8447 return false;
8448 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008449
Vladimir Markobc893672021-11-10 15:25:46 +00008450 klass->SetVTable(vtable.Get());
Vladimir Marko19366b82022-01-18 10:41:28 +00008451 klass->SetIfTable(iftable.Get());
8452 if (kIsDebugBuild) {
8453 CheckVTable(self, klass, kPointerSize);
8454 ClobberOldMethods(old_methods, klass->GetMethodsPtr());
8455 }
8456 return true;
Vladimir Markobc893672021-11-10 15:25:46 +00008457 } else {
Vladimir Marko78f62d82022-01-10 16:25:19 +00008458 return LinkJavaLangObjectMethods(self, klass);
Vladimir Markobc893672021-11-10 15:25:46 +00008459 }
Vladimir Markobc893672021-11-10 15:25:46 +00008460}
8461
Vladimir Markob91402f2021-12-21 15:55:06 +00008462template <PointerSize kPointerSize>
Vladimir Marko78f62d82022-01-10 16:25:19 +00008463bool ClassLinker::LinkMethodsHelper<kPointerSize>::LinkJavaLangObjectMethods(
Vladimir Markob91402f2021-12-21 15:55:06 +00008464 Thread* self,
8465 Handle<mirror::Class> klass) {
8466 DCHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(class_linker_));
8467 DCHECK_EQ(klass->NumVirtualMethods(), mirror::Object::kVTableLength);
8468 static_assert(IsUint<16>(mirror::Object::kVTableLength));
Vladimir Marko0441d202022-02-18 13:55:15 +00008469 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, mirror::Object::kVTableLength);
Vladimir Markob91402f2021-12-21 15:55:06 +00008470 if (UNLIKELY(vtable == nullptr)) {
8471 self->AssertPendingOOMException();
8472 return false;
8473 }
8474 for (size_t i = 0; i < mirror::Object::kVTableLength; ++i) {
8475 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
8476 vtable->SetElementPtrSize(i, virtual_method, kPointerSize);
8477 virtual_method->SetMethodIndex(i);
8478 }
8479 klass->SetVTable(vtable);
8480 InitializeObjectVirtualMethodHashes(
8481 klass.Get(),
8482 kPointerSize,
8483 ArrayRef<uint32_t>(class_linker_->object_virtual_method_hashes_));
Vladimir Marko78f62d82022-01-10 16:25:19 +00008484 // The interface table is already allocated but there are no interface methods to link.
8485 DCHECK(klass->GetIfTable() != nullptr);
8486 DCHECK_EQ(klass->GetIfTableCount(), 0);
Vladimir Markob91402f2021-12-21 15:55:06 +00008487 return true;
8488}
8489
Vladimir Markobc893672021-11-10 15:25:46 +00008490// Populate the class vtable and itable. Compute return type indices.
8491bool ClassLinker::LinkMethods(Thread* self,
8492 Handle<mirror::Class> klass,
8493 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
8494 bool* out_new_conflict,
8495 ArtMethod** out_imt) {
8496 self->AllowThreadSuspension();
Vladimir Markobc893672021-11-10 15:25:46 +00008497 // Link virtual methods then interface methods.
8498 Runtime* const runtime = Runtime::Current();
Vladimir Markob91402f2021-12-21 15:55:06 +00008499 if (LIKELY(GetImagePointerSize() == kRuntimePointerSize)) {
8500 LinkMethodsHelper<kRuntimePointerSize> helper(this, klass, self, runtime);
Vladimir Marko78f62d82022-01-10 16:25:19 +00008501 return helper.LinkMethods(self, klass, interfaces, out_new_conflict, out_imt);
Vladimir Markob91402f2021-12-21 15:55:06 +00008502 } else {
8503 constexpr PointerSize kOtherPointerSize =
8504 (kRuntimePointerSize == PointerSize::k64) ? PointerSize::k32 : PointerSize::k64;
8505 LinkMethodsHelper<kOtherPointerSize> helper(this, klass, self, runtime);
Vladimir Marko78f62d82022-01-10 16:25:19 +00008506 return helper.LinkMethods(self, klass, interfaces, out_new_conflict, out_imt);
Vladimir Markob91402f2021-12-21 15:55:06 +00008507 }
Vladimir Markobc893672021-11-10 15:25:46 +00008508}
8509
Vladimir Marko42bee502021-01-28 14:58:35 +00008510class ClassLinker::LinkFieldsHelper {
8511 public:
8512 static bool LinkFields(ClassLinker* class_linker,
8513 Thread* self,
8514 Handle<mirror::Class> klass,
8515 bool is_static,
8516 size_t* class_size)
8517 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008518
Vladimir Marko42bee502021-01-28 14:58:35 +00008519 private:
8520 enum class FieldTypeOrder : uint16_t;
8521 class FieldGaps;
8522
8523 struct FieldTypeOrderAndIndex {
8524 FieldTypeOrder field_type_order;
8525 uint16_t field_index;
8526 };
8527
8528 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8529
8530 template <size_t kSize>
8531 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8532 REQUIRES_SHARED(Locks::mutator_lock_);
8533};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008534
Vladimir Markoc7993d52021-01-27 15:20:56 +00008535// We use the following order of field types for assigning offsets.
8536// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008537enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008538 kReference = 0u,
8539 kLong,
8540 kDouble,
8541 kInt,
8542 kFloat,
8543 kChar,
8544 kShort,
8545 kBoolean,
8546 kByte,
8547
8548 kLast64BitType = kDouble,
8549 kLast32BitType = kFloat,
8550 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008551};
8552
Vladimir Markoc7993d52021-01-27 15:20:56 +00008553ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008554ClassLinker::LinkFieldsHelper::FieldTypeOrder
8555ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008556 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008557 case 'J':
8558 return FieldTypeOrder::kLong;
8559 case 'D':
8560 return FieldTypeOrder::kDouble;
8561 case 'I':
8562 return FieldTypeOrder::kInt;
8563 case 'F':
8564 return FieldTypeOrder::kFloat;
8565 case 'C':
8566 return FieldTypeOrder::kChar;
8567 case 'S':
8568 return FieldTypeOrder::kShort;
8569 case 'Z':
8570 return FieldTypeOrder::kBoolean;
8571 case 'B':
8572 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008573 default:
8574 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8575 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008576 }
8577}
8578
8579// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008580class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008581 public:
8582 template <uint32_t kSize>
8583 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8584 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8585 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8586 uint32_t gap_start = field_offset.Uint32Value();
8587 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8588 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8589 }
8590 return field_offset;
8591 }
8592
8593 template <uint32_t kSize>
8594 bool HasGap() const {
8595 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8596 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8597 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8598 gap4_offset_ != kNoOffset;
8599 }
8600
8601 template <uint32_t kSize>
8602 MemberOffset ReleaseGap() {
8603 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8604 uint32_t result;
8605 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8606 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8607 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8608 result = gap1_offset_;
8609 gap1_offset_ = kNoOffset;
8610 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8611 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8612 result = gap2_offset_;
8613 gap2_offset_ = kNoOffset;
8614 if (kSize < 2u) {
8615 AddGaps<1u>(result + kSize, result + 2u);
8616 }
8617 } else {
8618 DCHECK_NE(gap4_offset_, kNoOffset);
8619 result = gap4_offset_;
8620 gap4_offset_ = kNoOffset;
8621 if (kSize < 4u) {
8622 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8623 }
8624 }
8625 return MemberOffset(result);
8626 }
8627
8628 private:
8629 template <uint32_t kGapsToCheck>
8630 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8631 if ((kGapsToCheck & 1u) != 0u) {
8632 DCHECK_LT(gap_start, gap_end);
8633 DCHECK_ALIGNED(gap_end, 2u);
8634 if ((gap_start & 1u) != 0u) {
8635 DCHECK_EQ(gap1_offset_, kNoOffset);
8636 gap1_offset_ = gap_start;
8637 gap_start += 1u;
8638 if (kGapsToCheck == 1u || gap_start == gap_end) {
8639 DCHECK_EQ(gap_start, gap_end);
8640 return;
8641 }
8642 }
8643 }
8644
8645 if ((kGapsToCheck & 2u) != 0u) {
8646 DCHECK_LT(gap_start, gap_end);
8647 DCHECK_ALIGNED(gap_start, 2u);
8648 DCHECK_ALIGNED(gap_end, 4u);
8649 if ((gap_start & 2u) != 0u) {
8650 DCHECK_EQ(gap2_offset_, kNoOffset);
8651 gap2_offset_ = gap_start;
8652 gap_start += 2u;
8653 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8654 DCHECK_EQ(gap_start, gap_end);
8655 return;
8656 }
8657 }
8658 }
8659
8660 if ((kGapsToCheck & 4u) != 0u) {
8661 DCHECK_LT(gap_start, gap_end);
8662 DCHECK_ALIGNED(gap_start, 4u);
8663 DCHECK_ALIGNED(gap_end, 8u);
8664 DCHECK_EQ(gap_start + 4u, gap_end);
8665 DCHECK_EQ(gap4_offset_, kNoOffset);
8666 gap4_offset_ = gap_start;
8667 return;
8668 }
8669
8670 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8671 << " after checking " << kGapsToCheck;
8672 }
8673
8674 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8675
8676 uint32_t gap4_offset_ = kNoOffset;
8677 uint32_t gap2_offset_ = kNoOffset;
8678 uint32_t gap1_offset_ = kNoOffset;
8679};
8680
8681template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008682ALWAYS_INLINE
8683MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8684 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008685 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8686 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8687 field->SetOffset(field_offset);
8688 return MemberOffset(field_offset.Uint32Value() + kSize);
8689}
8690
Vladimir Marko42bee502021-01-28 14:58:35 +00008691bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8692 Thread* self,
8693 Handle<mirror::Class> klass,
8694 bool is_static,
8695 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008696 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008697 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008698 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8699 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008700
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008701 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008702 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008703 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008704 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8705 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008706 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008707 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008708 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008709 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008710 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008711 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008712 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008713 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008714
David Sehr709b0702016-10-13 09:12:37 -07008715 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008716
Brian Carlstromdbc05252011-09-09 01:59:59 -07008717 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008718 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008719 //
8720 // The overall sort order order is:
8721 // 1) All object reference fields, sorted alphabetically.
8722 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8723 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8724 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8725 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8726 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8727 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8728 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8729 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8730 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008731 // (References are first to increase the chance of reference visiting
8732 // being able to take a fast path using a bitmap of references at the
8733 // start of the object, see `Class::reference_instance_offsets_`.)
8734 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008735 // Once the fields are sorted in this order we will attempt to fill any gaps
8736 // that might be present in the memory layout of the structure.
8737 // Note that we shall not fill gaps between the superclass fields.
8738
8739 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008740 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008741 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008742 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8743 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8744 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8745 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008746 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008747 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008748 } else {
8749 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008750 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008751 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008752 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008753 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008754 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008755 for (size_t i = 0; i != num_fields; ++i) {
8756 ArtField* field = &fields->At(i);
8757 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008758 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8759 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008760 // Insert references to the start, other fields to the end.
8761 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008762 if (field_type_order == FieldTypeOrder::kReference) {
8763 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008764 ++num_reference_fields;
8765 } else {
8766 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008767 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008768 }
8769 }
8770 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008771
Vladimir Marko42bee502021-01-28 14:58:35 +00008772 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008773 DCHECK(std::is_sorted(
8774 sorted_fields.begin(),
8775 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008776 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8777 ArtField* lhs_field = &fields->At(lhs.field_index);
8778 ArtField* rhs_field = &fields->At(rhs.field_index);
8779 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8780 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8781 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8782 lhs.field_index < rhs.field_index);
8783 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008784 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008785 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008786 DCHECK(std::is_sorted(
8787 sorted_fields.begin() + primitive_fields_start,
8788 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008789 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8790 ArtField* lhs_field = &fields->At(lhs.field_index);
8791 ArtField* rhs_field = &fields->At(rhs.field_index);
8792 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8793 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8794 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8795 lhs.field_index > rhs.field_index);
8796 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008797 }));
8798 // Sort the primitive fields by the field type order, then field index.
8799 std::sort(sorted_fields.begin() + primitive_fields_start,
8800 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008801 [](const auto& lhs, const auto& rhs) {
8802 if (lhs.field_type_order != rhs.field_type_order) {
8803 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008804 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008805 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008806 }
8807 });
8808 // Primitive fields are now sorted by field size (descending), then type, then field index.
8809 DCHECK(std::is_sorted(
8810 sorted_fields.begin() + primitive_fields_start,
8811 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008812 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8813 ArtField* lhs_field = &fields->At(lhs.field_index);
8814 ArtField* rhs_field = &fields->At(rhs.field_index);
8815 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008816 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008817 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008818 CHECK_NE(rhs_type, Primitive::kPrimNot);
8819 if (lhs_type != rhs_type) {
8820 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8821 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8822 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8823 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008824 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008825 }
8826 }));
8827
8828 // Process reference fields.
8829 FieldGaps field_gaps;
8830 size_t index = 0u;
8831 if (num_reference_fields != 0u) {
8832 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8833 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8834 for (; index != num_reference_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008835 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008836 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008837 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008838 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008839 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008840 if (index != num_fields &&
8841 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008842 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008843 while (index != num_fields &&
8844 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8845 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008846 field_offset = AssignFieldOffset<8u>(field, field_offset);
8847 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008848 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008849 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008850 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008851 if (index != num_fields &&
8852 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008853 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8854 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008855 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008856 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8857 ++index;
8858 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8859 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008860 while (index != num_fields &&
8861 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8862 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008863 field_offset = AssignFieldOffset<4u>(field, field_offset);
8864 ++index;
8865 }
8866 }
8867 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008868 if (index != num_fields &&
8869 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008870 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8871 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008872 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008873 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008874 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008875 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8876 ++index;
8877 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008878 while (index != num_fields &&
8879 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8880 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008881 field_offset = AssignFieldOffset<2u>(field, field_offset);
8882 ++index;
8883 }
8884 }
8885 // Process 8-bit fields.
8886 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008887 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008888 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8889 }
8890 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008891 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008892 field_offset = AssignFieldOffset<1u>(field, field_offset);
8893 }
8894
Ian Rogers7b078e82014-09-10 14:44:24 -07008895 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008896
Elliott Hughesadb460d2011-10-05 17:02:34 -07008897 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00008898 DCHECK_IMPLIES(class_linker->init_done_, !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
Vladimir Marko42bee502021-01-28 14:58:35 +00008899 if (!is_static &&
8900 UNLIKELY(!class_linker->init_done_) &&
8901 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008902 // We know there are no non-reference fields in the Reference classes, and we know
8903 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008904 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008905 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008906 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008907 --num_reference_fields;
8908 }
8909
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008910 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008911 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008912 if (is_static) {
8913 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008914 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008915 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008916 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008917 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008918 if (num_reference_fields == 0 || super_class == nullptr) {
8919 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008920 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008921 if (super_class == nullptr ||
8922 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8923 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008924 }
8925 }
8926 if (kIsDebugBuild) {
8927 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8928 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008929 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008930 while (cur_super != nullptr) {
8931 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8932 cur_super = cur_super->GetSuperClass();
8933 }
8934 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008935 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008936 } else {
8937 // Check that there is at least num_reference_fields other than Object.class.
8938 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008939 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008940 }
8941 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008942 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008943 std::string temp;
8944 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8945 size_t previous_size = klass->GetObjectSize();
8946 if (previous_size != 0) {
8947 // Make sure that we didn't originally have an incorrect size.
8948 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008949 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008950 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008951 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008952 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008953
8954 if (kIsDebugBuild) {
8955 // Make sure that the fields array is ordered by name but all reference
8956 // offsets are at the beginning as far as alignment allows.
8957 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00008958 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008959 : klass->GetFirstReferenceInstanceFieldOffset();
8960 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8961 num_reference_fields *
8962 sizeof(mirror::HeapReference<mirror::Object>));
8963 MemberOffset current_ref_offset = start_ref_offset;
8964 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008965 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008966 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008967 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8968 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008969 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008970 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008971 // NOTE: The field names can be the same. This is not possible in the Java language
8972 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008973 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008974 }
8975 Primitive::Type type = field->GetTypeAsPrimitiveType();
8976 bool is_primitive = type != Primitive::kPrimNot;
8977 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8978 strcmp("referent", field->GetName()) == 0) {
8979 is_primitive = true; // We lied above, so we have to expect a lie here.
8980 }
8981 MemberOffset offset = field->GetOffsetDuringLinking();
8982 if (is_primitive) {
8983 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8984 // Shuffled before references.
8985 size_t type_size = Primitive::ComponentSize(type);
8986 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8987 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8988 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8989 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8990 }
8991 } else {
8992 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8993 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8994 sizeof(mirror::HeapReference<mirror::Object>));
8995 }
8996 }
8997 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8998 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008999 return true;
9000}
9001
Vladimir Marko42bee502021-01-28 14:58:35 +00009002bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
9003 CHECK(klass != nullptr);
9004 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
9005}
9006
9007bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
9008 CHECK(klass != nullptr);
9009 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
9010}
9011
Vladimir Marko76649e82014-11-10 18:32:59 +00009012// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07009013void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009014 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009015 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009016 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009017 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009018 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009019 // Compute reference offsets unless our superclass overflowed.
9020 if (reference_offsets != mirror::Class::kClassWalkSuper) {
9021 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00009022 if (num_reference_fields != 0u) {
9023 // All of the fields that contain object references are guaranteed be grouped in memory
9024 // starting at an appropriately aligned address after super class object data.
9025 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
9026 sizeof(mirror::HeapReference<mirror::Object>));
9027 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009028 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00009029 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009030 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009031 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00009032 reference_offsets |= (0xffffffffu << start_bit) &
9033 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009034 }
9035 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07009036 }
9037 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07009038 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009039}
9040
Vladimir Marko18090d12018-06-01 16:53:12 +01009041ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
9042 ObjPtr<mirror::DexCache> dex_cache) {
9043 StackHandleScope<1> hs(Thread::Current());
9044 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
9045 return DoResolveString(string_idx, h_dex_cache);
9046}
9047
9048ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
9049 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00009050 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07009051 uint32_t utf16_length;
9052 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009053 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00009054 if (string != nullptr) {
9055 dex_cache->SetResolvedString(string_idx, string);
9056 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00009057 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009058}
9059
Vladimir Marko18090d12018-06-01 16:53:12 +01009060ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
9061 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009062 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00009063 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00009064 uint32_t utf16_length;
9065 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08009066 ObjPtr<mirror::String> string =
9067 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00009068 if (string != nullptr) {
9069 dex_cache->SetResolvedString(string_idx, string);
9070 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00009071 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00009072}
9073
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009074ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01009075 ObjPtr<mirror::Class> referrer) {
9076 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
9077}
9078
9079ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009080 ObjPtr<mirror::DexCache> dex_cache,
9081 ObjPtr<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009082 DCHECK(dex_cache->GetClassLoader() == class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009083 const DexFile& dex_file = *dex_cache->GetDexFile();
9084 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Vladimir Markoc63d9672021-03-31 15:50:39 +01009085 ObjPtr<mirror::Class> type = LookupResolvedType(descriptor, class_loader);
9086 if (type != nullptr) {
9087 DCHECK(type->IsResolved());
9088 dex_cache->SetResolvedType(type_idx, type);
9089 }
9090 return type;
9091}
9092
9093ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const char* descriptor,
9094 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009095 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
9096 ObjPtr<mirror::Class> type = nullptr;
9097 if (descriptor[1] == '\0') {
9098 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
9099 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00009100 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009101 } else {
9102 Thread* const self = Thread::Current();
9103 DCHECK(self != nullptr);
9104 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
9105 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01009106 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009107 }
Vladimir Markoc63d9672021-03-31 15:50:39 +01009108 return (type != nullptr && type->IsResolved()) ? type : nullptr;
Mathieu Chartierb8901302016-09-30 10:27:43 -07009109}
9110
Andreas Gampeb0625e02019-05-01 12:43:31 -07009111template <typename RefType>
9112ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01009113 StackHandleScope<2> hs(Thread::Current());
9114 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9115 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
9116 return DoResolveType(type_idx, dex_cache, class_loader);
9117}
9118
Andreas Gampe4835d212018-11-21 14:55:10 -08009119// Instantiate the above.
9120template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9121 ArtField* referrer);
9122template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9123 ArtMethod* referrer);
9124template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9125 ObjPtr<mirror::Class> referrer);
9126
Vladimir Marko09c5ca42018-05-31 15:15:31 +01009127ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009128 Handle<mirror::DexCache> dex_cache,
9129 Handle<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009130 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009131 Thread* self = Thread::Current();
9132 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
9133 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
9134 if (resolved != nullptr) {
9135 // TODO: we used to throw here if resolved's class loader was not the
9136 // boot class loader. This was to permit different classes with the
9137 // same name to be loaded simultaneously by different loaders
9138 dex_cache->SetResolvedType(type_idx, resolved);
9139 } else {
9140 CHECK(self->IsExceptionPending())
9141 << "Expected pending exception for failed resolution of: " << descriptor;
9142 // Convert a ClassNotFoundException to a NoClassDefFoundError.
9143 StackHandleScope<1> hs(self);
9144 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009145 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009146 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
9147 self->ClearException();
9148 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
9149 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009150 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009151 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00009152 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07009153 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00009154 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009155}
9156
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009157ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
9158 ObjPtr<mirror::DexCache> dex_cache,
9159 ObjPtr<mirror::ClassLoader> class_loader,
9160 uint32_t method_idx) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009161 DCHECK(dex_cache->GetClassLoader() == class_loader);
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009162 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
9163 // functions can optimize the search if the dex_cache is the same as the DexCache
9164 // of the class, with fall-back to name and signature search otherwise.
9165 ArtMethod* resolved = nullptr;
9166 if (klass->IsInterface()) {
9167 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9168 } else {
9169 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9170 }
9171 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009172 if (resolved != nullptr &&
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009173 // We pass AccessMethod::kNone instead of kLinking to not warn yet on the
9174 // access, as we'll be looking if the method can be accessed through an
9175 // interface.
David Brazdilf50ac102018-10-17 18:00:06 +01009176 hiddenapi::ShouldDenyAccessToMember(resolved,
9177 hiddenapi::AccessContext(class_loader, dex_cache),
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009178 hiddenapi::AccessMethod::kNone)) {
9179 // The resolved method that we have found cannot be accessed due to
9180 // hiddenapi (typically it is declared up the hierarchy and is not an SDK
9181 // method). Try to find an interface method from the implemented interfaces which is
Nicolas Geoffrayaf61f502021-03-31 16:03:50 +00009182 // part of the SDK.
9183 ArtMethod* itf_method = klass->FindAccessibleInterfaceMethod(resolved, image_pointer_size_);
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009184 if (itf_method == nullptr) {
9185 // No interface method. Call ShouldDenyAccessToMember again but this time
9186 // with AccessMethod::kLinking to ensure that an appropriate warning is
9187 // logged.
9188 hiddenapi::ShouldDenyAccessToMember(resolved,
9189 hiddenapi::AccessContext(class_loader, dex_cache),
9190 hiddenapi::AccessMethod::kLinking);
9191 resolved = nullptr;
9192 } else {
9193 // We found an interface method that is accessible, continue with the resolved method.
9194 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009195 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009196 if (resolved != nullptr) {
9197 // In case of jmvti, the dex file gets verified before being registered, so first
9198 // check if it's registered before checking class tables.
9199 const DexFile& dex_file = *dex_cache->GetDexFile();
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00009200 DCHECK_IMPLIES(
9201 IsDexFileRegistered(Thread::Current(), dex_file),
9202 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009203 << "DexFile referrer: " << dex_file.GetLocation()
9204 << " ClassLoader: " << DescribeLoaders(class_loader, "");
9205 // Be a good citizen and update the dex cache to speed subsequent calls.
David Srbecky5de5efe2021-02-15 21:23:00 +00009206 dex_cache->SetResolvedMethod(method_idx, resolved);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009207 // Disable the following invariant check as the verifier breaks it. b/73760543
9208 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
9209 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
9210 // << "Method: " << resolved->PrettyMethod() << ", "
9211 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
9212 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009213 }
9214 return resolved;
9215}
9216
David Brazdil4525e0b2018-04-05 16:57:32 +01009217// Returns true if `method` is either null or hidden.
9218// Does not print any warnings if it is hidden.
9219static bool CheckNoSuchMethod(ArtMethod* method,
9220 ObjPtr<mirror::DexCache> dex_cache,
9221 ObjPtr<mirror::ClassLoader> class_loader)
9222 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009223 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
David Brazdil4525e0b2018-04-05 16:57:32 +01009224 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01009225 hiddenapi::ShouldDenyAccessToMember(method,
9226 hiddenapi::AccessContext(class_loader, dex_cache),
9227 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01009228}
9229
9230ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
9231 ObjPtr<mirror::DexCache> dex_cache,
9232 ObjPtr<mirror::ClassLoader> class_loader,
9233 uint32_t method_idx) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009234 DCHECK(dex_cache->GetClassLoader() == class_loader);
David Brazdil4525e0b2018-04-05 16:57:32 +01009235 if (klass->IsInterface()) {
9236 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9237 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
9238 } else {
9239 // If there was an interface method with the same signature, we would have
9240 // found it in the "copied" methods. Only DCHECK that the interface method
9241 // really does not exist.
9242 if (kIsDebugBuild) {
9243 ArtMethod* method =
9244 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
Nicolas Geoffray24642182022-02-14 14:40:51 +00009245 CHECK(CheckNoSuchMethod(method, dex_cache, class_loader) ||
9246 (klass->FindAccessibleInterfaceMethod(method, image_pointer_size_) == nullptr));
David Brazdil4525e0b2018-04-05 16:57:32 +01009247 }
9248 return nullptr;
9249 }
9250}
9251
Vladimir Marko89011192017-12-11 13:45:05 +00009252ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009253 Handle<mirror::DexCache> dex_cache,
9254 Handle<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009255 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
David Srbecky5de5efe2021-02-15 21:23:00 +00009256 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009257 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009258 if (resolved != nullptr) {
9259 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009260 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9261 return resolved;
9262 }
9263 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009264 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009265 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009266 if (klass == nullptr) {
9267 Thread::Current()->AssertPendingException();
9268 return nullptr;
9269 }
9270 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009271 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9272 } else {
9273 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009274 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009275 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009276 hiddenapi::ShouldDenyAccessToMember(
9277 resolved,
9278 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9279 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009280 resolved = nullptr;
9281 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009282 return resolved;
9283}
9284
Vladimir Markof44d36c2017-03-14 14:18:46 +00009285ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9286 ObjPtr<mirror::DexCache> dex_cache,
9287 ObjPtr<mirror::ClassLoader> class_loader,
9288 bool is_static) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009289 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009290 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009291 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009292 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9293 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009294 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009295 }
9296 if (klass == nullptr) {
9297 // The class has not been resolved yet, so the field is also unresolved.
9298 return nullptr;
9299 }
9300 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009301
David Brazdil1ab0fa82018-05-04 11:28:03 +01009302 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009303}
9304
Vladimir Markoe11dd502017-12-08 14:09:45 +00009305ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009306 Handle<mirror::DexCache> dex_cache,
9307 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009308 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009309 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
David Srbecky5de5efe2021-02-15 21:23:00 +00009310 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009311 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009312 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009313 return resolved;
9314 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009315 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009316 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009317 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009318 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009319 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009320 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009321 }
9322
David Brazdil1ab0fa82018-05-04 11:28:03 +01009323 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9324 if (resolved == nullptr) {
9325 const char* name = dex_file.GetFieldName(field_id);
9326 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009327 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009328 }
9329 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009330}
9331
David Brazdil1ab0fa82018-05-04 11:28:03 +01009332ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9333 ObjPtr<mirror::DexCache> dex_cache,
9334 ObjPtr<mirror::ClassLoader> class_loader,
9335 uint32_t field_idx,
9336 bool is_static) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009337 DCHECK(dex_cache->GetClassLoader() == class_loader);
Vladimir Markob10668c2021-06-10 09:52:53 +01009338 ArtField* resolved = is_static ? klass->FindStaticField(dex_cache, field_idx)
9339 : klass->FindInstanceField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009340 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009341 hiddenapi::ShouldDenyAccessToMember(resolved,
9342 hiddenapi::AccessContext(class_loader, dex_cache),
9343 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009344 resolved = nullptr;
9345 }
9346
9347 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009348 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009349 }
9350
9351 return resolved;
9352}
9353
9354ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9355 ObjPtr<mirror::DexCache> dex_cache,
9356 ObjPtr<mirror::ClassLoader> class_loader,
9357 uint32_t field_idx) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009358 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
Vladimir Markob10668c2021-06-10 09:52:53 +01009359 ArtField* resolved = klass->FindField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009360
9361 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009362 hiddenapi::ShouldDenyAccessToMember(resolved,
9363 hiddenapi::AccessContext(class_loader, dex_cache),
9364 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009365 resolved = nullptr;
9366 }
9367
9368 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009369 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009370 }
9371
9372 return resolved;
9373}
9374
Vladimir Markoaf940202017-12-08 15:01:18 +00009375ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9376 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009377 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009378 Handle<mirror::DexCache> dex_cache,
9379 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009380 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009381 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009382 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
Narayan Kamath25352fc2016-08-03 12:46:58 +01009383
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009384 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009385 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009386 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009387 }
9388
Narayan Kamath25352fc2016-08-03 12:46:58 +01009389 StackHandleScope<4> hs(self);
9390
9391 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009392 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009393 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009394 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009395 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009396 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009397 DCHECK(self->IsExceptionPending());
9398 return nullptr;
9399 }
9400
9401 // Then resolve the argument types.
9402 //
9403 // TODO: Is there a better way to figure out the number of method arguments
9404 // other than by looking at the shorty ?
9405 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9406
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009407 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009408 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9409 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009410 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009411 DCHECK(self->IsExceptionPending());
9412 return nullptr;
9413 }
9414
9415 DexFileParameterIterator it(dex_file, proto_id);
9416 int32_t i = 0;
9417 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9418 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009419 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009420 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009421 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009422 DCHECK(self->IsExceptionPending());
9423 return nullptr;
9424 }
9425
9426 method_params->Set(i++, param_class.Get());
9427 }
9428
9429 DCHECK(!it.HasNext());
9430
9431 Handle<mirror::MethodType> type = hs.NewHandle(
9432 mirror::MethodType::Create(self, return_type, method_params));
Nicolas Geoffray4aebd582021-07-23 15:27:31 +01009433 if (type != nullptr) {
9434 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9435 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01009436
9437 return type.Get();
9438}
9439
Vladimir Markoaf940202017-12-08 15:01:18 +00009440ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009441 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009442 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009443 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009444 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9445 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009446 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009447}
9448
Vladimir Marko5aead702019-03-27 11:00:36 +00009449ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009450 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009451 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009452 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009453 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009454 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9455 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009456 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009457 bool is_static;
9458 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009459 switch (handle_type) {
9460 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009461 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009462 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009463 is_static = true;
9464 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009465 break;
9466 }
9467 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009468 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009469 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009470 is_static = true;
9471 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009472 break;
9473 }
9474 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009475 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009476 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009477 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009478 num_params = 2;
9479 break;
9480 }
9481 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009482 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009483 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009484 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009485 num_params = 1;
9486 break;
9487 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009488 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009489 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009490 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009491 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009492 case DexFile::MethodHandleType::kInvokeInterface:
9493 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009494 }
9495
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009496 ArtField* target_field =
9497 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9498 if (LIKELY(target_field != nullptr)) {
9499 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9500 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9501 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9502 ThrowIllegalAccessErrorField(referring_class, target_field);
9503 return nullptr;
9504 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009505 if (UNLIKELY(is_put && target_field->IsFinal())) {
9506 ThrowIllegalAccessErrorField(referring_class, target_field);
9507 return nullptr;
9508 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009509 } else {
9510 DCHECK(Thread::Current()->IsExceptionPending());
9511 return nullptr;
9512 }
9513
9514 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009515 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009516 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9517 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009518 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009519 DCHECK(self->IsExceptionPending());
9520 return nullptr;
9521 }
9522
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009523 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009524 Handle<mirror::Class> return_type;
9525 switch (handle_type) {
9526 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009527 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009528 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009529 break;
9530 }
9531 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009532 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009533 break;
9534 }
9535 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009536 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009537 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009538 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009539 break;
9540 }
9541 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009542 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009543 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009544 break;
9545 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009546 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009547 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009548 case DexFile::MethodHandleType::kInvokeConstructor:
9549 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009550 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009551 UNREACHABLE();
9552 }
9553
9554 for (int32_t i = 0; i < num_params; ++i) {
9555 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9556 DCHECK(self->IsExceptionPending());
9557 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009558 }
9559 }
9560
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009561 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009562 DCHECK(self->IsExceptionPending());
9563 return nullptr;
9564 }
9565
9566 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009567 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9568 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009569 DCHECK(self->IsExceptionPending());
9570 return nullptr;
9571 }
Orion Hodson631827d2017-04-10 14:53:47 +01009572
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009573 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9574 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9575}
9576
Vladimir Marko5aead702019-03-27 11:00:36 +00009577ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009578 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009579 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009580 ArtMethod* referrer) {
9581 DexFile::MethodHandleType handle_type =
9582 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9583 mirror::MethodHandle::Kind kind;
9584 uint32_t receiver_count = 0;
9585 ArtMethod* target_method = nullptr;
9586 switch (handle_type) {
9587 case DexFile::MethodHandleType::kStaticPut:
9588 case DexFile::MethodHandleType::kStaticGet:
9589 case DexFile::MethodHandleType::kInstancePut:
9590 case DexFile::MethodHandleType::kInstanceGet:
9591 UNREACHABLE();
9592 case DexFile::MethodHandleType::kInvokeStatic: {
9593 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9594 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009595 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9596 method_handle.field_or_method_idx_,
9597 referrer,
9598 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009599 break;
9600 }
9601 case DexFile::MethodHandleType::kInvokeInstance: {
9602 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9603 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009604 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9605 method_handle.field_or_method_idx_,
9606 referrer,
9607 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009608 break;
9609 }
9610 case DexFile::MethodHandleType::kInvokeConstructor: {
9611 // Constructors are currently implemented as a transform. They
9612 // are special cased later in this method.
9613 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9614 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009615 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9616 method_handle.field_or_method_idx_,
9617 referrer,
9618 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009619 break;
9620 }
9621 case DexFile::MethodHandleType::kInvokeDirect: {
9622 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9623 receiver_count = 1;
9624 StackHandleScope<2> hs(self);
9625 // A constant method handle with type kInvokeDirect can refer to
9626 // a method that is private or to a method in a super class. To
9627 // disambiguate the two options, we resolve the method ignoring
9628 // the invocation type to determine if the method is private. We
9629 // then resolve again specifying the intended invocation type to
9630 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009631 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009632 hs.NewHandle(referrer->GetDexCache()),
9633 hs.NewHandle(referrer->GetClassLoader()));
9634 if (UNLIKELY(target_method == nullptr)) {
9635 break;
9636 }
9637
9638 if (target_method->IsPrivate()) {
9639 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009640 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9641 method_handle.field_or_method_idx_,
9642 referrer,
9643 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009644 } else {
9645 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009646 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9647 method_handle.field_or_method_idx_,
9648 referrer,
9649 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009650 if (UNLIKELY(target_method == nullptr)) {
9651 break;
9652 }
9653 // Find the method specified in the parent in referring class
9654 // so invoke-super invokes the method in the parent of the
9655 // referrer.
9656 target_method =
9657 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9658 kRuntimePointerSize);
9659 }
9660 break;
9661 }
9662 case DexFile::MethodHandleType::kInvokeInterface: {
9663 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9664 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009665 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9666 method_handle.field_or_method_idx_,
9667 referrer,
9668 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009669 break;
9670 }
Orion Hodson631827d2017-04-10 14:53:47 +01009671 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009672
9673 if (UNLIKELY(target_method == nullptr)) {
9674 DCHECK(Thread::Current()->IsExceptionPending());
9675 return nullptr;
9676 }
9677
9678 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9679 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9680 uint32_t access_flags = target_method->GetAccessFlags();
9681 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9682 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9683 return nullptr;
9684 }
9685
9686 // Calculate the number of parameters from the method shorty. We add the
9687 // receiver count (0 or 1) and deduct one for the return value.
9688 uint32_t shorty_length;
9689 target_method->GetShorty(&shorty_length);
9690 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9691
Orion Hodsonecd58562018-09-24 11:27:33 +01009692 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009693 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009694 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9695 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9696 if (method_params.Get() == nullptr) {
9697 DCHECK(self->IsExceptionPending());
9698 return nullptr;
9699 }
9700
Orion Hodsonecd58562018-09-24 11:27:33 +01009701 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009702 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009703 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009704 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009705 // Insert receiver. Use the class identified in the method handle rather than the declaring
9706 // class of the resolved method which may be super class or default interface method
9707 // (b/115964401).
9708 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9709 // receiver_class should have been resolved when resolving the target method.
9710 DCHECK(receiver_class != nullptr);
9711 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009712 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009713
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009714 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009715 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009716 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009717 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009718 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009719 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009720 if (nullptr == klass) {
9721 DCHECK(self->IsExceptionPending());
9722 return nullptr;
9723 }
9724 method_params->Set(index++, klass);
9725 it.Next();
9726 }
9727
Orion Hodsonecd58562018-09-24 11:27:33 +01009728 Handle<mirror::Class> return_type =
9729 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009730 if (UNLIKELY(return_type.IsNull())) {
9731 DCHECK(self->IsExceptionPending());
9732 return nullptr;
9733 }
9734
9735 Handle<mirror::MethodType>
9736 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9737 if (UNLIKELY(method_type.IsNull())) {
9738 DCHECK(self->IsExceptionPending());
9739 return nullptr;
9740 }
9741
9742 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9743 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9744 Handle<mirror::MethodHandlesLookup> lookup =
9745 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9746 return lookup->FindConstructor(self, constructor_class, method_type);
9747 }
9748
9749 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9750 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9751}
9752
Vladimir Markoaf940202017-12-08 15:01:18 +00009753ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9754 uint32_t method_handle_idx,
9755 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009756 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009757 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009758 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009759 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9760 case DexFile::MethodHandleType::kStaticPut:
9761 case DexFile::MethodHandleType::kStaticGet:
9762 case DexFile::MethodHandleType::kInstancePut:
9763 case DexFile::MethodHandleType::kInstanceGet:
9764 return ResolveMethodHandleForField(self, method_handle, referrer);
9765 case DexFile::MethodHandleType::kInvokeStatic:
9766 case DexFile::MethodHandleType::kInvokeInstance:
9767 case DexFile::MethodHandleType::kInvokeConstructor:
9768 case DexFile::MethodHandleType::kInvokeDirect:
9769 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009770 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009771 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009772}
9773
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009774bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9775 return (entry_point == GetQuickResolutionStub()) ||
9776 (quick_resolution_trampoline_ == entry_point);
9777}
9778
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009779bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9780 return (entry_point == GetQuickToInterpreterBridge()) ||
9781 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9782}
9783
9784bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9785 return (entry_point == GetQuickGenericJniStub()) ||
9786 (quick_generic_jni_trampoline_ == entry_point);
9787}
9788
David Sehra49e0532017-08-25 08:05:29 -07009789bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009790 return entry_point == GetJniDlsymLookupStub() ||
9791 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009792}
9793
Vladimir Markofa458ac2020-02-12 14:08:07 +00009794bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9795 return entry_point == GetJniDlsymLookupCriticalStub() ||
9796 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9797}
9798
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009799const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9800 return GetQuickGenericJniStub();
9801}
9802
Alex Lightdb01a092017-04-03 15:39:55 -07009803void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9804 DCHECK(method->IsObsolete());
9805 // We cannot mess with the entrypoints of native methods because they are used to determine how
9806 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9807 if (!method->IsNative()) {
9808 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9809 }
9810}
9811
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009812void ClassLinker::DumpForSigQuit(std::ostream& os) {
Hans Boehmfb3ad722021-08-16 16:53:17 +00009813 ScopedObjectAccess soa(Thread::Current());
9814 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009815 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9816 << NumNonZygoteClasses() << "\n";
Hans Boehmfb3ad722021-08-16 16:53:17 +00009817 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009818 os << "Dumping registered class loaders\n";
9819 size_t class_loader_index = 0;
9820 for (const ClassLoaderData& class_loader : class_loaders_) {
9821 ObjPtr<mirror::ClassLoader> loader =
Hans Boehmfb3ad722021-08-16 16:53:17 +00009822 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009823 if (loader != nullptr) {
9824 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9825 bool saw_one_dex_file = false;
David Srbecky6fbcc292021-02-23 01:05:32 +00009826 for (const auto& entry : dex_caches_) {
9827 const DexCacheData& dex_cache = entry.second;
9828 if (dex_cache.class_table == class_loader.class_table) {
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009829 if (saw_one_dex_file) {
9830 os << ":";
9831 }
9832 saw_one_dex_file = true;
David Srbecky6fbcc292021-02-23 01:05:32 +00009833 os << entry.first->GetLocation();
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009834 }
9835 }
9836 os << "]";
9837 bool found_parent = false;
9838 if (loader->GetParent() != nullptr) {
9839 size_t parent_index = 0;
9840 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9841 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
Hans Boehmfb3ad722021-08-16 16:53:17 +00009842 soa.Self()->DecodeJObject(class_loader2.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009843 if (loader2 == loader->GetParent()) {
9844 os << ", parent #" << parent_index;
9845 found_parent = true;
9846 break;
9847 }
9848 parent_index++;
9849 }
9850 if (!found_parent) {
9851 os << ", unregistered parent of type "
9852 << loader->GetParent()->GetClass()->PrettyDescriptor();
9853 }
9854 } else {
9855 os << ", no parent";
9856 }
9857 os << "\n";
9858 }
9859 }
9860 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009861 Runtime* runtime = Runtime::Current();
9862 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9863 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009864}
9865
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009866class CountClassesVisitor : public ClassLoaderVisitor {
9867 public:
9868 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9869
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009870 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009871 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009872 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009873 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009874 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9875 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009876 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009877 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009878
9879 size_t num_zygote_classes;
9880 size_t num_non_zygote_classes;
9881};
9882
9883size_t ClassLinker::NumZygoteClasses() const {
9884 CountClassesVisitor visitor;
9885 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009886 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009887}
9888
9889size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009890 CountClassesVisitor visitor;
9891 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009892 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009893}
9894
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009895size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009896 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009897 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009898 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009899}
9900
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009901pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009902 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009903}
9904
9905pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009906 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009907}
9908
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009909void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009910 DCHECK(!init_done_);
9911
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009912 DCHECK(klass != nullptr);
9913 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009914
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009915 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009916 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009917 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9918 int32_t index = static_cast<int32_t>(class_root);
9919 DCHECK(class_roots->Get(index) == nullptr);
9920 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009921}
9922
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009923ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9924 Thread* self,
9925 const std::vector<const DexFile*>& dex_files,
9926 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009927 Handle<mirror::ClassLoader> parent_loader,
Brad Stenning9c924e82021-10-11 19:09:00 -07009928 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries,
9929 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries_after) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009930
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009931 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009932
Mathieu Chartierc7853442015-03-27 14:35:38 -07009933 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009934 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009935
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009936 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009937 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009938 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009939 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009940 mirror::ObjectArray<mirror::Object>::Alloc(self,
9941 dex_elements_class.Get(),
9942 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009943 Handle<mirror::Class> h_dex_element_class =
9944 hs.NewHandle(dex_elements_class->GetComponentType());
9945
Mathieu Chartierc7853442015-03-27 14:35:38 -07009946 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009947 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009948 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009949
Andreas Gampe08883de2016-11-08 13:20:52 -08009950 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009951 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009952
Andreas Gampe08883de2016-11-08 13:20:52 -08009953 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009954 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009955
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009956 // Fill the elements array.
9957 int32_t index = 0;
9958 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009959 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009960
Calin Juravle7865ac72017-06-28 11:03:12 -07009961 // CreateWellKnownClassLoader is only used by gtests and compiler.
9962 // 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 -07009963 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9964 self,
9965 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009966 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009967 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009968
Mathieu Chartier3738e982017-05-12 16:07:28 -07009969 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9970 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009971 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009972 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009973 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009974 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009975
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009976 Handle<mirror::String> h_file_name = hs2.NewHandle(
9977 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009978 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009979 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9980
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009981 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009982 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009983 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009984
9985 h_dex_elements->Set(index, h_element.Get());
9986 index++;
9987 }
9988 DCHECK_EQ(index, h_dex_elements->GetLength());
9989
9990 // Create DexPathList.
9991 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009992 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009993 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009994 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009995 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009996 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9997 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9998 // elements.
9999 {
10000 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
10001 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
10002 DCHECK(native_lib_dirs != nullptr);
10003 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
10004 DCHECK(list_class != nullptr);
10005 {
10006 StackHandleScope<1> h_list_scope(self);
10007 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
10008 bool list_init = EnsureInitialized(self, h_list_class, true, true);
10009 DCHECK(list_init);
10010 list_class = h_list_class.Get();
10011 }
10012 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
10013 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
10014 // is fine for testing. While it violates a Java-code invariant (the elementData field is
10015 // normally never null), as long as one does not try to add elements, this will still
10016 // work.
10017 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
10018 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010019
Calin Juravle7865ac72017-06-28 11:03:12 -070010020 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010021 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
10022 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -070010023 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010024 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -070010025 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -080010026 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -070010027 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -070010028 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010029
10030 // Make a pretend boot-classpath.
10031 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -070010032 ArtField* const parent_field =
Vladimir Markoe300c4e2021-06-08 16:00:05 +010010033 jni::DecodeArtField(WellKnownClasses::java_lang_ClassLoader_parent);
Roland Levillainf39c9eb2015-05-26 15:02:07 +010010034 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010035 if (parent_loader.Get() == nullptr) {
10036 ScopedObjectAccessUnchecked soa(self);
10037 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
10038 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
10039 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
10040 } else {
10041 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
10042 }
Calin Juravle7865ac72017-06-28 11:03:12 -070010043
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010044 ArtField* shared_libraries_field =
10045 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
10046 DCHECK(shared_libraries_field != nullptr);
10047 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
10048
Brad Stenning9c924e82021-10-11 19:09:00 -070010049 ArtField* shared_libraries_after_field =
10050 jni::DecodeArtField(
10051 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
10052 DCHECK(shared_libraries_after_field != nullptr);
10053 shared_libraries_after_field->SetObject<false>(h_class_loader.Get(),
10054 shared_libraries_after.Get());
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010055 return h_class_loader.Get();
10056}
10057
10058jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
10059 const std::vector<const DexFile*>& dex_files,
10060 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010061 jobject parent_loader,
Brad Stenning9c924e82021-10-11 19:09:00 -070010062 jobject shared_libraries,
10063 jobject shared_libraries_after) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010064 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
10065 WellKnownClasses::dalvik_system_PathClassLoader) ||
10066 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +000010067 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
10068 self->GetJniEnv()->IsSameObject(loader_class,
10069 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010070
10071 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
10072 // We could move the jobject to the callers, but all call-sites do this...
10073 ScopedObjectAccessUnchecked soa(self);
10074
10075 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Brad Stenning9c924e82021-10-11 19:09:00 -070010076 StackHandleScope<5> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010077
10078 Handle<mirror::Class> h_loader_class =
10079 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010080 Handle<mirror::ClassLoader> h_parent =
10081 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
10082 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
10083 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Brad Stenning9c924e82021-10-11 19:09:00 -070010084 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries_after =
10085 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries_after));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010086
10087 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
10088 self,
10089 dex_files,
10090 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010091 h_parent,
Brad Stenning9c924e82021-10-11 19:09:00 -070010092 h_shared_libraries,
10093 h_shared_libraries_after);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010094
10095 // Make it a global ref and return.
10096 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010097 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010098 return soa.Env()->NewGlobalRef(local_ref.get());
10099}
10100
Calin Juravle7865ac72017-06-28 11:03:12 -070010101jobject ClassLinker::CreatePathClassLoader(Thread* self,
10102 const std::vector<const DexFile*>& dex_files) {
10103 return CreateWellKnownClassLoader(self,
10104 dex_files,
10105 WellKnownClasses::dalvik_system_PathClassLoader,
10106 nullptr);
10107}
10108
Andreas Gampe8ac75952015-06-02 21:01:45 -070010109void ClassLinker::DropFindArrayClassCache() {
10110 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
10111 find_array_class_cache_next_victim_ = 0;
10112}
10113
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010114void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010115 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010116 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -070010117 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010118 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
10119 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010120 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +010010121 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010122 }
10123 }
10124}
10125
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010126void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10127 for (const ClassLoaderData& data : class_loaders_) {
10128 LinearAlloc* alloc = data.allocator;
10129 if (alloc != nullptr && !visitor->Visit(alloc)) {
10130 break;
10131 }
10132 }
10133}
10134
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010135void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10136 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010137 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010138 Thread* const self = Thread::Current();
10139 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010140 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010141 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010142 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010143 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10144 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010145 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010146 }
10147}
10148
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010149void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010150 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010151 std::vector<ClassLoaderData> to_delete;
10152 // Do the delete outside the lock to avoid lock violation in jit code cache.
10153 {
10154 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10155 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10156 const ClassLoaderData& data = *it;
10157 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010158 ObjPtr<mirror::ClassLoader> class_loader =
10159 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010160 if (class_loader != nullptr) {
10161 ++it;
10162 } else {
10163 VLOG(class_linker) << "Freeing class loader";
10164 to_delete.push_back(data);
10165 it = class_loaders_.erase(it);
10166 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010167 }
10168 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010169 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010170 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010171 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010172 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010173}
10174
Mathieu Chartier65975772016-08-05 10:46:36 -070010175class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10176 public:
10177 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10178 : method_(method),
10179 pointer_size_(pointer_size) {}
10180
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010181 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010182 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10183 holder_ = klass;
10184 }
10185 // Return false to stop searching if holder_ is not null.
10186 return holder_ == nullptr;
10187 }
10188
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010189 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010190 const ArtMethod* const method_;
10191 const PointerSize pointer_size_;
10192};
10193
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010194ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010195 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10196 CHECK(method->IsCopied());
10197 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10198 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010199 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010200}
10201
Calin Juravle33787682019-07-26 14:27:18 -070010202bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10203 REQUIRES_SHARED(Locks::mutator_lock_) {
10204 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10205 LOG(FATAL) << "UNREACHABLE";
10206 UNREACHABLE();
10207}
10208
10209bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10210 REQUIRES_SHARED(Locks::mutator_lock_) {
10211 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10212 LOG(FATAL) << "UNREACHABLE";
10213 UNREACHABLE();
10214}
10215
10216bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10217 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10218 LOG(FATAL) << "UNREACHABLE";
10219 UNREACHABLE();
10220}
10221
Calin Juravle2c2724c2021-01-14 19:54:23 -080010222void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10223 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10224 LOG(FATAL) << "UNREACHABLE";
10225 UNREACHABLE();
10226}
10227
Roland Levillain0e840272018-08-23 19:55:30 +010010228// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010229template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010230 Thread* self,
10231 ObjPtr<mirror::Class> java_lang_Class,
10232 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010233template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010234 Thread* self,
10235 ObjPtr<mirror::Class> java_lang_Class,
10236 uint32_t class_size);
10237
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010238} // namespace art