blob: f6f98e6192f1da55a4c13d65e8e03aedab7fa61c [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 Marko365c0202022-03-22 09:53:31 +00001385 uint32_t hash = static_cast<uint32_t>(referred_str->GetStoredHashCode());
1386 // All image strings have the hash code calculated, even if they are not interned.
1387 DCHECK_EQ(hash, static_cast<uint32_t>(referred_str->ComputeHashCode()));
1388 auto it = image_interns_.FindWithHash(GcRoot<mirror::String>(referred_str), hash);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001389 if (it != image_interns_.end() && it->Read() == referred_str) {
1390 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001391 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001392 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001393 }
1394
Chris Wailes0c61be42018-09-26 17:27:34 -07001395 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001396 mirror::CompressedReference<mirror::Object>* root) const
1397 REQUIRES_SHARED(Locks::mutator_lock_) {
1398 if (!root->IsNull()) {
1399 VisitRoot(root);
1400 }
1401 }
1402
Chris Wailes0c61be42018-09-26 17:27:34 -07001403 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001404 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001405 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001406 }
1407
1408 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001409 void operator()(ObjPtr<mirror::Object> obj,
1410 MemberOffset offset,
1411 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001412 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001413 // References within image or across images don't need a read barrier.
1414 ObjPtr<mirror::Object> referred_obj =
1415 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1416 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001417 }
1418
1419 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1420 ObjPtr<mirror::Reference> ref) const
1421 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001422 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001423 }
1424
Vladimir Marko8e05f092019-06-10 11:10:38 +01001425 size_t GetCount() const {
1426 return count_;
1427 }
1428
1429 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001430 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001431 const InternTable::UnorderedSet& image_interns_;
1432 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001433};
1434
Chris Wailes0c61be42018-09-26 17:27:34 -07001435/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001436 * This function counts references to strings interned in the AppImage.
1437 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001438 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001439size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1440 const InternTable::UnorderedSet& image_interns)
1441 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001442 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1443 const ImageHeader& image_header = space.GetImageHeader();
1444 const uint8_t* target_base = space.GetMemMap()->Begin();
1445 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001446
1447 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1448 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001449
Vladimir Marko8e05f092019-06-10 11:10:38 +01001450 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001451 bitmap->VisitMarkedRange(objects_begin,
1452 objects_end,
1453 [&space, &visitor](mirror::Object* obj)
1454 REQUIRES_SHARED(Locks::mutator_lock_) {
1455 if (space.HasAddress(obj)) {
1456 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001457 obj->VisitReferences</* kVisitNativeRoots= */ true,
1458 kVerifyNone,
1459 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001460 } else {
1461 // Don't visit native roots for non-dex-cache as they can't contain
1462 // native references to strings. This is verified during compilation
1463 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001464 obj->VisitReferences</* kVisitNativeRoots= */ false,
1465 kVerifyNone,
1466 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001467 }
1468 }
1469 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001470 return visitor.GetCount();
1471}
1472
1473template <typename Visitor>
1474static void VisitInternedStringReferences(
1475 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001476 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1477 const uint8_t* target_base = space->Begin();
1478 const ImageSection& sro_section =
1479 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1480 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1481
1482 VLOG(image)
1483 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1484 << num_string_offsets;
1485
1486 const auto* sro_base =
1487 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1488
1489 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1490 uint32_t base_offset = sro_base[offset_index].first;
1491
David Srbecky86d6cd52020-12-02 18:13:10 +00001492 uint32_t raw_member_offset = sro_base[offset_index].second;
1493 DCHECK_ALIGNED(base_offset, 2);
1494 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001495
David Srbecky86d6cd52020-12-02 18:13:10 +00001496 ObjPtr<mirror::Object> obj_ptr =
1497 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1498 MemberOffset member_offset(raw_member_offset);
1499 ObjPtr<mirror::String> referred_string =
1500 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001501 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001502 kWithoutReadBarrier,
1503 /* kIsVolatile= */ false>(member_offset);
1504 DCHECK(referred_string != nullptr);
1505
1506 ObjPtr<mirror::String> visited = visitor(referred_string);
1507 if (visited != referred_string) {
1508 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1509 /* kCheckTransaction= */ false,
1510 kVerifyNone,
1511 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001512 }
1513 }
1514}
1515
1516static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1517 REQUIRES_SHARED(Locks::mutator_lock_) {
1518 InternTable::UnorderedSet image_interns;
1519 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1520 if (section.Size() > 0) {
1521 size_t read_count;
1522 const uint8_t* data = space->Begin() + section.Offset();
1523 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1524 image_set.swap(image_interns);
1525 }
1526 size_t num_recorded_refs = 0u;
1527 VisitInternedStringReferences(
1528 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001529 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1530 REQUIRES_SHARED(Locks::mutator_lock_) {
1531 auto it = image_interns.find(GcRoot<mirror::String>(str));
1532 CHECK(it != image_interns.end());
1533 CHECK(it->Read() == str);
1534 ++num_recorded_refs;
1535 return str;
1536 });
1537 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1538 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001539}
1540
Andreas Gampe2af99022017-04-25 08:32:59 -07001541// new_class_set is the set of classes that were read from the class table section in the image.
1542// If there was no class table section, it is null.
1543// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001544class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001545 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001546 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001547 ClassLinker* class_linker,
1548 gc::space::ImageSpace* space,
1549 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001550 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001551 REQUIRES(!Locks::dex_lock_)
1552 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001553
Chris Wailesfbeef462018-10-19 14:16:35 -07001554 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001555 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001556};
1557
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001558void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001559 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001560 gc::space::ImageSpace* space,
1561 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001562 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001563 REQUIRES(!Locks::dex_lock_)
1564 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001565 ScopedTrace app_image_timing("AppImage:Updating");
1566
Vladimir Marko8e05f092019-06-10 11:10:38 +01001567 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1568 // In debug build, verify the string references before applying
1569 // the Runtime::LoadAppImageStartupCache() option.
1570 VerifyInternedStringReferences(space);
1571 }
1572
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001573 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001574 Runtime* const runtime = Runtime::Current();
1575 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001576 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001577 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001578 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001579 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001580 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001581 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001582 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001583 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001584 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001585 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001586 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001587 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001588 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001589
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001590 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001591 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001592 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001593
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001594 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001595 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001596 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001597 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1598 header.VisitPackedArtMethods([&](ArtMethod& method)
1599 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1600 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1601 if (klass != nullptr) {
1602 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1603 }
1604 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001605 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001606}
1607
Chris Wailesfbeef462018-10-19 14:16:35 -07001608void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001609 // Iterate over the string reference offsets stored in the image and intern
1610 // the strings they point to.
1611 ScopedTrace timing("AppImage:InternString");
1612
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001613 Runtime* const runtime = Runtime::Current();
1614 InternTable* const intern_table = runtime->GetInternTable();
1615
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001616 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1617 // for faster lookup.
1618 // TODO: Optimize with a bitmap or bloom filter
1619 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001620 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001621 REQUIRES_SHARED(Locks::mutator_lock_)
1622 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001623 const size_t non_boot_image_strings = intern_table->CountInterns(
1624 /*visit_boot_images=*/false,
1625 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001626 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001627 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1628 // Visit the smaller of the two sets to compute the intersection.
1629 if (interns.size() < non_boot_image_strings) {
1630 for (auto it = interns.begin(); it != interns.end(); ) {
1631 ObjPtr<mirror::String> string = it->Read();
1632 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1633 if (existing == nullptr) {
1634 existing = intern_table->LookupStrongLocked(string);
1635 }
1636 if (existing != nullptr) {
1637 intern_remap.Put(string.Ptr(), existing.Ptr());
1638 it = interns.erase(it);
1639 } else {
1640 ++it;
1641 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001642 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001643 } else {
1644 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1645 REQUIRES_SHARED(Locks::mutator_lock_)
1646 REQUIRES(Locks::intern_table_lock_) {
1647 auto it = interns.find(root);
1648 if (it != interns.end()) {
1649 ObjPtr<mirror::String> existing = root.Read();
1650 intern_remap.Put(it->Read(), existing.Ptr());
1651 it = interns.erase(it);
1652 }
1653 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1654 }
David Srbecky346fd962020-07-27 16:51:00 +01001655 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001656 if (kIsDebugBuild) {
1657 for (GcRoot<mirror::String>& root : interns) {
1658 ObjPtr<mirror::String> string = root.Read();
1659 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1660 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001661 }
1662 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001663 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001664 intern_table->AddImageStringsToTable(space, func);
1665 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001666 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001667 VisitInternedStringReferences(
1668 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001669 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1670 auto it = intern_remap.find(str.Ptr());
1671 if (it != intern_remap.end()) {
1672 return ObjPtr<mirror::String>(it->second);
1673 }
1674 return str;
1675 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001676 }
1677}
1678
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001679static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1680 const char* location,
1681 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001682 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001683 DCHECK(error_msg != nullptr);
1684 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001685 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001686 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001687 return std::unique_ptr<const DexFile>();
1688 }
1689 std::string inner_error_msg;
1690 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1691 if (dex_file == nullptr) {
1692 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1693 location,
1694 oat_file->GetLocation().c_str(),
1695 inner_error_msg.c_str());
1696 return std::unique_ptr<const DexFile>();
1697 }
1698
1699 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1700 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1701 location,
1702 dex_file->GetLocationChecksum(),
1703 oat_dex_file->GetDexFileLocationChecksum());
1704 return std::unique_ptr<const DexFile>();
1705 }
1706 return dex_file;
1707}
1708
1709bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1710 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1711 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001712 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001713 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001714 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001715 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001716 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001717 dex_caches_object->AsObjectArray<mirror::DexCache>();
1718 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001719 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001720 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1721 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1722 dex_file_location.c_str(),
1723 error_msg);
1724 if (dex_file == nullptr) {
1725 return false;
1726 }
1727 dex_cache->SetDexFile(dex_file.get());
1728 out_dex_files->push_back(std::move(dex_file));
1729 }
1730 return true;
1731}
1732
Andreas Gampe0793bec2016-12-01 11:37:33 -08001733// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1734// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001735class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001736 public:
1737 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1738 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001739 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001740 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1741 DCHECK(obj != nullptr);
1742 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1743 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1744 if (obj->IsClass()) {
1745 auto klass = obj->AsClass();
1746 for (ArtField& field : klass->GetIFields()) {
1747 CHECK_EQ(field.GetDeclaringClass(), klass);
1748 }
1749 for (ArtField& field : klass->GetSFields()) {
1750 CHECK_EQ(field.GetDeclaringClass(), klass);
1751 }
Orion Hodson5880c772020-07-28 20:12:08 +01001752 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001753 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001754 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001755 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001756 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001757 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001758 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001759 }
1760 if (klass->ShouldHaveImt()) {
1761 ImTable* imt = klass->GetImt(pointer_size);
1762 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001763 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001764 }
1765 }
1766 if (klass->ShouldHaveEmbeddedVTable()) {
1767 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001768 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001769 }
1770 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001771 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001772 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1773 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001774 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001775 }
1776 }
1777 }
1778 };
1779 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001780 }
1781
Andreas Gampe0793bec2016-12-01 11:37:33 -08001782 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001783 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001784 : spaces_(heap->GetBootImageSpaces()),
1785 pointer_size_(class_linker->GetImagePointerSize()) {
1786 space_begin_.reserve(spaces_.size());
1787 method_sections_.reserve(spaces_.size());
1788 runtime_method_sections_.reserve(spaces_.size());
1789 for (gc::space::ImageSpace* space : spaces_) {
1790 space_begin_.push_back(space->Begin());
1791 auto& header = space->GetImageHeader();
1792 method_sections_.push_back(&header.GetMethodsSection());
1793 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1794 }
1795 }
1796
Orion Hodson5880c772020-07-28 20:12:08 +01001797 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001798 REQUIRES_SHARED(Locks::mutator_lock_) {
1799 if (m->IsRuntimeMethod()) {
1800 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1801 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1802 } else if (m->IsCopied()) {
1803 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1804 } else if (expected_class != nullptr) {
1805 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1806 }
1807 if (!spaces_.empty()) {
1808 bool contains = false;
1809 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1810 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1811 contains = method_sections_[i]->Contains(offset) ||
1812 runtime_method_sections_[i]->Contains(offset);
1813 }
1814 CHECK(contains) << m << " not found";
1815 }
1816 }
1817
Orion Hodson5880c772020-07-28 20:12:08 +01001818 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1819 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001820 REQUIRES_SHARED(Locks::mutator_lock_) {
1821 CHECK(arr != nullptr);
1822 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1823 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1824 // expected_class == null means we are a dex cache.
1825 if (expected_class != nullptr) {
1826 CHECK(method != nullptr);
1827 }
1828 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001829 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001830 }
1831 }
1832 }
1833
Andreas Gampe0793bec2016-12-01 11:37:33 -08001834 const std::vector<gc::space::ImageSpace*>& spaces_;
1835 const PointerSize pointer_size_;
1836
1837 // Cached sections from the spaces.
1838 std::vector<const uint8_t*> space_begin_;
1839 std::vector<const ImageSection*> method_sections_;
1840 std::vector<const ImageSection*> runtime_method_sections_;
1841};
1842
Andreas Gampebe7af222017-07-25 09:57:28 -07001843static void VerifyAppImage(const ImageHeader& header,
1844 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001845 ClassTable* class_table,
1846 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001847 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001848 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1849 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1850 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1851 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1852 << mirror::Class::PrettyClass(klass);
1853 }
1854 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001855 {
1856 // Verify that all direct interfaces of classes in the class table are also resolved.
1857 std::vector<ObjPtr<mirror::Class>> classes;
1858 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1859 REQUIRES_SHARED(Locks::mutator_lock_) {
1860 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1861 classes.push_back(klass);
1862 }
1863 return true;
1864 };
1865 class_table->Visit(verify_direct_interfaces_in_table);
Andreas Gampebe7af222017-07-25 09:57:28 -07001866 for (ObjPtr<mirror::Class> klass : classes) {
1867 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +01001868 CHECK(klass->GetDirectInterface(i) != nullptr)
Andreas Gampebe7af222017-07-25 09:57:28 -07001869 << klass->PrettyDescriptor() << " iface #" << i;
1870 }
1871 }
1872 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001873}
1874
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001875bool ClassLinker::AddImageSpace(
1876 gc::space::ImageSpace* space,
1877 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001878 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1879 std::string* error_msg) {
1880 DCHECK(out_dex_files != nullptr);
1881 DCHECK(error_msg != nullptr);
1882 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001883 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001884 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001885 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001886 DCHECK(dex_caches_object != nullptr);
1887 Runtime* const runtime = Runtime::Current();
1888 gc::Heap* const heap = runtime->GetHeap();
1889 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001890 // Check that the image is what we are expecting.
1891 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1892 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1893 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1894 image_pointer_size_);
1895 return false;
1896 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001897 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1898 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1899 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1900 expected_image_roots,
1901 header.GetImageRoots()->GetLength());
1902 return false;
1903 }
1904 StackHandleScope<3> hs(self);
1905 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1906 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1907 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1908 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001909 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001910 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1911 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001912 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001913 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001914 *error_msg = StringPrintf("Expected %d class roots but got %d",
1915 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001916 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001917 return false;
1918 }
1919 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001920 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1921 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1922 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001923 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1924 return false;
1925 }
1926 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001927 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001928 if (oat_file->GetOatHeader().GetDexFileCount() !=
1929 static_cast<uint32_t>(dex_caches->GetLength())) {
1930 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1931 "image";
1932 return false;
1933 }
1934
Alex Lighta9bbc082019-11-14 14:51:41 -08001935 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001936 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001937 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1938 dex_file_location.c_str(),
1939 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001940 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001941 return false;
1942 }
1943
David Srbecky86d6cd52020-12-02 18:13:10 +00001944 {
David Srbecky33df0e32021-09-30 14:36:32 +00001945 // Native fields are all null. Initialize them.
David Srbecky86d6cd52020-12-02 18:13:10 +00001946 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky33df0e32021-09-30 14:36:32 +00001947 dex_cache->Initialize(dex_file.get(), class_loader.Get());
David Srbecky86d6cd52020-12-02 18:13:10 +00001948 }
1949 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001950 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001951 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001952 }
1953 out_dex_files->push_back(std::move(dex_file));
1954 }
1955
1956 if (app_image) {
1957 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001958 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001959 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1960 *error_msg = "Unexpected BootClassLoader in app image";
1961 return false;
1962 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 }
1964
Orion Hodson5880c772020-07-28 20:12:08 +01001965 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001966 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001967 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001968 }
1969 }
1970
1971 // Set entry point to interpreter if in InterpretOnly mode.
1972 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001973 // Set image methods' entry point to interpreter.
1974 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1975 if (!method.IsRuntimeMethod()) {
1976 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001977 if (!method.IsNative() && !method.IsResolutionMethod()) {
1978 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1979 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001980 }
1981 }
1982 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001983 }
1984
Nicolas Geoffray47171752020-08-31 15:03:20 +01001985 if (!runtime->IsAotCompiler()) {
Nicolas Geoffray0ca39d12022-04-27 14:11:23 +01001986 // If we are profiling the boot classpath, disable the shared memory for
1987 // boot image method optimization. We need to disable it before doing
1988 // ResetCounter below, as counters of shared memory method always hold the
1989 // "hot" value.
1990 if (runtime->GetJITOptions()->GetProfileSaverOptions().GetProfileBootClassPath()) {
1991 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1992 method.ClearMemorySharedMethod();
1993 }, space->Begin(), image_pointer_size_);
1994 }
1995
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001996 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001997 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00001998 uint16_t hotness_threshold = runtime->GetJITOptions()->GetWarmupThreshold();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001999 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01002000 // In the image, the `data` pointer field of the ArtMethod contains the code
2001 // item offset. Change this to the actual pointer to the code item.
2002 if (method.HasCodeItem()) {
2003 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
2004 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
zhaoxuyang7156ea22022-01-10 13:58:11 +08002005 method.SetCodeItem(code_item, method.GetDexFile()->IsCompactDexFile());
Nicolas Geoffray61673dc2021-11-06 13:58:31 +00002006 // The hotness counter may have changed since we compiled the image, so
2007 // reset it with the runtime value.
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00002008 method.ResetCounter(hotness_threshold);
Nicolas Geoffray47171752020-08-31 15:03:20 +01002009 }
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00002010 if (method.GetEntryPointFromQuickCompiledCode() == nterp_trampoline_) {
2011 if (can_use_nterp) {
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00002012 // Set image methods' entry point that point to the nterp trampoline to the
2013 // nterp entry point. This allows taking the fast path when doing a
2014 // nterp->nterp call.
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00002015 DCHECK_IMPLIES(NeedsClinitCheckBeforeCall(&method),
2016 method.GetDeclaringClass()->IsVisiblyInitialized());
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00002017 method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
2018 } else {
2019 method.SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2020 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01002021 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002022 }, space->Begin(), image_pointer_size_);
2023 }
2024
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00002025 if (runtime->IsVerificationSoftFail()) {
2026 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2027 if (!method.IsNative() && method.IsInvokable()) {
2028 method.ClearSkipAccessChecks();
2029 }
2030 }, space->Begin(), image_pointer_size_);
2031 }
2032
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002033 ClassTable* class_table = nullptr;
2034 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002035 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002036 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002037 }
2038 // If we have a class table section, read it and use it for verification in
2039 // UpdateAppImageClassLoadersAndDexCaches.
2040 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002041 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002042 const bool added_class_table = class_table_section.Size() > 0u;
2043 if (added_class_table) {
2044 const uint64_t start_time2 = NanoTime();
2045 size_t read_count = 0;
2046 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2047 /*make copy*/false,
2048 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002049 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002050 }
2051 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002052 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002053
2054 {
2055 ScopedTrace trace("AppImage:UpdateClassLoaders");
2056 // Update class loader and resolved strings. If added_class_table is false, the resolved
2057 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002058 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002059 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002060 // Note: We probably don't need the read barrier unless we copy the app image objects into
2061 // the region space.
2062 ObjPtr<mirror::Class> klass(root.Read());
2063 // Do not update class loader for boot image classes where the app image
2064 // class loader is only the initiating loader but not the defining loader.
2065 // Avoid read barrier since we are comparing against null.
2066 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002067 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002068 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002069 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002070 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002071
Vladimir Marko305c38b2018-02-14 11:50:07 +00002072 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002073 // Every class in the app image has initially SubtypeCheckInfo in the
2074 // Uninitialized state.
2075 //
2076 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2077 // after class initialization is complete. The app image ClassStatus as-is
2078 // are almost all ClassStatus::Initialized, and being in the
2079 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2080 //
2081 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2082 //
2083 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002084 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002085 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2086 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002087 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002088 }
2089 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002090 }
2091 if (!oat_file->GetBssGcRoots().empty()) {
2092 // Insert oat file to class table for visiting .bss GC roots.
2093 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002094 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002095
Mathieu Chartier69731002016-03-02 16:08:31 -08002096 if (added_class_table) {
2097 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2098 class_table->AddClassSet(std::move(temp_set));
2099 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002100
Mathieu Chartier69731002016-03-02 16:08:31 -08002101 if (kIsDebugBuild && app_image) {
2102 // This verification needs to happen after the classes have been added to the class loader.
2103 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002104 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002105 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002106 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002107
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002108 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002109 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002110}
2111
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002112void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002113 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2114 // enabling tracing requires the mutator lock, there are no race conditions here.
2115 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002116 Thread* const self = Thread::Current();
2117 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002118 if (kUseReadBarrier) {
2119 // We do not track new roots for CC.
2120 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2121 kVisitRootFlagClearRootLog |
2122 kVisitRootFlagStartLoggingNewRoots |
2123 kVisitRootFlagStopLoggingNewRoots));
2124 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002125 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002126 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2127 // There is 3 GC cases to handle:
2128 // Non moving concurrent:
2129 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002130 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002131 //
2132 // Moving non-concurrent:
2133 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2134 // To prevent missing roots, this case needs to ensure that there is no
2135 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2136 // class which is in the class table.
2137 //
2138 // Moving concurrent:
2139 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2140 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002141 //
2142 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2143 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2144 // these objects.
2145 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002146 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002147 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002148 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002149 for (const ClassLoaderData& data : class_loaders_) {
2150 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2151 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2152 }
2153 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002154 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002155 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002156 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002157 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002158 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002159 // Concurrent moving GC marked new roots through the to-space invariant.
2160 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002161 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002162 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2163 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2164 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2165 if (old_ref != nullptr) {
2166 DCHECK(old_ref->IsClass());
2167 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2168 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2169 // Concurrent moving GC marked new roots through the to-space invariant.
2170 CHECK_EQ(new_ref, old_ref);
2171 }
2172 }
2173 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002174 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002175 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002176 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002177 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002178 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002179 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002180 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002181 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002182 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002183 }
2184 // We deliberately ignore the class roots in the image since we
2185 // handle image roots by using the MS/CMS rescanning of dirty cards.
2186}
2187
Brian Carlstroma663ea52011-08-19 23:33:41 -07002188// Keep in sync with InitCallback. Anything we visit, we need to
2189// reinit references to when reinitializing a ClassLinker from a
2190// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002191void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002192 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002193 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002194 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2195 // unloading if we are marking roots.
2196 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002197}
2198
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002199class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2200 public:
2201 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2202 : visitor_(visitor),
2203 done_(false) {}
2204
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002205 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002206 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002207 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002208 if (!done_ && class_table != nullptr) {
2209 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2210 if (!class_table->Visit(visitor)) {
2211 // If the visitor ClassTable returns false it means that we don't need to continue.
2212 done_ = true;
2213 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002214 }
2215 }
2216
2217 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002218 // Class visitor that limits the class visits from a ClassTable to the classes with
2219 // the provided defining class loader. This filter is used to avoid multiple visits
2220 // of the same class which can be recorded for multiple initiating class loaders.
2221 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2222 public:
2223 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2224 ClassVisitor* visitor)
2225 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2226
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002227 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002228 if (klass->GetClassLoader() != defining_class_loader_) {
2229 return true;
2230 }
2231 return (*visitor_)(klass);
2232 }
2233
Vladimir Marko0984e482019-03-27 16:41:41 +00002234 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002235 ClassVisitor* const visitor_;
2236 };
2237
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002238 ClassVisitor* const visitor_;
2239 // If done is true then we don't need to do any more visiting.
2240 bool done_;
2241};
2242
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002243void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002244 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002245 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2246 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002247 }
2248}
2249
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002250void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002251 Thread* const self = Thread::Current();
2252 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2253 // Not safe to have thread suspension when we are holding a lock.
2254 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002255 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002256 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002257 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002258 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002259 }
2260}
2261
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002262class GetClassesInToVector : public ClassVisitor {
2263 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002264 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002265 classes_.push_back(klass);
2266 return true;
2267 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002268 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002269};
2270
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002271class GetClassInToObjectArray : public ClassVisitor {
2272 public:
2273 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2274 : arr_(arr), index_(0) {}
2275
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002276 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002277 ++index_;
2278 if (index_ <= arr_->GetLength()) {
2279 arr_->Set(index_ - 1, klass);
2280 return true;
2281 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002282 return false;
2283 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002284
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002285 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002286 return index_ <= arr_->GetLength();
2287 }
2288
2289 private:
2290 mirror::ObjectArray<mirror::Class>* const arr_;
2291 int32_t index_;
2292};
2293
2294void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002295 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2296 // is avoiding duplicates.
2297 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002298 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002299 GetClassesInToVector accumulator;
2300 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002301 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002302 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002303 return;
2304 }
2305 }
2306 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002307 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002308 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002309 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002310 // We size the array assuming classes won't be added to the class table during the visit.
2311 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002312 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002313 size_t class_table_size;
2314 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002315 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002316 // Add 100 in case new classes get loaded when we are filling in the object array.
2317 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002318 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002319 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002320 classes.Assign(
2321 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002322 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002323 GetClassInToObjectArray accumulator(classes.Get());
2324 VisitClasses(&accumulator);
2325 if (accumulator.Succeeded()) {
2326 break;
2327 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002328 }
2329 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2330 // If the class table shrank during creation of the clases array we expect null elements. If
2331 // the class table grew then the loop repeats. If classes are created after the loop has
2332 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002333 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002334 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002335 return;
2336 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002337 }
2338 }
2339}
2340
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002341ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002342 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002343 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002344 // CHA unloading analysis is not needed. No negative consequences are expected because
2345 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002346 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002347 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002348 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002349 while (!running_visibly_initialized_callbacks_.empty()) {
2350 std::unique_ptr<VisiblyInitializedCallback> callback(
2351 std::addressof(running_visibly_initialized_callbacks_.front()));
2352 running_visibly_initialized_callbacks_.pop_front();
2353 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002354}
2355
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002356void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002357 Runtime* const runtime = Runtime::Current();
2358 JavaVMExt* const vm = runtime->GetJavaVM();
2359 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002360 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002361 if (runtime->GetJit() != nullptr) {
2362 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2363 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002364 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002365 code_cache->RemoveMethodsIn(self, *data.allocator);
2366 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002367 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002368 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002369 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002370 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002371 // Cleanup references to single implementation ArtMethods that will be deleted.
2372 if (cleanup_cha) {
2373 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
Vladimir Marko5f958f62022-02-08 12:01:07 +00002374 data.class_table->Visit<kWithoutReadBarrier>(visitor);
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002375 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002376 {
2377 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2378 auto end = critical_native_code_with_clinit_check_.end();
2379 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2380 if (data.allocator->ContainsUnsafe(it->first)) {
2381 it = critical_native_code_with_clinit_check_.erase(it);
2382 } else {
2383 ++it;
2384 }
2385 }
2386 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002387
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002388 delete data.allocator;
2389 delete data.class_table;
2390}
2391
Vladimir Markobcf17522018-06-01 13:14:32 +01002392ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2393 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002394 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002395 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2396 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002397}
2398
David Srbecky86d6cd52020-12-02 18:13:10 +00002399ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002400 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002401 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002402 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002403 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002404 self->AssertPendingOOMException();
2405 return nullptr;
2406 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002407 // Use InternWeak() so that the location String can be collected when the ClassLoader
2408 // with this DexCache is collected.
2409 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002410 if (location == nullptr) {
2411 self->AssertPendingOOMException();
2412 return nullptr;
2413 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002414 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002415 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002416}
2417
David Srbecky33df0e32021-09-30 14:36:32 +00002418ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(
2419 Thread* self, const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
2420 StackHandleScope<1> hs(self);
2421 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00002422 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002423 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002424 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky33df0e32021-09-30 14:36:32 +00002425 dex_cache->Initialize(&dex_file, h_class_loader.Get());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002426 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002427 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002428}
2429
Vladimir Marko70e2a762019-07-12 16:49:00 +01002430template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002431ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2432 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002433 uint32_t class_size,
2434 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002435 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002436 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002437 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002438 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2439 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002440 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002441 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002442 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002443 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002444 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002445}
2446
Vladimir Marko70e2a762019-07-12 16:49:00 +01002447template <bool kMovable>
2448ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2449 ObjPtr<mirror::Class> java_lang_Class,
2450 uint32_t class_size) {
2451 mirror::Class::InitializeClassVisitor visitor(class_size);
2452 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2453}
2454
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002455ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002456 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002457}
2458
Vladimir Marko70e2a762019-07-12 16:49:00 +01002459void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2460 ClassRoot primitive_root,
2461 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002462 // We make this class non-movable for the unlikely case where it were to be
2463 // moved by a sticky-bit (minor) collection when using the Generational
2464 // Concurrent Copying (CC) collector, potentially creating a stale reference
2465 // in the `klass_` field of one of its instances allocated in the Large-Object
2466 // Space (LOS) -- see the comment about the dirty card scanning logic in
2467 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002468 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2469 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2470 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2471 DCHECK(component_type->IsPrimitive());
2472 array_class->SetComponentType(component_type);
2473 SetClassRoot(array_root, array_class);
2474}
2475
2476void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2477 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2478 array_class->SetSuperClass(java_lang_Object);
2479 array_class->SetVTable(java_lang_Object->GetVTable());
2480 array_class->SetPrimitiveType(Primitive::kPrimNot);
2481 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2482 array_class->SetClassFlags(component_type->IsPrimitive()
2483 ? mirror::kClassFlagNoReferenceFields
2484 : mirror::kClassFlagObjectArray);
2485 array_class->SetClassLoader(component_type->GetClassLoader());
2486 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2487 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2488 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2489 array_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002490 DCHECK_EQ(array_class->NumMethods(), 0u);
2491
2492 // don't need to set new_class->SetObjectSize(..)
2493 // because Object::SizeOf delegates to Array::SizeOf
2494
2495 // All arrays have java/lang/Cloneable and java/io/Serializable as
2496 // interfaces. We need to set that up here, so that stuff like
2497 // "instanceof" works right.
2498
2499 // Use the single, global copies of "interfaces" and "iftable"
2500 // (remember not to free them for arrays).
2501 {
2502 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2503 CHECK(array_iftable != nullptr);
2504 array_class->SetIfTable(array_iftable);
2505 }
2506
2507 // Inherit access flags from the component type.
2508 int access_flags = component_type->GetAccessFlags();
2509 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2510 access_flags &= kAccJavaFlagsMask;
2511 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2512 // and remove "interface".
2513 access_flags |= kAccAbstract | kAccFinal;
2514 access_flags &= ~kAccInterface;
Vladimir Marko70e2a762019-07-12 16:49:00 +01002515
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002516 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002517
Vladimir Markobf121912019-06-04 13:49:05 +01002518 // Array classes are fully initialized either during single threaded startup,
2519 // or from a pre-fence visitor, so visibly initialized.
2520 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002521}
2522
2523void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2524 // Do not hold lock on the array class object, the initialization of
2525 // core array classes is done while the process is still single threaded.
2526 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2527 FinishArrayClassSetup(array_class);
2528
2529 std::string temp;
2530 const char* descriptor = array_class->GetDescriptor(&temp);
2531 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2532 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2533 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002534}
2535
Vladimir Markobcf17522018-06-01 13:14:32 +01002536ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002537 Thread* self,
2538 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002539 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002540 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002541}
2542
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002543ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2544 const char* descriptor,
2545 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002546 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002547 if (kIsDebugBuild) {
2548 StackHandleScope<1> hs(self);
2549 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2550 Thread::PoisonObjectPointersIfDebug();
2551 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002552
2553 // For temporary classes we must wait for them to be retired.
2554 if (init_done_ && klass->IsTemp()) {
2555 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002556 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002557 ThrowEarlierClassFailure(klass);
2558 return nullptr;
2559 }
2560 StackHandleScope<1> hs(self);
2561 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2562 ObjectLock<mirror::Class> lock(self, h_class);
2563 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002564 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002565 lock.WaitIgnoringInterrupts();
2566 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002567 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002568 ThrowEarlierClassFailure(h_class.Get());
2569 return nullptr;
2570 }
2571 CHECK(h_class->IsRetired());
2572 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002573 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002574 }
2575
Brian Carlstromaded5f72011-10-07 17:15:04 -07002576 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002577 size_t index = 0;
2578 // Maximum number of yield iterations until we start sleeping.
2579 static const size_t kNumYieldIterations = 1000;
2580 // How long each sleep is in us.
2581 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002582 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002583 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002584 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002585 {
2586 ObjectTryLock<mirror::Class> lock(self, h_class);
2587 // Can not use a monitor wait here since it may block when returning and deadlock if another
2588 // thread has locked klass.
2589 if (lock.Acquired()) {
2590 // Check for circular dependencies between classes, the lock is required for SetStatus.
2591 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2592 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002593 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002594 return nullptr;
2595 }
2596 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002598 {
2599 // Handle wrapper deals with klass moving.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002600 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002601 if (index < kNumYieldIterations) {
2602 sched_yield();
2603 } else {
2604 usleep(kSleepDurationUS);
2605 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002606 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002607 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002608 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002609
Vladimir Marko72ab6842017-01-20 19:32:50 +00002610 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002611 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002612 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002613 }
2614 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002615 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002616 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002617 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002618}
2619
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002620using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002621
2622// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002623ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002624 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002625 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002626 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002627 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002628 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002629 return ClassPathEntry(dex_file, dex_class_def);
2630 }
2631 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002632 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002633}
2634
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002635// Helper macro to make sure each class loader lookup call handles the case the
2636// class loader is not recognized, or the lookup threw an exception.
2637#define RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(call_, result_, thread_) \
2638do { \
2639 auto local_call = call_; \
2640 if (!local_call) { \
2641 return false; \
2642 } \
2643 auto local_result = result_; \
2644 if (local_result != nullptr) { \
2645 return true; \
2646 } \
2647 auto local_thread = thread_; \
2648 if (local_thread->IsExceptionPending()) { \
2649 /* Pending exception means there was an error other than */ \
2650 /* ClassNotFound that must be returned to the caller. */ \
2651 return false; \
2652 } \
2653} while (0)
2654
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002655bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2656 Thread* self,
2657 const char* descriptor,
2658 size_t hash,
2659 Handle<mirror::ClassLoader> class_loader,
2660 /*out*/ ObjPtr<mirror::Class>* result) {
2661 ArtField* field =
2662 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
Brad Stenning9c924e82021-10-11 19:09:00 -07002663 return FindClassInSharedLibrariesHelper(soa, self, descriptor, hash, class_loader, field, result);
2664}
2665
2666bool ClassLinker::FindClassInSharedLibrariesHelper(ScopedObjectAccessAlreadyRunnable& soa,
2667 Thread* self,
2668 const char* descriptor,
2669 size_t hash,
2670 Handle<mirror::ClassLoader> class_loader,
2671 ArtField* field,
2672 /*out*/ ObjPtr<mirror::Class>* result) {
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002673 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2674 if (raw_shared_libraries == nullptr) {
2675 return true;
2676 }
2677
2678 StackHandleScope<2> hs(self);
2679 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2680 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2681 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002682 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2683 temp_loader.Assign(loader);
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002684 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2685 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result),
2686 *result,
2687 self);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002688 }
2689 return true;
2690}
2691
Brad Stenning9c924e82021-10-11 19:09:00 -07002692bool ClassLinker::FindClassInSharedLibrariesAfter(ScopedObjectAccessAlreadyRunnable& soa,
2693 Thread* self,
2694 const char* descriptor,
2695 size_t hash,
2696 Handle<mirror::ClassLoader> class_loader,
2697 /*out*/ ObjPtr<mirror::Class>* result) {
2698 ArtField* field = jni::DecodeArtField(
2699 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
2700 return FindClassInSharedLibrariesHelper(soa, self, descriptor, hash, class_loader, field, result);
2701}
2702
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002703bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2704 Thread* self,
2705 const char* descriptor,
2706 size_t hash,
2707 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002708 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002709 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002710 if (IsBootClassLoader(soa, class_loader.Get())) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002711 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2712 FindClassInBootClassLoaderClassPath(self, descriptor, hash, result), *result, self);
Andreas Gampef865ea92015-04-13 22:14:19 -07002713 return true;
2714 }
2715
David Brazdil05909d82018-12-06 16:25:16 +00002716 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002717 // For regular path or dex class loader the search order is:
2718 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002719 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002720 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002721
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002722 // Create a handle as RegisterDexFile may allocate dex caches (and cause thread suspension).
Calin Juravlecdd49122017-07-05 20:09:53 -07002723 StackHandleScope<1> hs(self);
2724 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002725 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2726 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result),
2727 *result,
2728 self);
2729 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2730 FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result),
2731 *result,
2732 self);
2733 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2734 FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader, result),
2735 *result,
2736 self);
Brad Stenning9c924e82021-10-11 19:09:00 -07002737 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2738 FindClassInSharedLibrariesAfter(soa, self, descriptor, hash, class_loader, result),
2739 *result,
2740 self);
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002741 // We did not find a class, but the class loader chain was recognized, so we
2742 // return true.
2743 return true;
Andreas Gampef865ea92015-04-13 22:14:19 -07002744 }
2745
Calin Juravlecdd49122017-07-05 20:09:53 -07002746 if (IsDelegateLastClassLoader(soa, class_loader)) {
2747 // For delegate last, the search order is:
2748 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002749 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002750 // - class loader dex files
2751 // - parent
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002752 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2753 FindClassInBootClassLoaderClassPath(self, descriptor, hash, result), *result, self);
2754 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2755 FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result),
2756 *result,
2757 self);
2758 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2759 FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader, result),
2760 *result,
2761 self);
Brad Stenning9c924e82021-10-11 19:09:00 -07002762 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2763 FindClassInSharedLibrariesAfter(soa, self, descriptor, hash, class_loader, result),
2764 *result,
2765 self);
Calin Juravlecdd49122017-07-05 20:09:53 -07002766
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002767 // Create a handle as RegisterDexFile may allocate dex caches (and cause thread suspension).
Calin Juravlecdd49122017-07-05 20:09:53 -07002768 StackHandleScope<1> hs(self);
2769 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002770 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2771 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result),
2772 *result,
2773 self);
2774 // We did not find a class, but the class loader chain was recognized, so we
2775 // return true.
2776 return true;
Calin Juravlecdd49122017-07-05 20:09:53 -07002777 }
2778
2779 // Unsupported class loader.
2780 *result = nullptr;
2781 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002782}
2783
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002784#undef RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION
2785
Andreas Gampe501c3b02019-04-17 21:54:27 +00002786namespace {
2787
2788// Matches exceptions caught in DexFile.defineClass.
2789ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2790 ClassLinker* class_linker)
2791 REQUIRES_SHARED(Locks::mutator_lock_) {
2792 return
2793 // ClassNotFoundException.
2794 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2795 class_linker))
2796 ||
2797 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2798 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2799}
2800
2801// Clear exceptions caught in DexFile.defineClass.
2802ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2803 REQUIRES_SHARED(Locks::mutator_lock_) {
2804 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2805 self->ClearException();
2806 }
2807}
2808
2809} // namespace
2810
Calin Juravle415dc3d2017-06-28 11:03:12 -07002811// Finds the class in the boot class loader.
2812// If the class is found the method returns the resolved class. Otherwise it returns null.
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002813bool ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2814 const char* descriptor,
2815 size_t hash,
2816 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002817 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2818 if (pair.second != nullptr) {
2819 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2820 if (klass != nullptr) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002821 *result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002822 } else {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002823 *result = DefineClass(self,
2824 descriptor,
2825 hash,
2826 ScopedNullHandle<mirror::ClassLoader>(),
2827 *pair.first,
2828 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002829 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002830 if (*result == nullptr) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002831 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002832 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002833 }
2834 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002835 // The boot classloader is always a known lookup.
2836 return true;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002837}
Andreas Gampef865ea92015-04-13 22:14:19 -07002838
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002839bool ClassLinker::FindClassInBaseDexClassLoaderClassPath(
Calin Juravle415dc3d2017-06-28 11:03:12 -07002840 ScopedObjectAccessAlreadyRunnable& soa,
2841 const char* descriptor,
2842 size_t hash,
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002843 Handle<mirror::ClassLoader> class_loader,
2844 /*out*/ ObjPtr<mirror::Class>* result) {
David Brazdil05909d82018-12-06 16:25:16 +00002845 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2846 IsInMemoryDexClassLoader(soa, class_loader) ||
2847 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002848 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002849
Vladimir Marko68c07582021-04-19 16:01:15 +00002850 const DexFile* dex_file = nullptr;
2851 const dex::ClassDef* class_def = nullptr;
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002852 ObjPtr<mirror::Class> ret;
Vladimir Marko68c07582021-04-19 16:01:15 +00002853 auto find_class_def = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2854 const dex::ClassDef* cp_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2855 if (cp_class_def != nullptr) {
2856 dex_file = cp_dex_file;
2857 class_def = cp_class_def;
2858 return false; // Found a class definition, stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002859 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002860 return true; // Continue with the next DexFile.
2861 };
Vladimir Marko68c07582021-04-19 16:01:15 +00002862 VisitClassLoaderDexFiles(soa, class_loader, find_class_def);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002863
Vladimir Marko68c07582021-04-19 16:01:15 +00002864 if (class_def != nullptr) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002865 *result = DefineClass(soa.Self(), descriptor, hash, class_loader, *dex_file, *class_def);
2866 if (UNLIKELY(*result == nullptr)) {
Vladimir Marko68c07582021-04-19 16:01:15 +00002867 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2868 FilterDexFileCaughtExceptions(soa.Self(), this);
2869 } else {
2870 DCHECK(!soa.Self()->IsExceptionPending());
2871 }
2872 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002873 // A BaseDexClassLoader is always a known lookup.
2874 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002875}
2876
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002877ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2878 const char* descriptor,
2879 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002880 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002881 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002882 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002883 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002884 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002885 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2886 // for primitive classes that aren't backed by dex files.
2887 return FindPrimitiveClass(descriptor[0]);
2888 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002889 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002890 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002891 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002892 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002893 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002894 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002895 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002896 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002897 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002898 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002899 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002900 return DefineClass(self,
2901 descriptor,
2902 hash,
2903 ScopedNullHandle<mirror::ClassLoader>(),
2904 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002905 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002906 } else {
2907 // The boot class loader is searched ahead of the application class loader, failures are
2908 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2909 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002910 ObjPtr<mirror::Throwable> pre_allocated =
2911 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002912 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002913 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002914 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002915 }
2916 ObjPtr<mirror::Class> result_ptr;
2917 bool descriptor_equals;
2918 if (descriptor[0] == '[') {
2919 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2920 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2921 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2922 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002923 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002924 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002925 bool known_hierarchy =
2926 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2927 if (result_ptr != nullptr) {
2928 // The chain was understood and we found the class. We still need to add the class to
2929 // the class table to protect from racy programs that can try and redefine the path list
2930 // which would change the Class<?> returned for subsequent evaluation of const-class.
2931 DCHECK(known_hierarchy);
2932 DCHECK(result_ptr->DescriptorEquals(descriptor));
2933 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002934 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002935 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002936 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2937 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002938 //
2939 // If the chain was understood but we did not find the class, let the Java-side
2940 // rediscover all this and throw the exception with the right stack trace. Note that
2941 // the Java-side could still succeed for racy programs if another thread is actively
2942 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002943
Alex Light185a4612018-10-04 15:54:25 -07002944 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002945 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002946 // Oops, we can't call into java so we can't run actual class-loader code.
2947 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002948 ObjPtr<mirror::Throwable> pre_allocated =
2949 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2950 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002951 return nullptr;
2952 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002953
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002954 // Inlined DescriptorToDot(descriptor) with extra validation.
2955 //
2956 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2957 // the DescriptorEquals() check below and give a confusing error message. For example,
2958 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2959 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2960 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2961 size_t descriptor_length = strlen(descriptor);
2962 if (UNLIKELY(descriptor[0] != 'L') ||
2963 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2964 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2965 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2966 return nullptr;
2967 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002968
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002969 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2970 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002971 if (known_hierarchy &&
2972 fast_class_not_found_exceptions_ &&
2973 !Runtime::Current()->IsJavaDebuggable()) {
2974 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2975 // debuggable, optimize this path by throwing directly here without going back to Java
2976 // language. This reduces how many ClassNotFoundExceptions happen.
2977 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2978 "%s",
2979 class_name_string.c_str());
2980 } else {
2981 ScopedLocalRef<jobject> class_loader_object(
2982 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2983 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2984 {
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002985 ScopedThreadStateChange tsc(self, ThreadState::kNative);
Andreas Gampe87658f32019-04-18 18:39:02 +00002986 ScopedLocalRef<jobject> class_name_object(
2987 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2988 if (class_name_object.get() == nullptr) {
2989 DCHECK(self->IsExceptionPending()); // OOME.
2990 return nullptr;
2991 }
2992 CHECK(class_loader_object.get() != nullptr);
2993 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2994 WellKnownClasses::java_lang_ClassLoader_loadClass,
2995 class_name_object.get()));
2996 }
2997 if (result.get() == nullptr && !self->IsExceptionPending()) {
2998 // broken loader - throw NPE to be compatible with Dalvik
2999 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
3000 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003001 return nullptr;
3002 }
Andreas Gampe87658f32019-04-18 18:39:02 +00003003 result_ptr = soa.Decode<mirror::Class>(result.get());
3004 // Check the name of the returned class.
3005 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003006 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003007 } else {
3008 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003009 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003010 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003011
3012 if (self->IsExceptionPending()) {
3013 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3014 // However, to comply with the RI behavior, first check if another thread succeeded.
3015 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3016 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3017 self->ClearException();
3018 return EnsureResolved(self, descriptor, result_ptr);
3019 }
3020 return nullptr;
3021 }
3022
3023 // Try to insert the class to the class table, checking for mismatch.
3024 ObjPtr<mirror::Class> old;
3025 {
3026 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3027 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3028 old = class_table->Lookup(descriptor, hash);
3029 if (old == nullptr) {
3030 old = result_ptr; // For the comparison below, after releasing the lock.
3031 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003032 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003033 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003034 } // else throw below, after releasing the lock.
3035 }
3036 }
3037 if (UNLIKELY(old != result_ptr)) {
3038 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3039 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003040 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003041 const char* loader_class_name =
3042 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3043 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3044 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3045 << DescriptorToDot(descriptor) << "\").";
3046 return EnsureResolved(self, descriptor, old);
3047 }
3048 if (UNLIKELY(!descriptor_equals)) {
3049 std::string result_storage;
3050 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3051 std::string loader_storage;
3052 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3053 ThrowNoClassDefFoundError(
3054 "Initiating class loader of type %s returned class %s instead of %s.",
3055 DescriptorToDot(loader_class_name).c_str(),
3056 DescriptorToDot(result_name).c_str(),
3057 DescriptorToDot(descriptor).c_str());
3058 return nullptr;
3059 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003060 // Success.
3061 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003062}
3063
Alex Light270db1c2019-12-03 12:20:01 +00003064// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3065// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3066// like pausing class definition.
3067struct ScopedDefiningClass {
3068 public:
3069 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3070 : self_(self), returned_(false) {
3071 Locks::mutator_lock_->AssertSharedHeld(self_);
3072 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3073 self_->IncrDefineClassCount();
3074 }
3075 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3076 Locks::mutator_lock_->AssertSharedHeld(self_);
3077 CHECK(returned_);
3078 }
3079
3080 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3081 REQUIRES_SHARED(Locks::mutator_lock_) {
3082 CHECK(!returned_);
3083 self_->DecrDefineClassCount();
3084 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3085 Thread::PoisonObjectPointersIfDebug();
3086 returned_ = true;
3087 return h_klass.Get();
3088 }
3089
3090 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3091 REQUIRES_SHARED(Locks::mutator_lock_) {
3092 StackHandleScope<1> hs(self_);
3093 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3094 return Finish(h_klass);
3095 }
3096
3097 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3098 REQUIRES_SHARED(Locks::mutator_lock_) {
3099 ScopedNullHandle<mirror::Class> snh;
3100 return Finish(snh);
3101 }
3102
3103 private:
3104 Thread* self_;
3105 bool returned_;
3106};
3107
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003108ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3109 const char* descriptor,
3110 size_t hash,
3111 Handle<mirror::ClassLoader> class_loader,
3112 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003113 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003114 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003115 StackHandleScope<3> hs(self);
Eric Holk74584e62021-02-18 14:39:17 -08003116 metrics::AutoTimer timer{GetMetrics()->ClassLoadingTotalTime()};
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003117 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003118
Brian Carlstromaded5f72011-10-07 17:15:04 -07003119 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003120 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003121 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003122 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003123 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003124 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003125 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003126 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003127 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003128 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003129 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003130 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003131 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003132 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003133 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003134 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003135 }
3136
Calin Juravle33787682019-07-26 14:27:18 -07003137 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3138 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3139 // public class path then we prevent the definition of the class.
3140 //
3141 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3142 // classpath is not checked.
3143 if (class_loader == nullptr &&
3144 Runtime::Current()->IsAotCompiler() &&
3145 DenyAccessBasedOnPublicSdk(descriptor)) {
3146 ObjPtr<mirror::Throwable> pre_allocated =
3147 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3148 self->SetException(pre_allocated);
3149 return sdc.Finish(nullptr);
3150 }
3151
Alex Lighte9f61032018-09-24 16:04:51 -07003152 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3153 // code to be executed. We put it up here so we can avoid all the allocations associated with
3154 // creating the class. This can happen with (eg) jit threads.
3155 if (!self->CanLoadClasses()) {
3156 // Make sure we don't try to load anything, potentially causing an infinite loop.
3157 ObjPtr<mirror::Throwable> pre_allocated =
3158 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3159 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003160 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003161 }
3162
Andreas Gampefa4333d2017-02-14 11:10:34 -08003163 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003164 // Allocate a class with the status of not ready.
3165 // Interface object should get the right size here. Regular class will
3166 // figure out the right size later and be replaced with one of the right
3167 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003168 if (CanAllocClass()) {
3169 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3170 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003171 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003172 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003173 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003174 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003175 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003176 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003177 }
Alex Lightb0f11922017-01-23 14:25:17 -08003178 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3179 // nothing.
3180 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003181 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003182 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3183 // will only be called once.
3184 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3185 klass,
3186 class_loader,
3187 dex_file,
3188 dex_class_def,
3189 &new_dex_file,
3190 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003191 // Check to see if an exception happened during runtime callbacks. Return if so.
3192 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003193 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003194 }
Alex Lightb0f11922017-01-23 14:25:17 -08003195 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003196 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003197 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003198 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003199 }
3200 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003201 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003202
Jeff Hao848f70a2014-01-15 13:49:50 -08003203 // Mark the string class by setting its access flag.
3204 if (UNLIKELY(!init_done_)) {
3205 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3206 klass->SetStringClass();
3207 }
3208 }
3209
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003210 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003211 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003212 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003213 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003214
Mathieu Chartier590fee92013-09-13 13:46:47 -07003215 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003216 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003217 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003218 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3219 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003220 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003221 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003222
Mathieu Chartierc7853442015-03-27 14:35:38 -07003223 // Load the fields and other things after we are inserted in the table. This is so that we don't
3224 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3225 // other reason is that the field roots are only visited from the class table. So we need to be
3226 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003227 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003228 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003229 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003230 // An exception occured during load, set status to erroneous while holding klass' lock in case
3231 // notification is necessary.
3232 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003233 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003234 }
Alex Light270db1c2019-12-03 12:20:01 +00003235 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003236 }
3237
Brian Carlstromaded5f72011-10-07 17:15:04 -07003238 // Finish loading (if necessary) by finding parents
3239 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003240 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003241 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003242 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003243 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003244 }
Alex Light270db1c2019-12-03 12:20:01 +00003245 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003246 }
3247 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003248
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003249 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003250 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003251 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003252
Brian Carlstromaded5f72011-10-07 17:15:04 -07003253 // Link the class (if necessary)
3254 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003255 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003256 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003257
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003258 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003259 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003260 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003261 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003262 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003263 }
Alex Light270db1c2019-12-03 12:20:01 +00003264 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003265 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003266 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003267 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Markof9e82e52021-10-06 08:34:40 +01003268 CHECK(h_new_class->IsResolved()) << descriptor << " " << h_new_class->GetStatus();
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003269
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003270 // Instrumentation may have updated entrypoints for all methods of all
3271 // classes. However it could not update methods of this class while we
3272 // were loading it. Now the class is resolved, we can update entrypoints
3273 // as required by instrumentation.
3274 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3275 // We must be in the kRunnable state to prevent instrumentation from
3276 // suspending all threads to update entrypoints while we are doing it
3277 // for this class.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00003278 DCHECK_EQ(self->GetState(), ThreadState::kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003279 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003280 }
3281
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003282 /*
3283 * We send CLASS_PREPARE events to the debugger from here. The
3284 * definition of "preparation" is creating the static fields for a
3285 * class and initializing them to the standard default values, but not
3286 * executing any code (that comes later, during "initialization").
3287 *
3288 * We did the static preparation in LinkClass.
3289 *
3290 * The class has been prepared and resolved but possibly not yet verified
3291 * at this point.
3292 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003293 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003294
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003295 // Notify native debugger of the new class and its layout.
3296 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3297
Alex Light270db1c2019-12-03 12:20:01 +00003298 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003299}
3300
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003301uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003302 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003303 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003304 size_t num_8 = 0;
3305 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003306 size_t num_32 = 0;
3307 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003308 ClassAccessor accessor(dex_file, dex_class_def);
3309 // We allow duplicate definitions of the same field in a class_data_item
3310 // but ignore the repeated indexes here, b/21868015.
3311 uint32_t last_field_idx = dex::kDexNoIndex;
3312 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3313 uint32_t field_idx = field.GetIndex();
3314 // Ordering enforced by DexFileVerifier.
3315 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3316 if (UNLIKELY(field_idx == last_field_idx)) {
3317 continue;
3318 }
3319 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003320 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003321 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3322 char c = descriptor[0];
3323 switch (c) {
3324 case 'L':
3325 case '[':
3326 num_ref++;
3327 break;
3328 case 'J':
3329 case 'D':
3330 num_64++;
3331 break;
3332 case 'I':
3333 case 'F':
3334 num_32++;
3335 break;
3336 case 'S':
3337 case 'C':
3338 num_16++;
3339 break;
3340 case 'B':
3341 case 'Z':
3342 num_8++;
3343 break;
3344 default:
3345 LOG(FATAL) << "Unknown descriptor: " << c;
3346 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003347 }
3348 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003349 return mirror::Class::ComputeClassSize(false,
3350 0,
3351 num_8,
3352 num_16,
3353 num_32,
3354 num_64,
3355 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003356 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003357}
3358
Vladimir Marko86c87522020-05-11 16:55:55 +01003359void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003360 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003361 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003362 size_t num_direct_methods = klass->NumDirectMethods();
3363 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003364 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003365 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003366 if (UNLIKELY(klass->IsProxyClass())) {
3367 return;
3368 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003369 PointerSize pointer_size = image_pointer_size_;
3370 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3371 klass->GetDirectMethods(pointer_size).end(),
3372 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3373 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3374 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3375 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3376 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3377 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3378 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3379 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3380 lb->first->SetEntryPointFromJni(lb->second);
3381 lb = critical_native_code_with_clinit_check_.erase(lb);
3382 }
3383 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003384 Runtime* runtime = Runtime::Current();
Nicolas Geoffray854af032021-12-21 08:32:42 +00003385 if (runtime->IsAotCompiler()) {
3386 // We should not update entrypoints when running the transactional
3387 // interpreter.
3388 return;
Ian Rogers19846512012-02-24 11:42:47 -08003389 }
Alex Light64ad14d2014-08-19 14:23:13 -07003390
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00003391 instrumentation::Instrumentation* instrumentation = runtime->GetInstrumentation();
Ian Rogers1c829822013-09-30 18:18:50 -07003392 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003393 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3394 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003395 if (!method->IsStatic()) {
3396 // Only update static methods.
3397 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003398 }
Nicolas Geoffray854af032021-12-21 08:32:42 +00003399 instrumentation->UpdateMethodsCode(method, instrumentation->GetCodeForInvoke(method));
Ian Rogers19846512012-02-24 11:42:47 -08003400 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003401 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003402}
3403
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003404// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3405// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003406inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3407 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003408 DCHECK(method != nullptr);
3409 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003410 method->SetEntryPointFromQuickCompiledCodePtrSize(
3411 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3412 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003413}
3414
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003415static void LinkCode(ClassLinker* class_linker,
3416 ArtMethod* method,
3417 const OatFile::OatClass* oat_class,
3418 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003419 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003420 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003421 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003422 // The following code only applies to a non-compiler runtime.
3423 return;
3424 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003425
Ian Rogers62d6c772013-02-27 08:32:07 -08003426 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003427 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray854af032021-12-21 08:32:42 +00003428 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
Jeff Hao16743632013-05-08 10:59:04 -07003429
Alex Light9139e002015-10-09 15:59:48 -07003430 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003431 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003432 return;
3433 }
Ian Rogers19846512012-02-24 11:42:47 -08003434
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003435 const void* quick_code = nullptr;
3436 if (oat_class != nullptr) {
3437 // Every kind of method should at least get an invoke stub from the oat_method.
3438 // non-abstract methods also get their code pointers.
3439 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3440 quick_code = oat_method.GetQuickCode();
3441 }
Nicolas Geoffray854af032021-12-21 08:32:42 +00003442 runtime->GetInstrumentation()->InitializeMethodsCode(method, quick_code);
jeffhao26c0a1a2012-01-17 16:28:33 -08003443
Ian Rogers62d6c772013-02-27 08:32:07 -08003444 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003445 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3446 // as the extra processing for @CriticalNative is not needed yet.
3447 method->SetEntryPointFromJni(
3448 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Brian Carlstrom92827a52011-10-10 15:50:01 -07003449 }
3450}
3451
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003452void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003453 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003454 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003455 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003456 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003457 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003458 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003459 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003460 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003461
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003462 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003463 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003464 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003465 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003466 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003467 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003468 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003469
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003470 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003471 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003472}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003473
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003474LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3475 LinearAlloc* allocator,
3476 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003477 if (length == 0) {
3478 return nullptr;
3479 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003480 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3481 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3482 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003483 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003484 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003485 CHECK(ret != nullptr);
3486 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3487 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003488}
3489
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003490LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3491 LinearAlloc* allocator,
3492 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003493 if (length == 0) {
3494 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003495 }
Vladimir Marko14632852015-08-17 12:07:23 +01003496 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3497 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003498 const size_t storage_size =
3499 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003500 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003501 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003502 CHECK(ret != nullptr);
3503 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003504 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003505 }
3506 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003507}
3508
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003509LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003510 if (class_loader == nullptr) {
3511 return Runtime::Current()->GetLinearAlloc();
3512 }
3513 LinearAlloc* allocator = class_loader->GetAllocator();
3514 DCHECK(allocator != nullptr);
3515 return allocator;
3516}
3517
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003518LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003519 if (class_loader == nullptr) {
3520 return Runtime::Current()->GetLinearAlloc();
3521 }
3522 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3523 LinearAlloc* allocator = class_loader->GetAllocator();
3524 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003525 RegisterClassLoader(class_loader);
3526 allocator = class_loader->GetAllocator();
3527 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003528 }
3529 return allocator;
3530}
3531
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003532void ClassLinker::LoadClass(Thread* self,
3533 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003534 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003535 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003536 ClassAccessor accessor(dex_file,
3537 dex_class_def,
3538 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003539 if (!accessor.HasClassData()) {
3540 return;
3541 }
3542 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003543 {
3544 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3545 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003546 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003547 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003548 // We allow duplicate definitions of the same field in a class_data_item
3549 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003550 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003551 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3552 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003553 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003554 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3555 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003556 accessor.NumInstanceFields());
3557 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003558 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003559 uint32_t last_static_field_idx = 0u;
3560 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003561
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003562 // Methods
3563 bool has_oat_class = false;
3564 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3565 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3566 : OatFile::OatClass::Invalid();
3567 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3568 klass->SetMethodsPtr(
3569 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3570 accessor.NumDirectMethods(),
3571 accessor.NumVirtualMethods());
3572 size_t class_def_method_index = 0;
3573 uint32_t last_dex_method_index = dex::kDexNoIndex;
3574 size_t last_class_def_method_index = 0;
3575
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003576 uint16_t hotness_threshold = runtime->GetJITOptions()->GetWarmupThreshold();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003577 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3578 // methods needs to decode all of the fields.
3579 accessor.VisitFieldsAndMethods([&](
3580 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3581 uint32_t field_idx = field.GetIndex();
3582 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3583 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3584 LoadField(field, klass, &sfields->At(num_sfields));
3585 ++num_sfields;
3586 last_static_field_idx = field_idx;
3587 }
3588 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3589 uint32_t field_idx = field.GetIndex();
3590 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3591 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3592 LoadField(field, klass, &ifields->At(num_ifields));
3593 ++num_ifields;
3594 last_instance_field_idx = field_idx;
3595 }
3596 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3597 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3598 image_pointer_size_);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003599 LoadMethod(dex_file, method, klass.Get(), art_method);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003600 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3601 uint32_t it_method_index = method.GetIndex();
3602 if (last_dex_method_index == it_method_index) {
3603 // duplicate case
3604 art_method->SetMethodIndex(last_class_def_method_index);
3605 } else {
3606 art_method->SetMethodIndex(class_def_method_index);
3607 last_dex_method_index = it_method_index;
3608 last_class_def_method_index = class_def_method_index;
3609 }
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003610 art_method->ResetCounter(hotness_threshold);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003611 ++class_def_method_index;
3612 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3613 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3614 class_def_method_index - accessor.NumDirectMethods(),
3615 image_pointer_size_);
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003616 art_method->ResetCounter(hotness_threshold);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003617 LoadMethod(dex_file, method, klass.Get(), art_method);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003618 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3619 ++class_def_method_index;
3620 });
3621
3622 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003623 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003624 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3625 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3626 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003627 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3628 if (sfields != nullptr) {
3629 sfields->SetSize(num_sfields);
3630 }
3631 if (ifields != nullptr) {
3632 ifields->SetSize(num_ifields);
3633 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003634 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003635 // Set the field arrays.
3636 klass->SetSFieldsPtr(sfields);
3637 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003638 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003639 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003640 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003641 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003642 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003643 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003644}
3645
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003646void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003647 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003648 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003649 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003650 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003651 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003652
David Brazdil85865692018-10-30 17:26:20 +00003653 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3654 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003655}
3656
Mathieu Chartier268764d2016-09-13 12:09:38 -07003657void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003658 const ClassAccessor::Method& method,
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003659 ObjPtr<mirror::Class> klass,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003660 ArtMethod* dst) {
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003661 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
3662
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003663 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003664 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003665 uint32_t name_utf16_length;
3666 const char* method_name = dex_file.StringDataAndUtf16LengthByIdx(method_id.name_idx_,
3667 &name_utf16_length);
3668 std::string_view shorty = dex_file.GetShortyView(dex_file.GetProtoId(method_id.proto_idx_));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003669
Mathieu Chartier66f19252012-09-18 08:57:04 -07003670 dst->SetDexMethodIndex(dex_method_idx);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003671 dst->SetDeclaringClass(klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003672
David Brazdil85865692018-10-30 17:26:20 +00003673 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3674 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003675
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003676 auto has_ascii_name = [method_name, name_utf16_length](const char* ascii_name,
3677 size_t length) ALWAYS_INLINE {
3678 DCHECK_EQ(strlen(ascii_name), length);
3679 return length == name_utf16_length &&
3680 method_name[length] == 0 && // Is `method_name` an ASCII string?
3681 memcmp(ascii_name, method_name, length) == 0;
3682 };
3683 if (UNLIKELY(has_ascii_name("finalize", sizeof("finalize") - 1u))) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003684 // Set finalizable flag on declaring class.
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003685 if (shorty == "V") {
Ian Rogersdfb325e2013-10-30 01:00:44 -07003686 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003687 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003688 klass->SetFinalizable();
3689 } else {
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003690 std::string_view klass_descriptor =
3691 dex_file.GetTypeDescriptorView(dex_file.GetTypeId(klass->GetDexTypeIndex()));
Ian Rogersdfb325e2013-10-30 01:00:44 -07003692 // The Enum class declares a "final" finalize() method to prevent subclasses from
3693 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3694 // subclasses, so we exclude it here.
3695 // We also want to avoid setting the flag on Object, where we know that finalize() is
3696 // empty.
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003697 if (klass_descriptor != "Ljava/lang/Object;" &&
3698 klass_descriptor != "Ljava/lang/Enum;") {
Ian Rogers241b5de2013-10-09 17:58:57 -07003699 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003700 }
3701 }
3702 }
3703 } else if (method_name[0] == '<') {
3704 // Fix broken access flags for initializers. Bug 11157540.
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003705 bool is_init = has_ascii_name("<init>", sizeof("<init>") - 1u);
3706 bool is_clinit = has_ascii_name("<clinit>", sizeof("<clinit>") - 1u);
Ian Rogers241b5de2013-10-09 17:58:57 -07003707 if (UNLIKELY(!is_init && !is_clinit)) {
3708 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3709 } else {
3710 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3711 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003712 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003713 access_flags |= kAccConstructor;
3714 }
3715 }
3716 }
Vladimir Markoe815aec2022-03-29 15:58:40 +00003717
3718 // Check for nterp invoke fast-path based on shorty.
3719 bool all_parameters_are_reference = true;
3720 bool all_parameters_are_reference_or_int = true;
3721 for (size_t i = 1; i < shorty.length(); ++i) {
3722 if (shorty[i] != 'L') {
3723 all_parameters_are_reference = false;
3724 if (shorty[i] == 'F' || shorty[i] == 'D' || shorty[i] == 'J') {
3725 all_parameters_are_reference_or_int = false;
3726 break;
3727 }
3728 }
3729 }
3730 if (all_parameters_are_reference_or_int && shorty[0] != 'F' && shorty[0] != 'D') {
3731 access_flags |= kAccNterpInvokeFastPathFlag;
3732 }
3733
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003734 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3735 // Check if the native method is annotated with @FastNative or @CriticalNative.
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003736 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3737 access_flags |=
3738 annotations::GetNativeMethodAnnotationAccessFlags(dex_file, class_def, dex_method_idx);
3739 dst->SetAccessFlags(access_flags);
3740 DCHECK(!dst->IsAbstract());
3741 DCHECK(!dst->HasCodeItem());
Nicolas Geoffray47171752020-08-31 15:03:20 +01003742 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003743 dst->SetDataPtrSize(nullptr, image_pointer_size_); // JNI stub/trampoline not linked yet.
3744 } else if ((access_flags & kAccAbstract) != 0u) {
3745 dst->SetAccessFlags(access_flags);
3746 // Must be done after SetAccessFlags since IsAbstract depends on it.
3747 DCHECK(dst->IsAbstract());
3748 if (klass->IsInterface()) {
3749 dst->CalculateAndSetImtIndex();
3750 }
3751 DCHECK(!dst->HasCodeItem());
3752 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3753 dst->SetDataPtrSize(nullptr, image_pointer_size_); // Single implementation not set yet.
3754 } else {
Vladimir Markoe815aec2022-03-29 15:58:40 +00003755 // Check for nterp entry fast-path based on shorty.
3756 if (all_parameters_are_reference) {
3757 access_flags |= kAccNterpEntryPointFastPathFlag;
3758 }
Vladimir Marko05f1a5b2022-03-09 14:20:15 +00003759 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3760 if (annotations::MethodIsNeverCompile(dex_file, class_def, dex_method_idx)) {
3761 access_flags |= kAccCompileDontBother;
3762 }
3763 dst->SetAccessFlags(access_flags);
3764 DCHECK(!dst->IsAbstract());
3765 DCHECK(dst->HasCodeItem());
3766 uint32_t code_item_offset = method.GetCodeItemOffset();
3767 DCHECK_NE(code_item_offset, 0u);
3768 if (Runtime::Current()->IsAotCompiler()) {
3769 dst->SetDataPtrSize(reinterpret_cast32<void*>(code_item_offset), image_pointer_size_);
3770 } else {
3771 dst->SetCodeItem(dex_file.GetCodeItem(code_item_offset), dex_file.IsCompactDexFile());
3772 }
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003773 }
Nicolas Geoffrayf9ae8e32022-02-15 22:54:11 +00003774
Nicolas Geoffray0ca39d12022-04-27 14:11:23 +01003775 if (Runtime::Current()->IsZygote() &&
3776 !Runtime::Current()->GetJITOptions()->GetProfileSaverOptions().GetProfileBootClassPath()) {
Nicolas Geoffrayf9ae8e32022-02-15 22:54:11 +00003777 dst->SetMemorySharedMethod();
3778 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003779}
3780
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003781void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
David Srbecky33df0e32021-09-30 14:36:32 +00003782 ObjPtr<mirror::DexCache> dex_cache =
3783 AllocAndInitializeDexCache(self, *dex_file, /* class_loader= */ nullptr);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003784 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003785 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003786}
3787
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003788void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003789 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003790 CHECK(dex_file != nullptr);
3791 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
Nicolas Geoffray7913cf32022-02-16 09:28:21 +00003792 CHECK_EQ(dex_cache->GetDexFile(), dex_file) << dex_file->GetLocation();
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003793 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003794 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003795 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003796}
3797
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003798void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003799 ObjPtr<mirror::DexCache> dex_cache,
3800 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003801 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003802 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003803 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003804 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003805 // For app images, the dex cache location may be a suffix of the dex file location since the
3806 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003807 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3808 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003809 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3810 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003811 // The following paths checks don't work on preopt when using boot dex files, where the dex
3812 // cache location is the one on device, and the dex_file's location is the one on host.
3813 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3814 CHECK_GE(dex_file_location.length(), dex_cache_length)
3815 << dex_cache_location << " " << dex_file.GetLocation();
3816 const std::string dex_file_suffix = dex_file_location.substr(
3817 dex_file_location.length() - dex_cache_length,
3818 dex_cache_length);
3819 // Example dex_cache location is SettingsProvider.apk and
3820 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3821 CHECK_EQ(dex_cache_location, dex_file_suffix);
3822 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003823 const OatFile* oat_file =
3824 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003825 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3826 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3827 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3828 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003829 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003830 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
David Srbecky6fbcc292021-02-23 01:05:32 +00003831 const DexCacheData& data = it->second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003832 if (self->IsJWeakCleared(data.weak_root)) {
3833 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003834 it = dex_caches_.erase(it);
3835 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003836 if (initialize_oat_file_data &&
David Srbecky6fbcc292021-02-23 01:05:32 +00003837 it->first->GetOatDexFile() != nullptr &&
3838 it->first->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003839 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003840 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003841 ++it;
3842 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003843 }
Vladimir Markob066d432018-01-03 13:14:37 +00003844 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003845 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003846 }
David Brazdila5c3a802019-03-08 14:59:41 +00003847 // Let hiddenapi assign a domain to the newly registered dex file.
3848 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3849
Vladimir Markocd556b02017-02-03 11:47:34 +00003850 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003851 DexCacheData data;
3852 data.weak_root = dex_cache_jweak;
Vladimir Markocd556b02017-02-03 11:47:34 +00003853 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky6fbcc292021-02-23 01:05:32 +00003854 AddNativeDebugInfoForDex(self, &dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003855 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003856 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3857 // path dex caches without an image.
3858 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003859 // Make sure that the dex cache holds the classloader live.
3860 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003861 if (class_loader != nullptr) {
3862 // Since we added a strong root to the class table, do the write barrier as required for
3863 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003864 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003865 }
David Srbecky6fbcc292021-02-23 01:05:32 +00003866 bool inserted = dex_caches_.emplace(&dex_file, std::move(data)).second;
3867 CHECK(inserted);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003868}
3869
Alex Light725da8f2020-02-19 14:46:33 -08003870ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3871 return data != nullptr
3872 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003873 : nullptr;
3874}
3875
Alex Light725da8f2020-02-19 14:46:33 -08003876bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003877 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003878 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003879 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003880 CHECK(data != nullptr);
David Srbecky6fbcc292021-02-23 01:05:32 +00003881 DCHECK_EQ(FindDexCacheDataLocked(*dex_cache->GetDexFile()), data);
Alex Light725da8f2020-02-19 14:46:33 -08003882 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003883}
3884
Alex Light07f06212017-06-01 14:01:43 -07003885void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3886 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003887 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003888 Thread* self = Thread::Current();
3889 StackHandleScope<2> hs(self);
3890 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3891 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3892 const DexFile* dex_file = dex_cache->GetDexFile();
3893 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3894 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003895 ReaderMutexLock mu(self, *Locks::dex_lock_);
3896 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3897 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003898 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3899 << "been registered on dex file " << dex_file->GetLocation();
3900 }
3901 ClassTable* table;
3902 {
3903 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3904 table = InsertClassTableForClassLoader(h_class_loader.Get());
3905 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003906 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3907 // a thread holding the dex lock and blocking on a condition variable regarding
3908 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003909 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003910 WriterMutexLock mu(self, *Locks::dex_lock_);
3911 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3912 table->InsertStrongRoot(h_dex_cache.Get());
3913 if (h_class_loader.Get() != nullptr) {
3914 // Since we added a strong root to the class table, do the write barrier as required for
3915 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003916 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003917 }
3918}
3919
Alex Lightde7f8782020-02-24 10:14:22 -08003920static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
3921 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08003922 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08003923 "Attempt to register dex file %s with multiple class loaders",
3924 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08003925}
3926
Vladimir Markocd556b02017-02-03 11:47:34 +00003927ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3928 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003929 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08003930 ObjPtr<mirror::DexCache> old_dex_cache;
3931 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003932 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003933 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003934 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
3935 old_dex_cache = DecodeDexCacheLocked(self, old_data);
3936 if (old_dex_cache != nullptr) {
3937 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
3938 return old_dex_cache;
3939 } else {
3940 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
3941 // be thrown when it's safe to do so to simplify this.
3942 registered_with_another_class_loader = true;
3943 }
3944 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003945 }
Alex Light725da8f2020-02-19 14:46:33 -08003946 // We need to have released the dex_lock_ to allocate safely.
3947 if (registered_with_another_class_loader) {
3948 ThrowDexFileAlreadyRegisteredError(self, dex_file);
3949 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003950 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003951 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003952 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3953 DCHECK(linear_alloc != nullptr);
3954 ClassTable* table;
3955 {
3956 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3957 table = InsertClassTableForClassLoader(class_loader);
3958 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003959 // Don't alloc while holding the lock, since allocation may need to
3960 // suspend all threads and another thread may need the dex_lock_ to
3961 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003962 StackHandleScope<3> hs(self);
3963 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00003964 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003965 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003966 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3967 // a thread holding the dex lock and blocking on a condition variable regarding
3968 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003969 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003970 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003971 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
3972 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003973 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
David Srbecky33df0e32021-09-30 14:36:32 +00003974 // Do Initialize while holding dex lock to make sure two threads don't call it
David Srbecky86d6cd52020-12-02 18:13:10 +00003975 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
3976 // DCHECK that the arrays are null.
David Srbecky33df0e32021-09-30 14:36:32 +00003977 h_dex_cache->Initialize(&dex_file, h_class_loader.Get());
Vladimir Markocd556b02017-02-03 11:47:34 +00003978 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003979 }
Alex Light725da8f2020-02-19 14:46:33 -08003980 if (old_dex_cache != nullptr) {
3981 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3982 // If this thread encountered OOME, ignore it.
3983 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
3984 self->ClearException();
3985 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
3986 // dex_lock_.
3987 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
3988 return old_dex_cache;
3989 } else {
3990 registered_with_another_class_loader = true;
3991 }
3992 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003993 }
Alex Light725da8f2020-02-19 14:46:33 -08003994 if (registered_with_another_class_loader) {
3995 ThrowDexFileAlreadyRegisteredError(self, dex_file);
3996 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00003997 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003998 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003999 self->AssertPendingOOMException();
4000 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004001 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004002 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004003 if (h_class_loader.Get() != nullptr) {
4004 // Since we added a strong root to the class table, do the write barrier as required for
4005 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004006 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004007 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004008 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
Nicolas Geoffray4f6bb442021-06-02 18:05:51 +01004009 PaletteNotifyDexFileLoaded(dex_file.GetLocation().c_str());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004010 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004011}
4012
Vladimir Markocd556b02017-02-03 11:47:34 +00004013bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004014 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004015 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004016}
4017
Vladimir Markocd556b02017-02-03 11:47:34 +00004018ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4019 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004020 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4021 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004022 if (dex_cache != nullptr) {
4023 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004024 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004025 // Failure, dump diagnostic and abort.
David Srbecky6fbcc292021-02-23 01:05:32 +00004026 for (const auto& entry : dex_caches_) {
4027 const DexCacheData& data = entry.second;
Alex Light725da8f2020-02-19 14:46:33 -08004028 if (DecodeDexCacheLocked(self, &data) != nullptr) {
David Srbecky6fbcc292021-02-23 01:05:32 +00004029 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << entry.first->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004030 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004031 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004032 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
David Srbecky6fbcc292021-02-23 01:05:32 +00004033 << " " << &dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004034 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004035}
4036
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004037ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const OatDexFile& oat_dex_file) {
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004038 ReaderMutexLock mu(self, *Locks::dex_lock_);
4039 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(oat_dex_file);
4040 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
4041 if (dex_cache != nullptr) {
4042 return dex_cache;
4043 }
4044 // Failure, dump diagnostic and abort.
4045 for (const auto& entry : dex_caches_) {
4046 const DexCacheData& data = entry.second;
4047 if (DecodeDexCacheLocked(self, &data) != nullptr) {
4048 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << entry.first->GetLocation();
4049 }
4050 }
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004051 LOG(FATAL) << "Failed to find DexCache for OatDexFile " << oat_dex_file.GetDexFileLocation()
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004052 << " " << &oat_dex_file;
4053 UNREACHABLE();
4054}
4055
Vladimir Markocd556b02017-02-03 11:47:34 +00004056ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4057 const DexFile* dex_file = dex_cache->GetDexFile();
4058 DCHECK(dex_file != nullptr);
4059 ReaderMutexLock mu(self, *Locks::dex_lock_);
David Srbecky6fbcc292021-02-23 01:05:32 +00004060 auto it = dex_caches_.find(dex_file);
4061 if (it != dex_caches_.end()) {
4062 const DexCacheData& data = it->second;
4063 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
4064 if (registered_dex_cache != nullptr) {
4065 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4066 return data.class_table;
Vladimir Markocd556b02017-02-03 11:47:34 +00004067 }
4068 }
4069 return nullptr;
4070}
4071
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004072const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004073 const OatDexFile& oat_dex_file) {
4074 auto it = std::find_if(dex_caches_.begin(), dex_caches_.end(), [&](const auto& entry) {
4075 return entry.first->GetOatDexFile() == &oat_dex_file;
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004076 });
4077 return it != dex_caches_.end() ? &it->second : nullptr;
4078}
4079
Alex Light725da8f2020-02-19 14:46:33 -08004080const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
David Srbecky6fbcc292021-02-23 01:05:32 +00004081 auto it = dex_caches_.find(&dex_file);
4082 return it != dex_caches_.end() ? &it->second : nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004083}
4084
Vladimir Marko70e2a762019-07-12 16:49:00 +01004085void ClassLinker::CreatePrimitiveClass(Thread* self,
4086 Primitive::Type type,
4087 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004088 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004089 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004090 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4091 // Do not hold lock on the primitive class object, the initialization of
4092 // primitive classes is done while the process is still single threaded.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004093 primitive_class->SetAccessFlagsDuringLinking(kAccPublic | kAccFinal | kAccAbstract);
Vladimir Marko70e2a762019-07-12 16:49:00 +01004094 primitive_class->SetPrimitiveType(type);
4095 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko70e2a762019-07-12 16:49:00 +01004096 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004097 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4098 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004099 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004100 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004101 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004102 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004103 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004104 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004105}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004106
Vladimir Marko02610552018-06-04 14:38:00 +01004107inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4108 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4109}
4110
Brian Carlstrombe977852011-07-19 14:54:54 -07004111// Create an array class (i.e. the class object for the array, not the
4112// array itself). "descriptor" looks like "[C" or "[[[[B" or
4113// "[Ljava/lang/String;".
4114//
4115// If "descriptor" refers to an array of primitives, look up the
4116// primitive type's internally-generated class object.
4117//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004118// "class_loader" is the class loader of the class that's referring to
4119// us. It's used to ensure that we're looking for the element type in
4120// the right context. It does NOT become the class loader for the
4121// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004122//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004123// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004124ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4125 const char* descriptor,
4126 size_t hash,
4127 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004128 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004129 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004130 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004131
4132 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4133 // code to be executed. We put it up here so we can avoid all the allocations associated with
4134 // creating the class. This can happen with (eg) jit threads.
4135 if (!self->CanLoadClasses()) {
4136 // Make sure we don't try to load anything, potentially causing an infinite loop.
4137 ObjPtr<mirror::Throwable> pre_allocated =
4138 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4139 self->SetException(pre_allocated);
4140 return nullptr;
4141 }
4142
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004143 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4144 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004145 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004146 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004147 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004148 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4149 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004150 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004151 DCHECK(self->IsExceptionPending());
4152 return nullptr;
4153 } else {
4154 self->ClearException();
4155 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004156 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004157 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4158 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4159 return nullptr;
4160 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004161 // See if the component type is already loaded. Array classes are
4162 // always associated with the class loader of their underlying
4163 // element type -- an array of Strings goes with the loader for
4164 // java/lang/String -- so we need to look for it there. (The
4165 // caller should have checked for the existence of the class
4166 // before calling here, but they did so with *their* class loader,
4167 // not the component type's loader.)
4168 //
4169 // If we find it, the caller adds "loader" to the class' initiating
4170 // loader list, which should prevent us from going through this again.
4171 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004172 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004173 // are the same, because our caller (FindClass) just did the
4174 // lookup. (Even if we get this wrong we still have correct behavior,
4175 // because we effectively do this lookup again when we add the new
4176 // class to the hash table --- necessary because of possible races with
4177 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004178 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004179 ObjPtr<mirror::Class> new_class =
4180 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004181 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004182 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004183 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004184 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004185 // Core array classes, i.e. Object[], Class[], String[] and primitive
4186 // arrays, have special initialization and they should be found above.
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00004187 DCHECK_IMPLIES(component_type->IsObjectClass(),
4188 // Guard from false positives for errors before setting superclass.
4189 component_type->IsErroneousUnresolved());
Vladimir Marko70e2a762019-07-12 16:49:00 +01004190 DCHECK(!component_type->IsStringClass());
4191 DCHECK(!component_type->IsClassClass());
4192 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004193
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004194 // Fill out the fields in the Class.
4195 //
4196 // It is possible to execute some methods against arrays, because
4197 // all arrays are subclasses of java_lang_Object_, so we need to set
4198 // up a vtable. We can just point at the one in java_lang_Object_.
4199 //
4200 // Array classes are simple enough that we don't need to do a full
4201 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004202 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4203 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4204 size_t usable_size)
4205 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004206 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004207 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4208 init_class(obj, usable_size);
4209 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4210 klass->SetComponentType(component_type.Get());
4211 // Do not hold lock for initialization, the fence issued after the visitor
4212 // returns ensures memory visibility together with the implicit consume
4213 // semantics (for all supported architectures) for any thread that loads
4214 // the array class reference from any memory locations afterwards.
4215 FinishArrayClassSetup(klass);
4216 };
4217 auto new_class = hs.NewHandle<mirror::Class>(
4218 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004219 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004220 self->AssertPendingOOMException();
4221 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004222 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004223
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004224 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004225 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004226 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4227 // duplicate events in case of races. Array classes don't really follow dedicated
4228 // load and prepare, anyways.
4229 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4230 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4231
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004232 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004233 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004234 }
4235 // Another thread must have loaded the class after we
4236 // started but before we finished. Abandon what we've
4237 // done.
4238 //
4239 // (Yes, this happens.)
4240
Vladimir Markobcf17522018-06-01 13:14:32 +01004241 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004242}
4243
Vladimir Marko9186b182018-11-06 14:55:54 +00004244ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4245 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004246 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004247 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4248 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4249 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4250 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4251 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4252 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4253 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4254 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4255 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004256 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004257 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004258 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004259 return GetClassRoot(class_root, this);
4260}
4261
4262ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4263 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4264 if (UNLIKELY(result == nullptr)) {
4265 std::string printable_type(PrintableChar(type));
4266 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4267 }
4268 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004269}
4270
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004271ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4272 ObjPtr<mirror::Class> klass,
4273 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004274 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004275 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004276 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004277 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004278 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004279 source += " from ";
4280 source += dex_cache->GetLocation()->ToModifiedUtf8();
4281 }
4282 LOG(INFO) << "Loaded class " << descriptor << source;
4283 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004284 {
4285 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004286 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004287 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004288 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004289 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004290 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004291 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004292 VerifyObject(klass);
4293 class_table->InsertWithHash(klass, hash);
4294 if (class_loader != nullptr) {
4295 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004296 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004297 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004298 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004299 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004300 }
4301 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004302 if (kIsDebugBuild) {
4303 // Test that copied methods correctly can find their holder.
4304 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4305 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4306 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004307 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004308 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004309}
4310
Vladimir Marko1998cd02017-01-13 13:02:58 +00004311void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004312 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4313 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4314 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4315 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004316 }
4317}
4318
Alex Lighte64300b2015-12-15 15:02:47 -08004319// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004320void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004321 LengthPrefixedArray<ArtMethod>* new_methods) {
4322 klass->SetMethodsPtrUnchecked(new_methods,
4323 klass->NumDirectMethods(),
4324 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004325 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004326 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004327}
4328
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004329ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4330 const char* descriptor,
4331 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004332 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4333}
4334
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004335ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4336 const char* descriptor,
4337 size_t hash,
4338 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004339 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4340 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4341 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004342 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004343 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004344 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004345 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004346 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004347 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004348}
4349
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004350class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4351 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004352 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004353
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004354 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004355 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004356 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004357 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004358 if (class_table != nullptr) {
4359 class_table->FreezeSnapshot();
4360 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004361 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004362};
4363
4364void ClassLinker::MoveClassTableToPreZygote() {
4365 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004366 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004367 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004368 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004369}
4370
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004371// Look up classes by hash and descriptor and put all matching ones in the result array.
4372class LookupClassesVisitor : public ClassLoaderVisitor {
4373 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004374 LookupClassesVisitor(const char* descriptor,
4375 size_t hash,
4376 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004377 : descriptor_(descriptor),
4378 hash_(hash),
4379 result_(result) {}
4380
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004381 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004382 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004383 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004384 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004385 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4386 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004387 result_->push_back(klass);
4388 }
4389 }
4390
4391 private:
4392 const char* const descriptor_;
4393 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004394 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004395};
4396
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004397void ClassLinker::LookupClasses(const char* descriptor,
4398 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004399 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004400 Thread* const self = Thread::Current();
4401 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004402 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004403 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004404 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004405 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004406 result.push_back(klass);
4407 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004408 LookupClassesVisitor visitor(descriptor, hash, &result);
4409 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004410}
4411
Alex Lightf1f10492015-10-07 16:08:36 -07004412bool ClassLinker::AttemptSupertypeVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004413 verifier::VerifierDeps* verifier_deps,
Alex Lightf1f10492015-10-07 16:08:36 -07004414 Handle<mirror::Class> klass,
4415 Handle<mirror::Class> supertype) {
4416 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004417 DCHECK(klass != nullptr);
4418 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004419
Alex Lightf1f10492015-10-07 16:08:36 -07004420 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004421 VerifyClass(self, verifier_deps, supertype);
Alex Lightf1f10492015-10-07 16:08:36 -07004422 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004423
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004424 if (supertype->IsVerified()
4425 || supertype->ShouldVerifyAtRuntime()
4426 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004427 // The supertype is either verified, or we soft failed at AOT time.
4428 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004429 return true;
4430 }
4431 // If we got this far then we have a hard failure.
4432 std::string error_msg =
4433 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004434 klass->PrettyDescriptor().c_str(),
4435 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004436 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004437 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004438 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004439 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004440 // Set during VerifyClass call (if at all).
4441 self->ClearException();
4442 }
4443 // Change into a verify error.
4444 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004445 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004446 self->GetException()->SetCause(cause.Get());
4447 }
4448 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4449 if (Runtime::Current()->IsAotCompiler()) {
4450 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4451 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004452 // Need to grab the lock to change status.
4453 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004454 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004455 return false;
4456}
4457
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004458verifier::FailureKind ClassLinker::VerifyClass(Thread* self,
4459 verifier::VerifierDeps* verifier_deps,
4460 Handle<mirror::Class> klass,
4461 verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004462 {
4463 // TODO: assert that the monitor on the Class is held
4464 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004465
Andreas Gampe884f3b82016-03-30 19:52:58 -07004466 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004467 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004468 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004469 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004470 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4471 // case we may see the same status again. b/62912904. This is why the check is
4472 // greater or equal.
4473 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004474 << "Class '" << klass->PrettyClass()
4475 << "' performed an illegal verification state transition from " << old_status
4476 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004477 old_status = klass->GetStatus();
4478 }
jeffhao98eacac2011-09-14 16:11:53 -07004479
Andreas Gampe884f3b82016-03-30 19:52:58 -07004480 // The class might already be erroneous, for example at compile time if we attempted to verify
4481 // this class as a parent to another.
4482 if (klass->IsErroneous()) {
4483 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004484 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004485 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004486
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004487 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004488 if (klass->IsVerified()) {
Nicolas Geoffray80789962021-04-30 16:50:39 +01004489 if (verifier_deps != nullptr &&
4490 verifier_deps->ContainsDexFile(klass->GetDexFile()) &&
4491 !verifier_deps->HasRecordedVerifiedStatus(klass->GetDexFile(), *klass->GetClassDef()) &&
4492 !Runtime::Current()->IsAotCompiler()) {
4493 // If the klass is verified, but `verifier_deps` did not record it, this
4494 // means we are running background verification of a secondary dex file.
4495 // Re-run the verifier to populate `verifier_deps`.
4496 // No need to run the verification when running on the AOT Compiler, as
4497 // the driver handles those multithreaded cases already.
4498 std::string error_msg;
4499 verifier::FailureKind failure =
4500 PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
4501 // We could have soft failures, so just check that we don't have a hard
4502 // failure.
4503 DCHECK_NE(failure, verifier::FailureKind::kHardFailure) << error_msg;
4504 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004505 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004506 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004507
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004508 if (klass->IsVerifiedNeedsAccessChecks()) {
4509 if (!Runtime::Current()->IsAotCompiler()) {
4510 // Mark the class as having a verification attempt to avoid re-running
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004511 // the verifier.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004512 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4513 }
4514 return verifier::FailureKind::kAccessChecksFailure;
4515 }
4516
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004517 // For AOT, don't attempt to re-verify if we have already found we should
4518 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004519 if (klass->ShouldVerifyAtRuntime()) {
4520 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004521 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004522 }
jeffhao98eacac2011-09-14 16:11:53 -07004523
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004524 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4525 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004526
4527 // Skip verification if disabled.
4528 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004529 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004530 UpdateClassAfterVerification(klass, image_pointer_size_, verifier::FailureKind::kNoFailure);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004531 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004532 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004533 }
4534
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004535 VLOG(class_linker) << "Beginning verification for class: "
4536 << klass->PrettyDescriptor()
4537 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4538
Ian Rogers9ffb0392012-09-10 11:56:50 -07004539 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004540 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004541 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4542 // If we have a superclass and we get a hard verification failure we can return immediately.
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004543 if (supertype != nullptr &&
4544 !AttemptSupertypeVerification(self, verifier_deps, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004545 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004546 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004547 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004548
Alex Lightf1f10492015-10-07 16:08:36 -07004549 // Verify all default super-interfaces.
4550 //
4551 // (1) Don't bother if the superclass has already had a soft verification failure.
4552 //
4553 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4554 // recursive initialization by themselves. This is because when an interface is initialized
4555 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4556 // but choose not to for an optimization. If the interfaces is being verified due to a class
4557 // initialization (which would need all the default interfaces to be verified) the class code
4558 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004559 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004560 && !klass->IsInterface()) { // See (2)
4561 int32_t iftable_count = klass->GetIfTableCount();
4562 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4563 // Loop through all interfaces this class has defined. It doesn't matter the order.
4564 for (int32_t i = 0; i < iftable_count; i++) {
4565 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004566 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004567 // We only care if we have default interfaces and can skip if we are already verified...
4568 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4569 continue;
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004570 } else if (UNLIKELY(!AttemptSupertypeVerification(self, verifier_deps, klass, iface))) {
Alex Lightf1f10492015-10-07 16:08:36 -07004571 // We had a hard failure while verifying this interface. Just return immediately.
4572 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004573 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004574 } else if (UNLIKELY(!iface->IsVerified())) {
4575 // We softly failed to verify the iface. Stop checking and clean up.
4576 // Put the iface into the supertype handle so we know what caused us to fail.
4577 supertype.Assign(iface.Get());
4578 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004579 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004580 }
4581 }
4582
Alex Lightf1f10492015-10-07 16:08:36 -07004583 // At this point if verification failed, then supertype is the "first" supertype that failed
4584 // verification (without a specific order). If verification succeeded, then supertype is either
4585 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004586 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004587 supertype.Get() == klass->GetSuperClass() ||
4588 !supertype->IsVerified());
4589
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004590 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004591 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004592 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004593 bool preverified = VerifyClassUsingOatFile(self, dex_file, klass, oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004594
4595 VLOG(class_linker) << "Class preverified status for class "
4596 << klass->PrettyDescriptor()
4597 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4598 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004599 << preverified
4600 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004601
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004602 // If the oat file says the class had an error, re-run the verifier. That way we will either:
4603 // 1) Be successful at runtime, or
4604 // 2) Get a precise error message.
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00004605 DCHECK_IMPLIES(mirror::Class::IsErroneous(oat_file_class_status), !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004606
Ian Rogers62d6c772013-02-27 08:32:07 -08004607 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004608 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004609 if (!preverified) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004610 verifier_failure = PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004611 } else if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks) {
4612 verifier_failure = verifier::FailureKind::kAccessChecksFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004613 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004614
4615 // Verification is done, grab the lock again.
4616 ObjectLock<mirror::Class> lock(self, klass);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004617 self->AssertNoPendingException();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004618
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004619 if (verifier_failure == verifier::FailureKind::kHardFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004620 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004621 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4622 << " because: " << error_msg;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004623 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004624 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004625 return verifier_failure;
jeffhao5cfd6fb2011-09-27 13:54:29 -07004626 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004627
4628 // Make sure all classes referenced by catch blocks are resolved.
4629 ResolveClassExceptionHandlerTypes(klass);
4630
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004631 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004632 if (supertype != nullptr && supertype->ShouldVerifyAtRuntime()) {
4633 // Regardless of our own verification result, we need to verify the class
4634 // at runtime if the super class is not verified. This is required in case
4635 // we generate an app/boot image.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004636 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4637 } else if (verifier_failure == verifier::FailureKind::kNoFailure) {
4638 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4639 } else if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4640 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
4641 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4642 } else {
4643 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4644 }
4645 // Notify the compiler about the verification status, in case the class
4646 // was verified implicitly (eg super class of a compiled class). When the
4647 // compiler unloads dex file after compilation, we still want to keep
4648 // verification states.
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004649 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4650 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004651 } else {
4652 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004653 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004654
4655 UpdateClassAfterVerification(klass, image_pointer_size_, verifier_failure);
Nicolas Geoffray08025182016-10-25 17:20:18 +01004656 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004657}
4658
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004659verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004660 verifier::VerifierDeps* verifier_deps,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004661 Handle<mirror::Class> klass,
4662 verifier::HardFailLogMode log_level,
4663 std::string* error_msg) {
4664 Runtime* const runtime = Runtime::Current();
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004665 StackHandleScope<2> hs(self);
4666 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4667 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004668 return verifier::ClassVerifier::VerifyClass(self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004669 verifier_deps,
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004670 dex_cache->GetDexFile(),
4671 klass,
4672 dex_cache,
4673 class_loader,
4674 *klass->GetClassDef(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004675 runtime->GetCompilerCallbacks(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004676 log_level,
4677 Runtime::Current()->GetTargetSdkVersion(),
4678 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004679}
4680
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004681bool ClassLinker::VerifyClassUsingOatFile(Thread* self,
4682 const DexFile& dex_file,
4683 Handle<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004684 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004685 // If we're compiling, we can only verify the class using the oat file if
4686 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004687 // the compilation unit (app - dependencies). We will let the compiler callback
4688 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004689 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004690 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004691 // We are compiling an app (not the image).
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004692 if (!callbacks->CanUseOatStatusForVerification(klass.Get())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004693 return false;
4694 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004695 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004696
Andreas Gampeb40d3612018-06-26 15:49:42 -07004697 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004698 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004699 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004700 return false;
4701 }
4702
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004703 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004704 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004705 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004706 return true;
4707 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004708 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4709 // We return that the clas has already been verified, and the caller should
4710 // check the class status to ensure we run with access checks.
4711 return true;
4712 }
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004713
4714 // Check the class status with the vdex file.
4715 const OatFile* oat_file = oat_dex_file->GetOatFile();
4716 if (oat_file != nullptr) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004717 ClassStatus vdex_status = oat_file->GetVdexFile()->ComputeClassStatus(self, klass);
4718 if (vdex_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
Nicolas Geoffray327cfcf2021-10-12 14:13:25 +01004719 VLOG(verifier) << "Vdex verification success for " << klass->PrettyClass();
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004720 oat_file_class_status = vdex_status;
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004721 return true;
4722 }
4723 }
4724
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004725 // If we only verified a subset of the classes at compile time, we can end up with classes that
4726 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004727 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004728 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004729 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004730 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4731 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4732 << klass->PrettyClass() << " " << dex_file.GetLocation();
4733
Vladimir Marko72ab6842017-01-20 19:32:50 +00004734 if (mirror::Class::IsErroneous(oat_file_class_status)) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004735 // Compile time verification failed with a hard error. We'll re-run
4736 // verification, which might be successful at runtime.
jeffhao1ac29442012-03-26 11:37:32 -07004737 return false;
4738 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004739 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004740 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4741 // not loading the class.
4742 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4743 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004744 return false;
4745 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004746 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004747 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004748 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004749 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004750 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004751}
4752
Alex Light5a559862016-01-29 12:24:48 -08004753void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004754 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004755 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004756 }
4757}
4758
Alex Light5a559862016-01-29 12:24:48 -08004759void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004760 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004761 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004762 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004763 return; // native or abstract method
4764 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004765 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004766 return; // nothing to process
4767 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004768 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004769 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004770 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4771 CatchHandlerIterator iterator(handlers_ptr);
4772 for (; iterator.HasNext(); iterator.Next()) {
4773 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4774 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004775 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004776 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004777 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004778 DCHECK(Thread::Current()->IsExceptionPending());
4779 Thread::Current()->ClearException();
4780 }
4781 }
4782 }
4783 handlers_ptr = iterator.EndDataPointer();
4784 }
4785}
4786
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004787ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4788 jstring name,
4789 jobjectArray interfaces,
4790 jobject loader,
4791 jobjectArray methods,
4792 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004793 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004794
4795 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4796 // code to be executed. We put it up here so we can avoid all the allocations associated with
4797 // creating the class. This can happen with (eg) jit-threads.
4798 if (!self->CanLoadClasses()) {
4799 // Make sure we don't try to load anything, potentially causing an infinite loop.
4800 ObjPtr<mirror::Throwable> pre_allocated =
4801 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4802 self->SetException(pre_allocated);
4803 return nullptr;
4804 }
4805
Alex Light133987d2020-03-26 19:22:12 +00004806 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004807 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004808 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004809 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004810 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004811 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004812 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004813 DCHECK(temp_klass->GetClass() != nullptr);
4814 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004815 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4816 // the methods.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004817 temp_klass->SetAccessFlagsDuringLinking(kAccClassIsProxy | kAccPublic | kAccFinal);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004818 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4819 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4820 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004821 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004822 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004823 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004824 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004825 std::string storage;
4826 const char* descriptor = temp_klass->GetDescriptor(&storage);
4827 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004828
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004829 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004830 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004831
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004832 // Insert the class before loading the fields as the field roots
4833 // (ArtField::declaring_class_) are only visited from the class
4834 // table. There can't be any suspend points between inserting the
4835 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004836 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004837 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004838
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004839 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004840 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004841 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004842 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004843
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004844 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4845 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004846 ArtField& interfaces_sfield = sfields->At(0);
4847 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004848 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004849 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004850
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004851 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004852 ArtField& throws_sfield = sfields->At(1);
4853 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004854 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004855 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004856
Ian Rogers466bb252011-10-14 03:29:56 -07004857 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004858 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004859
Alex Light133987d2020-03-26 19:22:12 +00004860 // The array we get passed contains all methods, including private and static
4861 // ones that aren't proxied. We need to filter those out since only interface
4862 // methods (non-private & virtual) are actually proxied.
4863 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4864 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004865 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004866 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004867 // List of the actual virtual methods this class will have.
4868 std::vector<ArtMethod*> proxied_methods;
4869 std::vector<size_t> proxied_throws_idx;
4870 proxied_methods.reserve(h_methods->GetLength());
4871 proxied_throws_idx.reserve(h_methods->GetLength());
4872 // Filter out to only the non-private virtual methods.
4873 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4874 ArtMethod* m = mirror->GetArtMethod();
4875 if (!m->IsPrivate() && !m->IsStatic()) {
4876 proxied_methods.push_back(m);
4877 proxied_throws_idx.push_back(idx);
4878 }
4879 }
4880 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004881 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4882 // contains an array of all the classes each function is declared to throw.
4883 // This is used to wrap unexpected exceptions in a
4884 // UndeclaredThrowableException exception. This array is in the same order as
4885 // the methods array and like the methods array must be filtered to remove any
4886 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004887 const bool has_filtered_methods =
4888 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4889 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4890 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4891 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4892 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4893 (has_filtered_methods)
4894 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4895 self, original_proxied_throws->GetClass(), num_virtual_methods)
4896 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004897 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4898 self->AssertPendingOOMException();
4899 return nullptr;
4900 }
Alex Light133987d2020-03-26 19:22:12 +00004901 if (has_filtered_methods) {
4902 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
4903 DCHECK_LE(new_idx, orig_idx);
4904 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
4905 }
4906 }
Alex Lighte64300b2015-12-15 15:02:47 -08004907
4908 // Create the methods array.
4909 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4910 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004911 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4912 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004913 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004914 self->AssertPendingOOMException();
4915 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004916 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004917 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004918
4919 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004920 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004921
4922 // Create virtual method using specified prototypes.
4923 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004924 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004925 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004926 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004927 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004928 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4929 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004930 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004931
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004932 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004933 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004934 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004935 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004936 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004937
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004938 // At this point the class is loaded. Publish a ClassLoad event.
4939 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4940 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4941
4942 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004943 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004944 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004945 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004946 // Link the fields and virtual methods, creating vtable and iftables.
4947 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004948 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004949 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004950 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Markoa4d28dd2021-06-30 11:28:06 +01004951 if (!temp_klass->IsErroneous()) {
4952 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
4953 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004954 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004955 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004956 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004957 CHECK(temp_klass->IsRetired());
4958 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004959
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004960 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004961 interfaces_sfield.SetObject<false>(
4962 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004963 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004964 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4965 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004966 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00004967 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004968
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004969 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4970
Vladimir Marko305c38b2018-02-14 11:50:07 +00004971 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4972 // See also ClassLinker::EnsureInitialized().
4973 if (kBitstringSubtypeCheckEnabled) {
4974 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4975 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4976 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4977 }
4978
Vladimir Markobf121912019-06-04 13:49:05 +01004979 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004980 {
4981 // Lock on klass is released. Lock new class object.
4982 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Markobf121912019-06-04 13:49:05 +01004983 // Conservatively go through the ClassStatus::kInitialized state.
4984 callback = MarkClassInitialized(self, klass);
4985 }
4986 if (callback != nullptr) {
4987 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07004988 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004989
David Srbecky346fd962020-07-27 16:51:00 +01004990 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07004991 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004992 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004993 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4994
Ian Rogersc2b44472011-12-14 21:17:17 -08004995 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004996 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004997 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08004998 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004999
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005000 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005001 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005002 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005003 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005004 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005005
5006 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005007 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005008 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005009
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005010 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005011 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005012 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005013 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005014 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005015 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005016}
5017
Mathieu Chartiere401d142015-04-22 13:56:20 -07005018void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5019 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005020 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5021 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005022
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005023 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5024 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005025 ArtMethod* proxy_constructor =
5026 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005027 DCHECK(proxy_constructor != nullptr)
5028 << "Could not find <init> method in java.lang.reflect.Proxy";
5029
Jeff Haodb8a6642014-08-14 17:18:52 -07005030 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5031 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005032 DCHECK(out != nullptr);
5033 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005034 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005035 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005036 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005037 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5038 kAccPublic |
5039 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005040 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005041
5042 // Set the original constructor method.
5043 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005044}
5045
Mathieu Chartiere401d142015-04-22 13:56:20 -07005046void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005047 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005048 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5049 CHECK_STREQ(np->GetName(), "<init>");
5050 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005051 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005052}
5053
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005054void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005055 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005056 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005057 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005058 DCHECK(out != nullptr);
5059 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005060
Alex Lighte9dd04f2016-03-16 16:09:45 -07005061 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005062 out->SetDeclaringClass(klass.Get());
Vladimir Markode0d0de2021-03-18 14:12:35 +00005063 // Clear the abstract and default flags to ensure that defaults aren't picked in
Alex Lighte9dd04f2016-03-16 16:09:45 -07005064 // preference to the invocation handler.
Vladimir Markode0d0de2021-03-18 14:12:35 +00005065 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005066 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005067 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5068 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005069 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5070
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005071 // Set the original interface method.
5072 out->SetDataPtrSize(prototype, image_pointer_size_);
5073
Ian Rogers466bb252011-10-14 03:29:56 -07005074 // At runtime the method looks like a reference and argument saving method, clone the code
5075 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005076 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005077}
Jesse Wilson95caa792011-10-12 18:14:17 -04005078
Mathieu Chartiere401d142015-04-22 13:56:20 -07005079void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005080 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005081 CHECK(!prototype->IsFinal());
5082 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005083 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005084
5085 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5086 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005087 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005088 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005089}
5090
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005091bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005092 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005093 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005094 return true;
5095 }
5096 if (!can_init_statics) {
5097 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005098 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005099 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005100 return false;
5101 }
5102 // Check if there are encoded static values needing initialization.
5103 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005104 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005105 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005106 if (dex_class_def->static_values_off_ != 0) {
5107 return false;
5108 }
5109 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005110 }
5111 // If we are a class we need to initialize all interfaces with default methods when we are
5112 // initialized. Check all of them.
5113 if (!klass->IsInterface()) {
5114 size_t num_interfaces = klass->GetIfTableCount();
5115 for (size_t i = 0; i < num_interfaces; i++) {
5116 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5117 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5118 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005119 return false;
5120 }
5121 }
5122 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005123 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005124 if (klass->IsInterface() || !klass->HasSuperClass()) {
5125 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005126 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005127 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005128 if (super_class->IsInitialized()) {
5129 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005130 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005131 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005132}
5133
Mathieu Chartier23369542020-03-04 08:24:11 -08005134bool ClassLinker::InitializeClass(Thread* self,
5135 Handle<mirror::Class> klass,
5136 bool can_init_statics,
5137 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005138 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5139
5140 // Are we already initialized and therefore done?
5141 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5142 // an initialized class will never change its state.
5143 if (klass->IsInitialized()) {
5144 return true;
5145 }
5146
5147 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005148 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005149 return false;
5150 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005151
Ian Rogers7b078e82014-09-10 14:44:24 -07005152 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005153 Runtime* const runtime = Runtime::Current();
5154 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005155 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005156 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005157 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005158
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005159 // Re-check under the lock in case another thread initialized ahead of us.
5160 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005161 return true;
5162 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005163
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005164 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005165 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005166 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005167 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005168 return false;
5169 }
5170
Vladimir Marko72ab6842017-01-20 19:32:50 +00005171 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5172 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005173
5174 if (!klass->IsVerified()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00005175 VerifyClass(self, /*verifier_deps= */ nullptr, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005176 if (!klass->IsVerified()) {
5177 // We failed to verify, expect either the klass to be erroneous or verification failed at
5178 // compile time.
5179 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005180 // The class is erroneous. This may be a verifier error, or another thread attempted
5181 // verification and/or initialization and failed. We can distinguish those cases by
5182 // whether an exception is already pending.
5183 if (self->IsExceptionPending()) {
5184 // Check that it's a VerifyError.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +01005185 DCHECK(IsVerifyError(self->GetException()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005186 } else {
5187 // Check that another thread attempted initialization.
5188 DCHECK_NE(0, klass->GetClinitThreadId());
5189 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5190 // Need to rethrow the previous failure now.
5191 ThrowEarlierClassFailure(klass.Get(), true);
5192 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005193 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005194 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005195 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005196 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005197 self->AssertNoPendingException();
5198 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005199 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005200 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005201 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005202 } else {
5203 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005204 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005205
5206 // A separate thread could have moved us all the way to initialized. A "simple" example
5207 // involves a subclass of the current class being initialized at the same time (which
5208 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005209 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005210 if (klass->IsInitialized()) {
5211 return true;
5212 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005213 }
5214
Vladimir Marko2c64a832018-01-04 11:31:56 +00005215 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005216 // initializing higher up the stack or another thread has beat us
5217 // to initializing and we need to wait. Either way, this
5218 // invocation of InitializeClass will not be responsible for
5219 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005220 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005221 // Could have got an exception during verification.
5222 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005223 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005224 return false;
5225 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005226 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005227 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005228 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005229 return true;
5230 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005231 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005232 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005233 }
5234
Jeff Haoe2e40342017-07-19 10:45:18 -07005235 // Try to get the oat class's status for this class if the oat file is present. The compiler
5236 // tries to validate superclass descriptors, and writes the result into the oat file.
5237 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5238 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5239 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005240 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005241 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5242 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5243 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005244 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005245 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005246 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005247 return false;
5248 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005249 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005250
Vladimir Marko2c64a832018-01-04 11:31:56 +00005251 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005252 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005253
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005254 // From here out other threads may observe that we're initializing and so changes of state
5255 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005256 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005257 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005258
Mathieu Chartier23369542020-03-04 08:24:11 -08005259 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005260 }
5261
Andreas Gampeaf864702019-07-23 14:05:35 -07005262 uint64_t t_sub = 0;
5263
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005264 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005265 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005266 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005267 if (!super_class->IsInitialized()) {
5268 CHECK(!super_class->IsInterface());
5269 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005270 StackHandleScope<1> hs(self);
5271 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005272 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005273 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005274 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005275 if (!super_initialized) {
5276 // The super class was verified ahead of entering initializing, we should only be here if
5277 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005278 // For the case of aot compiler, the super class might also be initializing but we don't
5279 // want to process circular dependencies in pre-compile.
5280 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005281 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005282 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005283 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005284 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005285 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005286 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005287 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005288 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005289 return false;
5290 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005291 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005292 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005293 }
5294
Alex Lighteb7c1442015-08-31 13:17:42 -07005295 if (!klass->IsInterface()) {
5296 // Initialize interfaces with default methods for the JLS.
5297 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005298 // Only setup the (expensive) handle scope if we actually need to.
5299 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005300 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005301 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5302 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005303 handle_scope_iface.Assign(klass->GetDirectInterface(i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005304 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005305 CHECK(handle_scope_iface->IsInterface());
5306 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5307 // We have already done this for this interface. Skip it.
5308 continue;
5309 }
5310 // We cannot just call initialize class directly because we need to ensure that ALL
5311 // interfaces with default methods are initialized. Non-default interface initialization
5312 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005313 // This is not very precise, misses all walking.
5314 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005315 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5316 handle_scope_iface,
5317 can_init_statics,
5318 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005319 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005320 if (!iface_initialized) {
5321 ObjectLock<mirror::Class> lock(self, klass);
5322 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005323 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005324 return false;
5325 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005326 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005327 }
5328 }
5329 }
5330
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005331 const size_t num_static_fields = klass->NumStaticFields();
5332 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005333 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005334 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005335 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005336 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005337 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005338
5339 // Eagerly fill in static fields so that the we don't have to do as many expensive
5340 // Class::FindStaticField in ResolveField.
5341 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005342 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005343 const uint32_t field_idx = field->GetDexFieldIndex();
David Srbecky5de5efe2021-02-15 21:23:00 +00005344 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005345 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005346 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005347 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5348 field,
5349 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5350 hiddenapi::AccessMethod::kNone));
David Srbecky5de5efe2021-02-15 21:23:00 +00005351 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005352 } else {
5353 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005354 }
5355 }
5356
Vladimir Markoe11dd502017-12-08 14:09:45 +00005357 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5358 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005359 this,
5360 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005361 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005362
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005363 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005364 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005365 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005366 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5367 if (!value_it.HasNext()) {
5368 break;
5369 }
5370 ArtField* art_field = ResolveField(field.GetIndex(),
5371 dex_cache,
5372 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005373 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005374 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005375 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005376 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005377 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005378 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005379 if (self->IsExceptionPending()) {
5380 break;
5381 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005382 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005383 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005384 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005385 }
5386 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005387
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005388
Mathieu Chartierda595be2016-08-10 13:57:39 -07005389 if (!self->IsExceptionPending()) {
5390 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5391 if (clinit != nullptr) {
5392 CHECK(can_init_statics);
5393 JValue result;
5394 clinit->Invoke(self, nullptr, 0, &result, "V");
5395 }
5396 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005397 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005398 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005399
Vladimir Markobf121912019-06-04 13:49:05 +01005400 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005401 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005402 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005403 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005404
5405 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005406 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005407 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005408 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005409 } else if (Runtime::Current()->IsTransactionAborted()) {
5410 // The exception thrown when the transaction aborted has been caught and cleared
5411 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005412 VLOG(compiler) << "Return from class initializer of "
5413 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005414 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005415 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005416 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005417 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005418 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005419 if (stats_enabled) {
5420 RuntimeStats* global_stats = runtime->GetStats();
5421 RuntimeStats* thread_stats = self->GetStats();
5422 ++global_stats->class_init_count;
5423 ++thread_stats->class_init_count;
5424 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5425 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5426 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005427 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005428 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005429 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005430 std::string temp;
5431 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005432 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005433 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005434 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005435 }
Vladimir Markobf121912019-06-04 13:49:05 +01005436 if (callback != nullptr) {
5437 callback->MakeVisible(self);
5438 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005439 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005440}
5441
Alex Lighteb7c1442015-08-31 13:17:42 -07005442// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5443// and perform the initialization only on those interfaces that contain default methods.
5444bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5445 Handle<mirror::Class> iface,
5446 bool can_init_statics,
5447 bool can_init_parents) {
5448 CHECK(iface->IsInterface());
5449 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005450 // Only create the (expensive) handle scope if we need it.
5451 if (UNLIKELY(num_direct_ifaces > 0)) {
5452 StackHandleScope<1> hs(self);
5453 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5454 // First we initialize all of iface's super-interfaces recursively.
5455 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005456 ObjPtr<mirror::Class> super_iface = iface->GetDirectInterface(i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005457 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005458 if (!super_iface->HasBeenRecursivelyInitialized()) {
5459 // Recursive step
5460 handle_super_iface.Assign(super_iface);
5461 if (!InitializeDefaultInterfaceRecursive(self,
5462 handle_super_iface,
5463 can_init_statics,
5464 can_init_parents)) {
5465 return false;
5466 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005467 }
5468 }
5469 }
5470
5471 bool result = true;
5472 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5473 // initialize if we don't have default methods.
5474 if (iface->HasDefaultMethods()) {
5475 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5476 }
5477
5478 // Mark that this interface has undergone recursive default interface initialization so we know we
5479 // can skip it on any later class initializations. We do this even if we are not a default
5480 // interface since we can still avoid the traversal. This is purely a performance optimization.
5481 if (result) {
5482 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005483 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5484 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5485 // initialization is a performance optimization (to avoid another idempotent visit
5486 // for other implementing classes/interfaces), and can be revisited later.
5487 ObjectTryLock<mirror::Class> lock(self, iface);
5488 if (lock.Acquired()) {
5489 iface->SetRecursivelyInitialized();
5490 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005491 }
5492 return result;
5493}
5494
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005495bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5496 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005497 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005498 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005499 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005500 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005501 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005502 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005503
5504 // When we wake up, repeat the test for init-in-progress. If
5505 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005506 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005507 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005508 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005509 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005510 return false;
5511 }
5512 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005513 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005514 continue;
5515 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005516 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005517 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005518 // Compile time initialization failed.
5519 return false;
5520 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005521 if (klass->IsErroneous()) {
5522 // The caller wants an exception, but it was thrown in a
5523 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005524 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005525 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005526 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005527 return false;
5528 }
5529 if (klass->IsInitialized()) {
5530 return true;
5531 }
David Sehr709b0702016-10-13 09:12:37 -07005532 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005533 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005534 }
Ian Rogers07140832014-09-30 15:43:59 -07005535 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005536}
5537
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005538static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5539 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005540 ArtMethod* method,
5541 ArtMethod* m)
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();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005546 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5547 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005548 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005549 std::string return_type = dex_file->PrettyType(return_type_idx);
5550 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005551 ThrowWrappedLinkageError(klass.Get(),
5552 "While checking class %s method %s signature against %s %s: "
5553 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005554 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5555 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005556 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005557 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005558 return_type.c_str(), class_loader.c_str());
5559}
5560
5561static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5562 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005563 ArtMethod* method,
5564 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005565 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005566 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005567 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005568 DCHECK(Thread::Current()->IsExceptionPending());
5569 DCHECK(!m->IsProxyMethod());
5570 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005571 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5572 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005573 ThrowWrappedLinkageError(klass.Get(),
5574 "While checking class %s method %s signature against %s %s: "
5575 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005576 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5577 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005578 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005579 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005580 index, arg_type.c_str(), class_loader.c_str());
5581}
5582
5583static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5584 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005585 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005586 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005587 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005588 ThrowLinkageError(klass.Get(),
5589 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005590 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5591 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005592 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005593 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005594 error_msg.c_str());
5595}
5596
Ian Rogersb5fb2072014-12-02 17:22:02 -08005597static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005598 Handle<mirror::Class> klass,
5599 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005600 ArtMethod* method1,
5601 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005602 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005603 {
5604 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005605 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005606 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005607 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005608 return false;
5609 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005610 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005611 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005612 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005613 return false;
5614 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005615 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005616 ThrowSignatureMismatch(klass, super_klass, method1,
5617 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005618 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005619 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005620 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005621 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005622 return false;
5623 }
5624 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005625 const dex::TypeList* types1 = method1->GetParameterTypeList();
5626 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005627 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005628 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005629 ThrowSignatureMismatch(klass, super_klass, method1,
5630 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005631 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005632 return false;
5633 }
5634 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005635 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005636 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005637 ThrowSignatureMismatch(klass, super_klass, method1,
5638 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005639 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005640 return false;
5641 }
5642 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005643 }
5644 uint32_t num_types = types1->Size();
5645 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005646 ThrowSignatureMismatch(klass, super_klass, method1,
5647 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005648 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005649 return false;
5650 }
5651 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005652 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005653 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005654 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005655 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005656 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005657 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005658 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005659 return false;
5660 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005661 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005662 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005663 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005664 if (UNLIKELY(other_param_type == nullptr)) {
5665 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005666 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005667 return false;
5668 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005669 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005670 ThrowSignatureMismatch(klass, super_klass, method1,
5671 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5672 i,
David Sehr709b0702016-10-13 09:12:37 -07005673 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005674 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005675 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005676 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005677 return false;
5678 }
5679 }
5680 return true;
5681}
5682
5683
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005684bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005685 if (klass->IsInterface()) {
5686 return true;
5687 }
Ian Rogers151f2212014-05-06 11:27:27 -07005688 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005689 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005690 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005691 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005692 if (klass->HasSuperClass() &&
5693 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005694 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005695 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005696 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5697 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5698 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005699 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5700 klass,
5701 super_klass,
5702 m,
5703 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005704 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005705 return false;
5706 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005707 }
5708 }
5709 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005710 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005711 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5712 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5713 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005714 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005715 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5716 j, image_pointer_size_);
5717 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5718 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005719 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5720 klass,
5721 super_klass,
5722 m,
5723 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005724 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005725 return false;
5726 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005727 }
5728 }
5729 }
5730 }
5731 return true;
5732}
5733
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005734bool ClassLinker::EnsureInitialized(Thread* self,
5735 Handle<mirror::Class> c,
5736 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005737 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005738 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005739
Mathieu Chartier524507a2014-08-27 15:28:28 -07005740 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005741 // If we've seen an initialized but not visibly initialized class
5742 // many times, request visible initialization.
5743 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5744 // Thanks to the x86 memory model classes skip the initialized status.
5745 DCHECK(c->IsVisiblyInitialized());
5746 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5747 if (self->IncrementMakeVisiblyInitializedCounter()) {
5748 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5749 }
5750 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07005751 return true;
5752 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005753 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5754 //
5755 // Ensure the bitstring is initialized before any of the class initialization
5756 // logic occurs. Once a class initializer starts running, objects can
5757 // escape into the heap and use the subtype checking code.
5758 //
5759 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5760 // can be used as a source for the IsSubClass check, and that all ancestors
5761 // of the class are Assigned (can be used as a target for IsSubClass check)
5762 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005763 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005764 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005765 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005766 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5767 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005768 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005769 if (!success) {
5770 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005771 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Vladimir Markoac576912021-03-31 11:16:22 +01005772 } else {
5773 // There may or may not be an exception pending. If there is, clear it.
5774 // We propagate the exception only if we can initialize fields and parents.
5775 self->ClearException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005776 }
5777 } else {
5778 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005779 }
5780 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005781}
5782
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005783void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5784 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005785 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005786 for (ArtField& field : new_class->GetIFields()) {
5787 if (field.GetDeclaringClass() == temp_class) {
5788 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005789 }
5790 }
5791
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005792 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005793 for (ArtField& field : new_class->GetSFields()) {
5794 if (field.GetDeclaringClass() == temp_class) {
5795 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005796 }
5797 }
5798
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005799 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005800 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005801 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005802 if (method.GetDeclaringClass() == temp_class) {
5803 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005804 }
5805 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005806
5807 // Make sure the remembered set and mod-union tables know that we updated some of the native
5808 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005809 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005810}
5811
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005812void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005813 CHECK(class_loader->GetAllocator() == nullptr);
5814 CHECK(class_loader->GetClassTable() == nullptr);
5815 Thread* const self = Thread::Current();
5816 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005817 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005818 // Create and set the class table.
5819 data.class_table = new ClassTable;
5820 class_loader->SetClassTable(data.class_table);
5821 // Create and set the linear allocator.
5822 data.allocator = Runtime::Current()->CreateLinearAlloc();
5823 class_loader->SetAllocator(data.allocator);
5824 // Add to the list so that we know to free the data later.
5825 class_loaders_.push_back(data);
5826}
5827
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005828ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005829 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005830 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005831 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005832 ClassTable* class_table = class_loader->GetClassTable();
5833 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005834 RegisterClassLoader(class_loader);
5835 class_table = class_loader->GetClassTable();
5836 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005837 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005838 return class_table;
5839}
5840
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005841ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005842 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005843}
5844
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005845static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005846 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005847 while (klass->HasSuperClass()) {
5848 klass = klass->GetSuperClass();
5849 if (klass->ShouldHaveImt()) {
5850 return klass->GetImt(pointer_size);
5851 }
5852 }
5853 return nullptr;
5854}
5855
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005856bool ClassLinker::LinkClass(Thread* self,
5857 const char* descriptor,
5858 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005859 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005860 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005861 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005862
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005863 if (!LinkSuperClass(klass)) {
5864 return false;
5865 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005866 ArtMethod* imt_data[ImTable::kSize];
5867 // If there are any new conflicts compared to super class.
5868 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005869 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005870 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005871 return false;
5872 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005873 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005874 return false;
5875 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005876 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005877 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005878 return false;
5879 }
5880 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005881 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005882
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005883 ImTable* imt = nullptr;
5884 if (klass->ShouldHaveImt()) {
5885 // If there are any new conflicts compared to the super class we can not make a copy. There
5886 // can be cases where both will have a conflict method at the same slot without having the same
5887 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5888 // will possibly create a table that is incorrect for either of the classes.
5889 // Same IMT with new_conflict does not happen very often.
5890 if (!new_conflict) {
5891 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5892 if (super_imt != nullptr) {
5893 bool imt_equals = true;
5894 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5895 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5896 }
5897 if (imt_equals) {
5898 imt = super_imt;
5899 }
5900 }
5901 }
5902 if (imt == nullptr) {
5903 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5904 imt = reinterpret_cast<ImTable*>(
5905 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5906 if (imt == nullptr) {
5907 return false;
5908 }
5909 imt->Populate(imt_data, image_pointer_size_);
5910 }
5911 }
5912
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005913 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5914 // We don't need to retire this class as it has no embedded tables or it was created the
5915 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005916 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005917
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005918 if (klass->ShouldHaveEmbeddedVTable()) {
5919 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005920 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005921 if (klass->ShouldHaveImt()) {
5922 klass->SetImt(imt, image_pointer_size_);
5923 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005924
5925 // Update CHA info based on whether we override methods.
5926 // Have to do this before setting the class as resolved which allows
5927 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005928 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005929 cha_->UpdateAfterLoadingOf(klass);
5930 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005931
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005932 // This will notify waiters on klass that saw the not yet resolved
5933 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005934 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005935 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005936 } else {
5937 CHECK(!klass->IsResolved());
5938 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005939 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01005940 Handle<mirror::Class> h_new_class =
5941 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005942 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5943 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5944 // may not see any references to the target space and clean the card for a class if another
5945 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005946 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005947 klass->SetSFieldsPtrUnchecked(nullptr);
5948 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005949 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005950 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005951 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005952 return false;
5953 }
5954
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005955 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5956 ObjectLock<mirror::Class> lock(self, h_new_class);
5957 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005958
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005959 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005960 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005961 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005962 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005963 const ObjPtr<mirror::Class> existing =
5964 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005965 if (class_loader != nullptr) {
5966 // We updated the class in the class table, perform the write barrier so that the GC knows
5967 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005968 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005969 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005970 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005971 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005972 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5973 }
5974 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005975
Mingyao Yang063fc772016-08-02 11:02:54 -07005976 // Update CHA info based on whether we override methods.
5977 // Have to do this before setting the class as resolved which allows
5978 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005979 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005980 cha_->UpdateAfterLoadingOf(h_new_class);
5981 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005982
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005983 // This will notify waiters on temp class that saw the not yet resolved class in the
5984 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005985 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005986
Vladimir Marko2c64a832018-01-04 11:31:56 +00005987 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005988 // This will notify waiters on new_class that saw the not yet resolved
5989 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005990 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005991 // Return the new class.
5992 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005993 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005994 return true;
5995}
5996
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005997bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005998 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005999 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006000 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6001 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006002 // Check that a class does not inherit from itself directly.
6003 //
6004 // TODO: This is a cheap check to detect the straightforward case
6005 // of a class extending itself (b/28685551), but we should do a
6006 // proper cycle detection on loaded classes, to detect all cases
6007 // of class circularity errors (b/28830038).
6008 if (super_class_idx == class_def.class_idx_) {
6009 ThrowClassCircularityError(klass.Get(),
6010 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006011 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006012 return false;
6013 }
6014
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006015 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006016 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006017 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006018 return false;
6019 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006020 // Verify
6021 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006022 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006023 super_class->PrettyDescriptor().c_str(),
6024 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006025 return false;
6026 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006027 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006028 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006029 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006030 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006031 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006032 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006033 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006034 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006035 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006036 DCHECK(Thread::Current()->IsExceptionPending());
6037 return false;
6038 }
6039 // Verify
6040 if (!klass->CanAccess(interface)) {
6041 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006042 ThrowIllegalAccessError(klass.Get(),
6043 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006044 interface->PrettyDescriptor().c_str(),
6045 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006046 return false;
6047 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006048 }
6049 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006050 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006051 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006052 return true;
6053}
6054
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006055bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006056 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006057 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006058 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6059 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006060 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006061 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006062 return false;
6063 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006064 return true;
6065 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006066 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006067 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006068 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006069 return false;
6070 }
6071 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006072 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006073 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6074 return false;
6075 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006076 if (super->IsFinal()) {
6077 ThrowVerifyError(klass.Get(),
6078 "Superclass %s of %s is declared final",
6079 super->PrettyDescriptor().c_str(),
6080 klass->PrettyDescriptor().c_str());
6081 return false;
6082 }
6083 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006084 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006085 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006086 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006087 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006088 return false;
6089 }
6090 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006091 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006092 super->PrettyDescriptor().c_str(),
6093 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006094 return false;
6095 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006096
Brian Carlstromf3632832014-05-20 15:36:53 -07006097 // Inherit kAccClassIsFinalizable from the superclass in case this
6098 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006099 if (super->IsFinalizable()) {
6100 klass->SetFinalizable();
6101 }
6102
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006103 // Inherit class loader flag form super class.
6104 if (super->IsClassLoaderClass()) {
6105 klass->SetClassLoaderClass();
6106 }
6107
Elliott Hughes2da50362011-10-10 16:57:08 -07006108 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006109 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006110 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006111 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006112 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006113 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006114 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006115 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006116 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006117 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006118 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006119 return false;
6120 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006121
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006122 if (kIsDebugBuild) {
6123 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006124 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006125 CHECK(super->IsResolved());
6126 super = super->GetSuperClass();
6127 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006128 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006129 return true;
6130}
6131
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006132// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6133// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6134// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006135class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006136 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006137 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006138 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006139 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006140 name_view_() {
David Sehr709b0702016-10-13 09:12:37 -07006141 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006142 }
6143
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006144 ALWAYS_INLINE std::string_view GetNameView() {
6145 if (name_view_.empty()) {
6146 name_view_ = dex_file_->StringViewByIdx(mid_->name_idx_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006147 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006148 return name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006149 }
6150
Mathieu Chartiere401d142015-04-22 13:56:20 -07006151 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006152 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006153 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006154 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006155 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006156 if (dex_file_ == other_dex_file) {
6157 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6158 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006159 return GetNameView() == other_dex_file->StringViewByIdx(other_mid.name_idx_) &&
6160 dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006161 }
6162
6163 private:
6164 // Dex file for the method to compare against.
6165 const DexFile* const dex_file_;
6166 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006167 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006168 // Lazily computed name from the dex file's strings.
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006169 std::string_view name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006170};
6171
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006172ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006173 ArtMethod* conflict_method,
6174 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006175 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006176 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006177 Runtime* const runtime = Runtime::Current();
6178 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006179
6180 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006181 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006182 ? runtime->CreateImtConflictMethod(linear_alloc)
6183 : conflict_method;
6184
6185 // Allocate a new table. Note that we will leak this table at the next conflict,
6186 // but that's a tradeoff compared to making the table fixed size.
6187 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006188 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6189 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006190 if (data == nullptr) {
6191 LOG(ERROR) << "Failed to allocate conflict table";
6192 return conflict_method;
6193 }
6194 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6195 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006196 method,
6197 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006198
6199 // Do a fence to ensure threads see the data in the table before it is assigned
6200 // to the conflict method.
6201 // Note that there is a race in the presence of multiple threads and we may leak
6202 // memory from the LinearAlloc, but that's a tradeoff compared to using
6203 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006204 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006205 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006206 return new_conflict_method;
6207}
6208
6209void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6210 ArtMethod* imt_conflict_method,
6211 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006212 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006213 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006214 // Place method in imt if entry is empty, place conflict otherwise.
6215 if (*imt_ref == unimplemented_method) {
6216 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006217 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006218 // If we are not a conflict and we have the same signature and name as the imt
6219 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006220 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6221 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006222 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006223 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006224 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006225 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006226 *imt_ref = current_method;
6227 } else {
Alex Light9139e002015-10-09 15:59:48 -07006228 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006229 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006230 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006231 } else {
6232 // Place the default conflict method. Note that there may be an existing conflict
6233 // method in the IMT, but it could be one tailored to the super class, with a
6234 // specific ImtConflictTable.
6235 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006236 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006237 }
6238}
6239
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006240void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006241 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6242 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006243 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006244 Runtime* const runtime = Runtime::Current();
6245 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6246 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006247 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006248 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006249 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006250 FillIMTFromIfTable(klass->GetIfTable(),
6251 unimplemented_method,
6252 conflict_method,
6253 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006254 /*create_conflict_tables=*/true,
6255 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006256 &new_conflict,
6257 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006258 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006259 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6260 // we can just use the same pointer.
6261 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006262 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006263 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6264 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6265 bool same = true;
6266 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6267 ArtMethod* method = imt_data[i];
6268 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6269 if (method != super_method) {
6270 bool is_conflict_table = method->IsRuntimeMethod() &&
6271 method != unimplemented_method &&
6272 method != conflict_method;
6273 // Verify conflict contents.
6274 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6275 super_method != unimplemented_method &&
6276 super_method != conflict_method;
6277 if (!is_conflict_table || !super_conflict_table) {
6278 same = false;
6279 } else {
6280 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6281 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6282 same = same && table1->Equals(table2, image_pointer_size_);
6283 }
6284 }
6285 }
6286 if (same) {
6287 imt = super_imt;
6288 }
6289 }
6290 if (imt == nullptr) {
6291 imt = klass->GetImt(image_pointer_size_);
6292 DCHECK(imt != nullptr);
6293 imt->Populate(imt_data, image_pointer_size_);
6294 } else {
6295 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006296 }
6297}
6298
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006299ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6300 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006301 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006302 void* data = linear_alloc->Alloc(Thread::Current(),
6303 ImtConflictTable::ComputeSize(count,
6304 image_pointer_size));
6305 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6306}
6307
6308ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6309 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6310}
6311
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006312void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006313 ArtMethod* unimplemented_method,
6314 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006315 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006316 bool create_conflict_tables,
6317 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006318 /*out*/bool* new_conflict,
6319 /*out*/ArtMethod** imt) {
6320 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006321 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006322 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006323 const size_t num_virtuals = interface->NumVirtualMethods();
6324 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6325 // Virtual methods can be larger than the if table methods if there are default methods.
6326 DCHECK_GE(num_virtuals, method_array_count);
6327 if (kIsDebugBuild) {
6328 if (klass->IsInterface()) {
6329 DCHECK_EQ(method_array_count, 0u);
6330 } else {
6331 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6332 }
6333 }
6334 if (method_array_count == 0) {
6335 continue;
6336 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006337 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006338 for (size_t j = 0; j < method_array_count; ++j) {
6339 ArtMethod* implementation_method =
6340 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6341 if (ignore_copied_methods && implementation_method->IsCopied()) {
6342 continue;
6343 }
6344 DCHECK(implementation_method != nullptr);
6345 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6346 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6347 // or interface methods in the IMT here they will not create extra conflicts since we compare
6348 // names and signatures in SetIMTRef.
6349 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006350 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006351
6352 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6353 // the same implementation method, keep track of this to avoid creating a conflict table in
6354 // this case.
6355
6356 // Conflict table size for each IMT slot.
6357 ++conflict_counts[imt_index];
6358
6359 SetIMTRef(unimplemented_method,
6360 imt_conflict_method,
6361 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006362 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006363 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006364 }
6365 }
6366
6367 if (create_conflict_tables) {
6368 // Create the conflict tables.
6369 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006370 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006371 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006372 if (imt[i] == imt_conflict_method) {
6373 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6374 if (new_table != nullptr) {
6375 ArtMethod* new_conflict_method =
6376 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6377 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6378 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006379 } else {
6380 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006381 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006382 }
6383 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006384 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006385 }
6386 }
6387
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006388 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006389 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006390 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6391 // Virtual methods can be larger than the if table methods if there are default methods.
6392 if (method_array_count == 0) {
6393 continue;
6394 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006395 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006396 for (size_t j = 0; j < method_array_count; ++j) {
6397 ArtMethod* implementation_method =
6398 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6399 if (ignore_copied_methods && implementation_method->IsCopied()) {
6400 continue;
6401 }
6402 DCHECK(implementation_method != nullptr);
6403 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006404 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006405 if (!imt[imt_index]->IsRuntimeMethod() ||
6406 imt[imt_index] == unimplemented_method ||
6407 imt[imt_index] == imt_conflict_method) {
6408 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006409 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006410 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6411 const size_t num_entries = table->NumEntries(image_pointer_size_);
6412 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6413 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006414 }
6415 }
6416 }
6417}
6418
Vladimir Marko78f62d82022-01-10 16:25:19 +00006419namespace {
6420
Alex Lighteb7c1442015-08-31 13:17:42 -07006421// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6422// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006423static bool NotSubinterfaceOfAny(
Vladimir Marko78f62d82022-01-10 16:25:19 +00006424 const ScopedArenaHashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006425 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006426 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006427 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006428 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006429 for (ObjPtr<mirror::Class> c : classes) {
6430 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006431 return false;
6432 }
6433 }
6434 return true;
6435}
6436
Vladimir Marko78f62d82022-01-10 16:25:19 +00006437// We record new interfaces by the index of the direct interface and the index in the
6438// direct interface's `IfTable`, or `dex::kDexNoIndex` if it's the direct interface itself.
6439struct NewInterfaceReference {
6440 uint32_t direct_interface_index;
6441 uint32_t direct_interface_iftable_index;
6442};
6443
6444class ProxyInterfacesAccessor {
6445 public:
6446 explicit ProxyInterfacesAccessor(Handle<mirror::ObjectArray<mirror::Class>> interfaces)
6447 REQUIRES_SHARED(Locks::mutator_lock_)
6448 : interfaces_(interfaces) {}
6449
6450 size_t GetLength() REQUIRES_SHARED(Locks::mutator_lock_) {
6451 return interfaces_->GetLength();
6452 }
6453
6454 ObjPtr<mirror::Class> GetInterface(size_t index) REQUIRES_SHARED(Locks::mutator_lock_) {
6455 DCHECK_LT(index, GetLength());
6456 return interfaces_->GetWithoutChecks(index);
6457 }
6458
6459 private:
6460 Handle<mirror::ObjectArray<mirror::Class>> interfaces_;
6461};
6462
6463class NonProxyInterfacesAccessor {
6464 public:
6465 NonProxyInterfacesAccessor(ClassLinker* class_linker, Handle<mirror::Class> klass)
6466 REQUIRES_SHARED(Locks::mutator_lock_)
6467 : interfaces_(klass->GetInterfaceTypeList()),
6468 class_linker_(class_linker),
6469 klass_(klass) {
6470 DCHECK(!klass->IsProxyClass());
6471 }
6472
6473 size_t GetLength() REQUIRES_SHARED(Locks::mutator_lock_) {
6474 return (interfaces_ != nullptr) ? interfaces_->Size() : 0u;
6475 }
6476
6477 ObjPtr<mirror::Class> GetInterface(size_t index) REQUIRES_SHARED(Locks::mutator_lock_) {
6478 DCHECK_LT(index, GetLength());
6479 dex::TypeIndex type_index = interfaces_->GetTypeItem(index).type_idx_;
6480 return class_linker_->LookupResolvedType(type_index, klass_.Get());
6481 }
6482
6483 private:
6484 const dex::TypeList* interfaces_;
6485 ClassLinker* class_linker_;
6486 Handle<mirror::Class> klass_;
6487};
6488
6489// Finds new interfaces to add to the interface table in addition to superclass interfaces.
Alex Lighteb7c1442015-08-31 13:17:42 -07006490//
Vladimir Marko78f62d82022-01-10 16:25:19 +00006491// Interfaces in the interface table must satisfy the following constraint:
6492// all I, J: Interface | I <: J implies J precedes I
6493// (note A <: B means that A is a subtype of B). We order this backwards so that we do not need
6494// to reorder superclass interfaces when new interfaces are added in subclass's interface tables.
Alex Lighteb7c1442015-08-31 13:17:42 -07006495//
Vladimir Marko78f62d82022-01-10 16:25:19 +00006496// This function returns a list of references for all interfaces in the transitive
6497// closure of the direct interfaces that are not in the superclass interfaces.
6498// The entries in the list are ordered to satisfy the interface table ordering
6499// constraint and therefore the interface table formed by appending them to the
6500// superclass interface table shall also satisfy that constraint.
6501template <typename InterfaceAccessor>
6502ALWAYS_INLINE
6503static ArrayRef<const NewInterfaceReference> FindNewIfTableInterfaces(
6504 ObjPtr<mirror::IfTable> super_iftable,
6505 size_t super_ifcount,
6506 ScopedArenaAllocator* allocator,
6507 InterfaceAccessor&& interfaces,
6508 ArrayRef<NewInterfaceReference> initial_storage,
6509 /*out*/ScopedArenaVector<NewInterfaceReference>* supplemental_storage)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006510 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00006511 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006512
Vladimir Marko782fb712020-12-23 12:47:31 +00006513 // This is the set of all classes already in the iftable. Used to make checking
6514 // if a class has already been added quicker.
6515 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
6516 mirror::Class* buffer[kBufferSize];
Vladimir Marko78f62d82022-01-10 16:25:19 +00006517 ScopedArenaHashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize, allocator->Adapter());
Alex Lighteb7c1442015-08-31 13:17:42 -07006518 // The first super_ifcount elements are from the superclass. We note that they are already added.
6519 for (size_t i = 0; i < super_ifcount; i++) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00006520 ObjPtr<mirror::Class> iface = super_iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006521 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006522 classes_in_iftable.Put(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07006523 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006524
6525 ArrayRef<NewInterfaceReference> current_storage = initial_storage;
6526 DCHECK_NE(current_storage.size(), 0u);
6527 size_t num_new_interfaces = 0u;
6528 auto insert_reference = [&](uint32_t direct_interface_index,
6529 uint32_t direct_interface_iface_index) {
6530 if (UNLIKELY(num_new_interfaces == current_storage.size())) {
6531 bool copy = current_storage.data() != supplemental_storage->data();
6532 supplemental_storage->resize(2u * num_new_interfaces);
6533 if (copy) {
6534 std::copy_n(current_storage.data(), num_new_interfaces, supplemental_storage->data());
6535 }
6536 current_storage = ArrayRef<NewInterfaceReference>(*supplemental_storage);
6537 }
6538 current_storage[num_new_interfaces] = {direct_interface_index, direct_interface_iface_index};
6539 ++num_new_interfaces;
6540 };
6541
6542 for (size_t i = 0, num_interfaces = interfaces.GetLength(); i != num_interfaces; ++i) {
6543 ObjPtr<mirror::Class> interface = interfaces.GetInterface(i);
Vladimir Marko782fb712020-12-23 12:47:31 +00006544
Alex Lighteb7c1442015-08-31 13:17:42 -07006545 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6546 // At this point in the loop current-iface-list has the invariant that:
6547 // for every pair of interfaces I,J within it:
6548 // if index_of(I) < index_of(J) then I is not a subtype of J
6549
6550 // If we have already seen this element then all of its super-interfaces must already be in the
6551 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00006552 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006553 // We haven't seen this interface so add all of its super-interfaces onto the
6554 // current-iface-list, skipping those already on it.
6555 int32_t ifcount = interface->GetIfTableCount();
6556 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006557 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006558 if (classes_in_iftable.find(super_interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006559 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006560 classes_in_iftable.Put(super_interface.Ptr());
6561 insert_reference(i, j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006562 }
6563 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006564 // Add this interface reference after all of its super-interfaces.
Alex Lighteb7c1442015-08-31 13:17:42 -07006565 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006566 classes_in_iftable.Put(interface.Ptr());
6567 insert_reference(i, dex::kDexNoIndex);
Alex Lighteb7c1442015-08-31 13:17:42 -07006568 } else if (kIsDebugBuild) {
6569 // Check all super-interfaces are already in the list.
6570 int32_t ifcount = interface->GetIfTableCount();
6571 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006572 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006573 DCHECK(classes_in_iftable.find(super_interface.Ptr()) != classes_in_iftable.end())
David Sehr709b0702016-10-13 09:12:37 -07006574 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6575 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006576 }
6577 }
6578 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006579 return ArrayRef<const NewInterfaceReference>(current_storage.data(), num_new_interfaces);
6580}
6581
6582template <typename InterfaceAccessor>
6583static ObjPtr<mirror::IfTable> SetupInterfaceLookupTable(
6584 Thread* self,
6585 Handle<mirror::Class> klass,
6586 ScopedArenaAllocator* allocator,
6587 InterfaceAccessor&& interfaces)
6588 REQUIRES_SHARED(Locks::mutator_lock_) {
6589 DCHECK(klass->HasSuperClass());
6590 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Vladimir Marko0441d202022-02-18 13:55:15 +00006591 DCHECK(super_iftable != nullptr);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006592 const size_t num_interfaces = interfaces.GetLength();
6593
Vladimir Marko0441d202022-02-18 13:55:15 +00006594 // If there are no new interfaces, return the interface table from superclass.
6595 // If any implementation methods are overridden, we shall copy the table and
6596 // the method arrays that contain any differences (copy-on-write).
6597 if (num_interfaces == 0) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00006598 return super_iftable;
6599 }
6600
6601 // Check that every class being implemented is an interface.
6602 for (size_t i = 0; i != num_interfaces; ++i) {
6603 ObjPtr<mirror::Class> interface = interfaces.GetInterface(i);
6604 DCHECK(interface != nullptr);
6605 if (UNLIKELY(!interface->IsInterface())) {
6606 ThrowIncompatibleClassChangeError(klass.Get(),
6607 "Class %s implements non-interface class %s",
6608 klass->PrettyDescriptor().c_str(),
6609 interface->PrettyDescriptor().c_str());
6610 return nullptr;
6611 }
6612 }
6613
6614 static constexpr size_t kMaxStackReferences = 16;
6615 NewInterfaceReference initial_storage[kMaxStackReferences];
6616 ScopedArenaVector<NewInterfaceReference> supplemental_storage(allocator->Adapter());
Vladimir Marko0441d202022-02-18 13:55:15 +00006617 const size_t super_ifcount = super_iftable->Count();
Vladimir Marko78f62d82022-01-10 16:25:19 +00006618 ArrayRef<const NewInterfaceReference> new_interface_references =
6619 FindNewIfTableInterfaces(
6620 super_iftable,
6621 super_ifcount,
6622 allocator,
6623 interfaces,
6624 ArrayRef<NewInterfaceReference>(initial_storage),
6625 &supplemental_storage);
6626
Vladimir Marko0441d202022-02-18 13:55:15 +00006627 // If all declared interfaces were already present in superclass interface table,
6628 // return the interface table from superclass. See above.
6629 if (UNLIKELY(new_interface_references.empty())) {
6630 return super_iftable;
Vladimir Marko78f62d82022-01-10 16:25:19 +00006631 }
6632
6633 // Create the interface table.
6634 size_t ifcount = super_ifcount + new_interface_references.size();
6635 ObjPtr<mirror::IfTable> iftable = AllocIfTable(self, ifcount, super_iftable->GetClass());
6636 if (UNLIKELY(iftable == nullptr)) {
6637 self->AssertPendingOOMException();
6638 return nullptr;
6639 }
6640 // Fill in table with superclass's iftable.
6641 if (super_ifcount != 0) {
6642 // Reload `super_iftable` as it may have been clobbered by the allocation.
6643 super_iftable = klass->GetSuperClass()->GetIfTable();
Vladimir Marko0441d202022-02-18 13:55:15 +00006644 for (size_t i = 0; i != super_ifcount; i++) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00006645 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Vladimir Marko0441d202022-02-18 13:55:15 +00006646 DCHECK(super_interface != nullptr);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006647 iftable->SetInterface(i, super_interface);
Vladimir Marko0441d202022-02-18 13:55:15 +00006648 ObjPtr<mirror::PointerArray> method_array = super_iftable->GetMethodArrayOrNull(i);
6649 if (method_array != nullptr) {
6650 iftable->SetMethodArray(i, method_array);
6651 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006652 }
6653 }
6654 // Fill in the table with additional interfaces.
6655 size_t current_index = super_ifcount;
6656 for (NewInterfaceReference ref : new_interface_references) {
6657 ObjPtr<mirror::Class> direct_interface = interfaces.GetInterface(ref.direct_interface_index);
6658 ObjPtr<mirror::Class> new_interface = (ref.direct_interface_iftable_index != dex::kDexNoIndex)
6659 ? direct_interface->GetIfTable()->GetInterface(ref.direct_interface_iftable_index)
6660 : direct_interface;
6661 iftable->SetInterface(current_index, new_interface);
6662 ++current_index;
6663 }
6664 DCHECK_EQ(current_index, ifcount);
6665
Alex Lighteb7c1442015-08-31 13:17:42 -07006666 if (kIsDebugBuild) {
6667 // Check that the iftable is ordered correctly.
Vladimir Marko78f62d82022-01-10 16:25:19 +00006668 for (size_t i = 0; i < ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006669 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006670 for (size_t j = i + 1; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006671 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006672 // !(if_a <: if_b)
6673 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006674 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6675 << ") extends "
6676 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006677 << "interface list.";
6678 }
6679 }
6680 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006681
Vladimir Marko78f62d82022-01-10 16:25:19 +00006682 return iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006683}
6684
Alex Light1f3925d2016-09-07 12:04:20 -07006685// Check that all vtable entries are present in this class's virtuals or are the same as a
6686// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006687void CheckClassOwnsVTableEntries(Thread* self,
6688 Handle<mirror::Class> klass,
6689 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006690 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006691 StackHandleScope<2> hs(self);
6692 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006693 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006694 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006695 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006696 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6697 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6698 CHECK(m != nullptr);
6699
Alex Lighta41a30782017-03-29 11:33:19 -07006700 if (m->GetMethodIndexDuringLinking() != i) {
6701 LOG(WARNING) << m->PrettyMethod()
6702 << " has an unexpected method index for its spot in the vtable for class"
6703 << klass->PrettyClass();
6704 }
Alex Lighte64300b2015-12-15 15:02:47 -08006705 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6706 auto is_same_method = [m] (const ArtMethod& meth) {
6707 return &meth == m;
6708 };
Alex Light3f980532017-03-17 15:10:32 -07006709 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6710 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6711 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6712 << klass->PrettyClass() << " or any of its superclasses!";
6713 }
Alex Lighte64300b2015-12-15 15:02:47 -08006714 }
6715}
6716
Alex Light1f3925d2016-09-07 12:04:20 -07006717// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6718// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08006719template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006720void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07006721 REQUIRES_SHARED(Locks::mutator_lock_) {
6722 StackHandleScope<1> hs(self);
6723 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6724 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006725
6726 // Observations:
6727 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
6728 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
6729 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
6730 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
6731 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
6732 // * The single-pass algorithm will trade memory for speed, but that is OK.
6733
6734 CHECK_GT(num_entries, 0);
6735
6736 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
6737 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
6738 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
6739 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6740 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
6741 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
6742 << m2->PrettyMethod() << " (0x" << std::hex
6743 << reinterpret_cast<uintptr_t>(m2) << ")";
6744 };
6745 struct BaseHashType {
6746 static size_t HashCombine(size_t seed, size_t val) {
6747 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
6748 }
6749 };
6750
6751 // Check assuming all entries come from the same dex file.
6752 {
6753 // Find the first interesting method and its dex file.
6754 int32_t start = 0;
6755 for (; start < num_entries; ++start) {
6756 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
6757 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
6758 // maybe).
6759 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6760 vtable_entry->GetAccessFlags())) {
6761 continue;
6762 }
6763 break;
6764 }
6765 if (start == num_entries) {
6766 return;
6767 }
6768 const DexFile* dex_file =
6769 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
6770 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
6771
6772 // Helper function to avoid logging if we have to run the cross-file checks.
6773 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
6774 // Use a map to store seen entries, as the storage space is too large for a bitvector.
6775 using PairType = std::pair<uint32_t, uint16_t>;
6776 struct PairHash : BaseHashType {
6777 size_t operator()(const PairType& key) const {
6778 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
6779 }
6780 };
Vladimir Marko782fb712020-12-23 12:47:31 +00006781 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006782 seen.reserve(2 * num_entries);
6783 bool need_slow_path = false;
6784 bool found_dup = false;
6785 for (int i = start; i < num_entries; ++i) {
6786 // Can use Unchecked here as the start loop already ensured that the arrays are correct
6787 // wrt/ kPointerSize.
6788 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
6789 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6790 vtable_entry->GetAccessFlags())) {
6791 continue;
6792 }
6793 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
6794 if (dex_file != m->GetDexFile()) {
6795 need_slow_path = true;
6796 break;
6797 }
6798 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
6799 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
6800 auto it = seen.find(pair);
6801 if (it != seen.end()) {
6802 found_dup = true;
6803 if (log_warn) {
6804 log_fn(it->second, i);
6805 }
6806 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00006807 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006808 }
6809 }
6810 return std::make_pair(need_slow_path, found_dup);
6811 };
6812 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
6813 if (!result.first) {
6814 if (result.second) {
6815 check_fn(/* log_warn= */ true);
6816 }
6817 return;
6818 }
6819 }
6820
6821 // Need to check across dex files.
6822 struct Entry {
6823 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00006824 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006825 const char* name = nullptr;
6826 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006827
Vladimir Marko782fb712020-12-23 12:47:31 +00006828 Entry() = default;
6829 Entry(const Entry& other) = default;
6830 Entry& operator=(const Entry& other) = default;
6831
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006832 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00006833 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
6834 // This call writes `name_len` and it is therefore necessary that the
6835 // initializer for `name_len` comes before it, otherwise the value
6836 // from the call would be overwritten by that initializer.
6837 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006838 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00006839 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
6840 if (name[name_len] != 0) {
6841 name_len += strlen(name + name_len);
6842 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006843 }
6844
6845 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00006846 return name_len == other.name_len &&
6847 memcmp(name, other.name, name_len) == 0 &&
6848 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006849 }
6850 };
6851 struct EntryHash {
6852 size_t operator()(const Entry& key) const {
6853 return key.cached_hash;
6854 }
6855 };
Vladimir Marko782fb712020-12-23 12:47:31 +00006856 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006857 for (int32_t i = 0; i < num_entries; ++i) {
6858 // Can use Unchecked here as the first loop already ensured that the arrays are correct
6859 // wrt/ kPointerSize.
6860 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
6861 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
6862 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07006863 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6864 vtable_entry->GetAccessFlags())) {
6865 continue;
6866 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006867 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
6868 const DexFile* dex_file = m->GetDexFile();
6869 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
6870
6871 Entry e(dex_file, mid);
6872
6873 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
6874 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
6875 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
6876 sig_hash);
6877
6878 auto it = map.find(e);
6879 if (it != map.end()) {
6880 log_fn(it->second, i);
6881 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00006882 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07006883 }
6884 }
6885}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006886
6887void CheckVTableHasNoDuplicates(Thread* self,
6888 Handle<mirror::Class> klass,
6889 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08006890 REQUIRES_SHARED(Locks::mutator_lock_) {
6891 switch (pointer_size) {
6892 case PointerSize::k64:
6893 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
6894 break;
6895 case PointerSize::k32:
6896 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
6897 break;
6898 }
6899}
Alex Light1f3925d2016-09-07 12:04:20 -07006900
Orion Hodson5880c772020-07-28 20:12:08 +01006901static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07006902 REQUIRES_SHARED(Locks::mutator_lock_) {
6903 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6904 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6905}
6906
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006907} // namespace
6908
Vladimir Markob91402f2021-12-21 15:55:06 +00006909template <PointerSize kPointerSize>
Vladimir Markobc893672021-11-10 15:25:46 +00006910class ClassLinker::LinkMethodsHelper {
Vladimir Marko921094a2017-01-12 18:37:06 +00006911 public:
Vladimir Markobc893672021-11-10 15:25:46 +00006912 LinkMethodsHelper(ClassLinker* class_linker,
6913 Handle<mirror::Class> klass,
6914 Thread* self,
6915 Runtime* runtime)
Vladimir Marko921094a2017-01-12 18:37:06 +00006916 : class_linker_(class_linker),
6917 klass_(klass),
Vladimir Marko921094a2017-01-12 18:37:06 +00006918 self_(self),
Vladimir Marko78f62d82022-01-10 16:25:19 +00006919 runtime_(runtime),
Vladimir Marko921094a2017-01-12 18:37:06 +00006920 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6921 allocator_(&stack_),
Vladimir Marko19366b82022-01-18 10:41:28 +00006922 copied_method_records_(copied_method_records_initial_buffer_,
6923 kCopiedMethodRecordInitialBufferSize,
6924 allocator_.Adapter()),
6925 num_new_copied_methods_(0u) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006926 }
6927
Vladimir Marko78f62d82022-01-10 16:25:19 +00006928 // Links the virtual and interface methods for the given class.
Vladimir Markobc893672021-11-10 15:25:46 +00006929 //
6930 // Arguments:
6931 // * self - The current thread.
6932 // * klass - class, whose vtable will be filled in.
Vladimir Marko78f62d82022-01-10 16:25:19 +00006933 // * interfaces - implemented interfaces for a proxy class, otherwise null.
6934 // * out_new_conflict - whether there is a new conflict compared to the superclass.
6935 // * out_imt - interface method table to fill.
6936 bool LinkMethods(
Vladimir Markobc893672021-11-10 15:25:46 +00006937 Thread* self,
6938 Handle<mirror::Class> klass,
Vladimir Marko78f62d82022-01-10 16:25:19 +00006939 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Vladimir Markobc893672021-11-10 15:25:46 +00006940 bool* out_new_conflict,
6941 ArtMethod** out_imt)
6942 REQUIRES_SHARED(Locks::mutator_lock_);
6943
6944 private:
Vladimir Marko0441d202022-02-18 13:55:15 +00006945 // Allocate a pointer array.
6946 static ObjPtr<mirror::PointerArray> AllocPointerArray(Thread* self, size_t length)
6947 REQUIRES_SHARED(Locks::mutator_lock_);
6948
6949 // Allocate method arrays for interfaces.
6950 bool AllocateIfTableMethodArrays(Thread* self,
6951 Handle<mirror::Class> klass,
6952 Handle<mirror::IfTable> iftable)
6953 REQUIRES_SHARED(Locks::mutator_lock_);
6954
Vladimir Marko8670e042021-12-21 17:55:48 +00006955 // Assign vtable indexes to declared virtual methods for a non-interface class other
6956 // than `java.lang.Object`. Returns the number of vtable entries on success, 0 on failure.
Vladimir Marko19366b82022-01-18 10:41:28 +00006957 // This function also assigns vtable indexes for interface methods in new interfaces
6958 // and records data for copied methods which shall be referenced by the vtable.
Vladimir Markobed84ef2022-01-21 13:57:14 +00006959 size_t AssignVTableIndexes(ObjPtr<mirror::Class> klass,
Vladimir Marko8670e042021-12-21 17:55:48 +00006960 ObjPtr<mirror::Class> super_class,
Vladimir Marko51718132022-02-07 16:31:08 +00006961 bool is_super_abstract,
Vladimir Marko19366b82022-01-18 10:41:28 +00006962 size_t num_virtual_methods,
6963 ObjPtr<mirror::IfTable> iftable)
6964 REQUIRES_SHARED(Locks::mutator_lock_);
6965
6966 bool FindCopiedMethodsForInterface(ObjPtr<mirror::Class> klass,
6967 size_t num_virtual_methods,
6968 ObjPtr<mirror::IfTable> iftable)
Vladimir Marko8670e042021-12-21 17:55:48 +00006969 REQUIRES_SHARED(Locks::mutator_lock_);
6970
Vladimir Marko78f62d82022-01-10 16:25:19 +00006971 bool LinkJavaLangObjectMethods(Thread* self, Handle<mirror::Class> klass)
Vladimir Markob91402f2021-12-21 15:55:06 +00006972 REQUIRES_SHARED(Locks::mutator_lock_) COLD_ATTR;
6973
Vladimir Marko19366b82022-01-18 10:41:28 +00006974 void ReallocMethods(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko0441d202022-02-18 13:55:15 +00006975 bool FinalizeIfTable(Handle<mirror::Class> klass,
6976 MutableHandle<mirror::IfTable> iftable,
6977 Handle<mirror::PointerArray> vtable,
Vladimir Marko51718132022-02-07 16:31:08 +00006978 bool is_klass_abstract,
6979 bool is_super_abstract,
Vladimir Marko19366b82022-01-18 10:41:28 +00006980 bool* out_new_conflict,
6981 ArtMethod** out_imt)
Vladimir Marko78f62d82022-01-10 16:25:19 +00006982 REQUIRES_SHARED(Locks::mutator_lock_);
6983
Vladimir Marko921094a2017-01-12 18:37:06 +00006984 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6985 LengthPrefixedArray<ArtMethod>* methods) {
Vladimir Marko19366b82022-01-18 10:41:28 +00006986 if (kIsDebugBuild && old_methods != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006987 CHECK(methods != nullptr);
6988 // Put some random garbage in old methods to help find stale pointers.
Vladimir Marko19366b82022-01-18 10:41:28 +00006989 if (methods != old_methods) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006990 // Need to make sure the GC is not running since it could be scanning the methods we are
6991 // about to overwrite.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00006992 ScopedThreadStateChange tsc(self_, ThreadState::kSuspended);
Vladimir Marko921094a2017-01-12 18:37:06 +00006993 gc::ScopedGCCriticalSection gcs(self_,
6994 gc::kGcCauseClassLinker,
6995 gc::kCollectorTypeClassLinker);
6996 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
Vladimir Markob91402f2021-12-21 15:55:06 +00006997 kMethodSize,
6998 kMethodAlignment);
Vladimir Marko921094a2017-01-12 18:37:06 +00006999 memset(old_methods, 0xFEu, old_size);
7000 }
7001 }
7002 }
7003
Vladimir Marko19366b82022-01-18 10:41:28 +00007004 NO_INLINE
7005 void LogNewVirtuals(LengthPrefixedArray<ArtMethod>* methods) const
7006 REQUIRES_SHARED(Locks::mutator_lock_) {
7007 ObjPtr<mirror::Class> klass = klass_.Get();
7008 size_t num_new_copied_methods = num_new_copied_methods_;
7009 size_t old_method_count = methods->size() - num_new_copied_methods;
7010 size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
7011 size_t num_miranda_methods = 0u;
7012 size_t num_overriding_default_methods = 0u;
7013 size_t num_default_methods = 0u;
7014 size_t num_overriding_default_conflict_methods = 0u;
7015 size_t num_default_conflict_methods = 0u;
7016 for (size_t i = 0; i != num_new_copied_methods; ++i) {
7017 ArtMethod& m = methods->At(old_method_count + i, kMethodSize, kMethodAlignment);
7018 if (m.IsDefault()) {
7019 if (m.GetMethodIndexDuringLinking() < super_vtable_length) {
7020 ++num_overriding_default_methods;
7021 } else {
7022 ++num_default_methods;
7023 }
7024 } else if (m.IsDefaultConflicting()) {
7025 if (m.GetMethodIndexDuringLinking() < super_vtable_length) {
7026 ++num_overriding_default_conflict_methods;
7027 } else {
7028 ++num_default_conflict_methods;
7029 }
7030 } else {
7031 DCHECK(m.IsMiranda());
7032 ++num_miranda_methods;
7033 }
Vladimir Marko5cfb7bb2022-01-28 11:12:17 +00007034 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007035 VLOG(class_linker) << klass->PrettyClass() << ": miranda_methods=" << num_miranda_methods
7036 << " default_methods=" << num_default_methods
7037 << " overriding_default_methods=" << num_overriding_default_methods
7038 << " default_conflict_methods=" << num_default_conflict_methods
Vladimir Marko921094a2017-01-12 18:37:06 +00007039 << " overriding_default_conflict_methods="
Vladimir Marko19366b82022-01-18 10:41:28 +00007040 << num_overriding_default_conflict_methods;
Vladimir Marko921094a2017-01-12 18:37:06 +00007041 }
7042
Vladimir Marko8670e042021-12-21 17:55:48 +00007043 class MethodIndexEmptyFn {
7044 public:
7045 void MakeEmpty(uint32_t& item) const {
7046 item = dex::kDexNoIndex;
7047 }
7048 bool IsEmpty(const uint32_t& item) const {
7049 return item == dex::kDexNoIndex;
7050 }
7051 };
7052
Vladimir Marko7ddae992022-01-18 14:27:20 +00007053 class VTableIndexCheckerDebug {
7054 protected:
7055 explicit VTableIndexCheckerDebug(size_t vtable_length)
7056 : vtable_length_(vtable_length) {}
Vladimir Marko8670e042021-12-21 17:55:48 +00007057
Vladimir Marko7ddae992022-01-18 14:27:20 +00007058 void CheckIndex(uint32_t index) const {
7059 CHECK_LT(index, vtable_length_);
Vladimir Marko8670e042021-12-21 17:55:48 +00007060 }
7061
7062 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007063 uint32_t vtable_length_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007064 };
7065
Vladimir Marko7ddae992022-01-18 14:27:20 +00007066 class VTableIndexCheckerRelease {
7067 protected:
7068 explicit VTableIndexCheckerRelease(size_t vtable_length ATTRIBUTE_UNUSED) {}
7069 void CheckIndex(uint32_t index ATTRIBUTE_UNUSED) const {}
7070 };
Vladimir Marko8670e042021-12-21 17:55:48 +00007071
Vladimir Marko7ddae992022-01-18 14:27:20 +00007072 using VTableIndexChecker =
7073 std::conditional_t<kIsDebugBuild, VTableIndexCheckerDebug, VTableIndexCheckerRelease>;
7074
7075 class VTableAccessor : private VTableIndexChecker {
7076 public:
7077 VTableAccessor(uint8_t* raw_vtable, size_t vtable_length)
7078 REQUIRES_SHARED(Locks::mutator_lock_)
7079 : VTableIndexChecker(vtable_length),
7080 raw_vtable_(raw_vtable) {}
Vladimir Marko8670e042021-12-21 17:55:48 +00007081
7082 ArtMethod* GetVTableEntry(uint32_t index) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko7ddae992022-01-18 14:27:20 +00007083 this->CheckIndex(index);
7084 uint8_t* entry = raw_vtable_ + static_cast<size_t>(kPointerSize) * index;
7085 if (kPointerSize == PointerSize::k64) {
7086 return reinterpret_cast64<ArtMethod*>(*reinterpret_cast<uint64_t*>(entry));
7087 } else {
7088 return reinterpret_cast32<ArtMethod*>(*reinterpret_cast<uint32_t*>(entry));
7089 }
Vladimir Marko8670e042021-12-21 17:55:48 +00007090 }
7091
7092 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007093 uint8_t* raw_vtable_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007094 };
7095
Vladimir Marko8670e042021-12-21 17:55:48 +00007096 class VTableSignatureHash {
7097 public:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007098 explicit VTableSignatureHash(VTableAccessor accessor)
Vladimir Marko8670e042021-12-21 17:55:48 +00007099 REQUIRES_SHARED(Locks::mutator_lock_)
7100 : accessor_(accessor) {}
7101
7102 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7103 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7104 return ComputeMethodHash(method);
7105 }
7106
7107 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7108 size_t operator()(uint32_t index) const NO_THREAD_SAFETY_ANALYSIS {
7109 return ComputeMethodHash(accessor_.GetVTableEntry(index));
7110 }
7111
7112 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007113 VTableAccessor accessor_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007114 };
7115
Vladimir Marko8670e042021-12-21 17:55:48 +00007116 class VTableSignatureEqual {
7117 public:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007118 explicit VTableSignatureEqual(VTableAccessor accessor)
Vladimir Marko8670e042021-12-21 17:55:48 +00007119 REQUIRES_SHARED(Locks::mutator_lock_)
7120 : accessor_(accessor) {}
7121
7122 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7123 bool operator()(uint32_t lhs_index, ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
Vladimir Markobed84ef2022-01-21 13:57:14 +00007124 return MethodSignatureEquals(accessor_.GetVTableEntry(lhs_index), rhs);
Vladimir Marko8670e042021-12-21 17:55:48 +00007125 }
7126
7127 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7128 bool operator()(uint32_t lhs_index, uint32_t rhs_index) const NO_THREAD_SAFETY_ANALYSIS {
7129 return (*this)(lhs_index, accessor_.GetVTableEntry(rhs_index));
7130 }
7131
7132 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007133 VTableAccessor accessor_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007134 };
7135
Vladimir Marko7ddae992022-01-18 14:27:20 +00007136 using VTableSignatureSet =
7137 ScopedArenaHashSet<uint32_t, MethodIndexEmptyFn, VTableSignatureHash, VTableSignatureEqual>;
Vladimir Marko8670e042021-12-21 17:55:48 +00007138
Vladimir Marko19366b82022-01-18 10:41:28 +00007139 class DeclaredVirtualSignatureHash {
7140 public:
7141 explicit DeclaredVirtualSignatureHash(ObjPtr<mirror::Class> klass)
7142 REQUIRES_SHARED(Locks::mutator_lock_)
7143 : klass_(klass) {}
7144
7145 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7146 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7147 return ComputeMethodHash(method);
7148 }
7149
7150 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7151 size_t operator()(uint32_t index) const NO_THREAD_SAFETY_ANALYSIS {
7152 DCHECK_LT(index, klass_->NumDeclaredVirtualMethods());
7153 ArtMethod* method = klass_->GetVirtualMethodDuringLinking(index, kPointerSize);
7154 return ComputeMethodHash(method->GetInterfaceMethodIfProxy(kPointerSize));
7155 }
7156
7157 private:
7158 ObjPtr<mirror::Class> klass_;
7159 };
7160
7161 class DeclaredVirtualSignatureEqual {
7162 public:
7163 explicit DeclaredVirtualSignatureEqual(ObjPtr<mirror::Class> klass)
7164 REQUIRES_SHARED(Locks::mutator_lock_)
7165 : klass_(klass) {}
7166
7167 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7168 bool operator()(uint32_t lhs_index, ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
7169 DCHECK_LT(lhs_index, klass_->NumDeclaredVirtualMethods());
7170 ArtMethod* lhs = klass_->GetVirtualMethodDuringLinking(lhs_index, kPointerSize);
7171 return MethodSignatureEquals(lhs->GetInterfaceMethodIfProxy(kPointerSize), rhs);
7172 }
7173
7174 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7175 bool operator()(uint32_t lhs_index, uint32_t rhs_index) const NO_THREAD_SAFETY_ANALYSIS {
7176 DCHECK_LT(lhs_index, klass_->NumDeclaredVirtualMethods());
7177 DCHECK_LT(rhs_index, klass_->NumDeclaredVirtualMethods());
7178 return lhs_index == rhs_index;
7179 }
7180
7181 private:
7182 ObjPtr<mirror::Class> klass_;
7183 };
7184
7185 using DeclaredVirtualSignatureSet = ScopedArenaHashSet<uint32_t,
7186 MethodIndexEmptyFn,
7187 DeclaredVirtualSignatureHash,
7188 DeclaredVirtualSignatureEqual>;
7189
7190 // Helper class to keep records for determining the correct copied method to create.
7191 class CopiedMethodRecord {
7192 public:
7193 enum class State : uint32_t {
7194 // Note: The `*Single` values are used when we know that there is only one interface
7195 // method with the given signature that's not masked; that method is the main method.
7196 // We use this knowledge for faster masking check, otherwise we need to search for
7197 // a masking method through methods of all interfaces that could potentially mask it.
7198 kAbstractSingle,
7199 kDefaultSingle,
7200 kAbstract,
7201 kDefault,
7202 kDefaultConflict,
7203 kUseSuperMethod,
7204 };
7205
7206 CopiedMethodRecord()
7207 : main_method_(nullptr),
7208 method_index_(0u),
7209 state_(State::kAbstractSingle) {}
7210
7211 CopiedMethodRecord(ArtMethod* main_method, size_t vtable_index)
7212 : main_method_(main_method),
7213 method_index_(vtable_index),
7214 state_(State::kAbstractSingle) {}
7215
7216 // Set main method. The new main method must be more specific implementation.
7217 void SetMainMethod(ArtMethod* main_method) {
7218 DCHECK(main_method_ != nullptr);
7219 main_method_ = main_method;
7220 }
7221
7222 // The main method is the first encountered default method if any,
7223 // otherwise the first encountered abstract method.
7224 ArtMethod* GetMainMethod() const {
7225 return main_method_;
7226 }
7227
7228 void SetMethodIndex(size_t method_index) {
7229 DCHECK_NE(method_index, dex::kDexNoIndex);
7230 method_index_ = method_index;
7231 }
7232
7233 size_t GetMethodIndex() const {
7234 DCHECK_NE(method_index_, dex::kDexNoIndex);
7235 return method_index_;
7236 }
7237
7238 void SetState(State state) {
7239 state_ = state;
7240 }
7241
7242 State GetState() const {
7243 return state_;
7244 }
7245
7246 ALWAYS_INLINE
7247 void UpdateStateForInterface(ObjPtr<mirror::Class> iface,
7248 ArtMethod* interface_method,
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 DCHECK(iface == interface_method->GetDeclaringClass());
7256 DCHECK(iface == iftable->GetInterface(index));
7257 DCHECK(interface_method->IsDefault());
7258 if (GetState() != State::kDefaultConflict) {
7259 DCHECK(GetState() == State::kDefault);
7260 // We do not record all overriding methods, so we need to walk over all
7261 // interfaces that could mask the `interface_method`.
7262 if (ContainsOverridingMethodOf(iftable, index + 1, ifcount, iface, interface_method)) {
7263 return; // Found an overriding method that masks `interface_method`.
7264 }
7265 // We have a new default method that's not masked by any other method.
7266 SetState(State::kDefaultConflict);
7267 }
7268 }
7269
7270 ALWAYS_INLINE
7271 void UpdateState(ObjPtr<mirror::Class> iface,
7272 ArtMethod* interface_method,
7273 size_t vtable_index,
7274 ObjPtr<mirror::IfTable> iftable,
7275 size_t ifcount,
7276 size_t index)
7277 REQUIRES_SHARED(Locks::mutator_lock_) {
7278 DCHECK_EQ(ifcount, iftable->Count());
7279 DCHECK_LT(index, ifcount);
7280 if (kIsDebugBuild) {
7281 if (interface_method->IsCopied()) {
7282 // Called from `FinalizeState()` for a default method from superclass.
7283 // The `index` points to the last interface inherited from the superclass
7284 // as we need to search only the new interfaces for masking methods.
7285 DCHECK(interface_method->IsDefault());
7286 } else {
7287 DCHECK(iface == interface_method->GetDeclaringClass());
7288 DCHECK(iface == iftable->GetInterface(index));
7289 }
7290 }
7291 DCHECK_EQ(vtable_index, method_index_);
7292 auto slow_is_masked = [=]() REQUIRES_SHARED(Locks::mutator_lock_) {
7293 return ContainsImplementingMethod(iftable, index + 1, ifcount, iface, vtable_index);
7294 };
7295 UpdateStateImpl(iface, interface_method, slow_is_masked);
7296 }
7297
7298 ALWAYS_INLINE
7299 void FinalizeState(ArtMethod* super_method,
7300 size_t vtable_index,
7301 ObjPtr<mirror::IfTable> iftable,
7302 size_t ifcount,
7303 ObjPtr<mirror::IfTable> super_iftable,
7304 size_t super_ifcount)
7305 REQUIRES_SHARED(Locks::mutator_lock_) {
7306 DCHECK(super_method->IsCopied());
7307 DCHECK_EQ(vtable_index, method_index_);
7308 DCHECK_EQ(vtable_index, super_method->GetMethodIndex());
7309 DCHECK_NE(super_ifcount, 0u);
7310 if (super_method->IsDefault()) {
7311 if (UNLIKELY(super_method->IsDefaultConflicting())) {
7312 // Some of the default methods that contributed to the conflict in the superclass
7313 // may be masked by new interfaces. Walk over all the interfaces and update state
7314 // as long as the current state is not `kDefaultConflict`.
7315 size_t i = super_ifcount;
7316 while (GetState() != State::kDefaultConflict && i != 0u) {
7317 --i;
7318 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
7319 DCHECK(iface == super_iftable->GetInterface(i));
7320 auto [found, index] =
7321 MethodArrayContains(super_iftable->GetMethodArrayOrNull(i), super_method);
7322 if (found) {
7323 ArtMethod* interface_method = iface->GetVirtualMethod(index, kPointerSize);
7324 auto slow_is_masked = [=]() REQUIRES_SHARED(Locks::mutator_lock_) {
7325 // Note: The `iftable` has method arrays in range [super_ifcount, ifcount) filled
7326 // with vtable indexes but the range [0, super_ifcount) is empty, so we need to
7327 // use the `super_iftable` filled with implementation methods for that range.
7328 return ContainsImplementingMethod(
7329 super_iftable, i + 1u, super_ifcount, iface, super_method) ||
7330 ContainsImplementingMethod(
7331 iftable, super_ifcount, ifcount, iface, vtable_index);
7332 };
7333 UpdateStateImpl(iface, interface_method, slow_is_masked);
7334 }
7335 }
7336 if (GetState() == State::kDefaultConflict) {
7337 SetState(State::kUseSuperMethod);
7338 }
7339 } else {
7340 // There was exactly one default method in superclass interfaces that was
7341 // not masked by subinterfaces. Use `UpdateState()` to process it and pass
7342 // `super_ifcount - 1` as index for checking if it's been masked by new interfaces.
7343 ObjPtr<mirror::Class> iface = super_method->GetDeclaringClass();
7344 UpdateState(
7345 iface, super_method, vtable_index, iftable, ifcount, /*index=*/ super_ifcount - 1u);
7346 if (GetMainMethod() == super_method) {
7347 DCHECK(GetState() == State::kDefault) << enum_cast<uint32_t>(GetState());
7348 SetState(State::kUseSuperMethod);
7349 }
7350 }
7351 } else {
7352 DCHECK(super_method->IsMiranda());
7353 // Any default methods with this signature in superclass interfaces have been
7354 // masked by subinterfaces. Check if we can reuse the miranda method.
7355 if (GetState() == State::kAbstractSingle || GetState() == State::kAbstract) {
7356 SetState(State::kUseSuperMethod);
7357 }
7358 }
7359 }
7360
7361 private:
7362 template <typename Predicate>
7363 ALWAYS_INLINE
7364 void UpdateStateImpl(ObjPtr<mirror::Class> iface,
7365 ArtMethod* interface_method,
7366 Predicate&& slow_is_masked)
7367 REQUIRES_SHARED(Locks::mutator_lock_) {
7368 bool have_default = false;
7369 switch (GetState()) {
7370 case State::kDefaultSingle:
7371 have_default = true;
7372 FALLTHROUGH_INTENDED;
7373 case State::kAbstractSingle:
7374 if (GetMainMethod()->GetDeclaringClass()->Implements(iface)) {
7375 return; // The main method masks the `interface_method`.
7376 }
7377 if (!interface_method->IsDefault()) {
7378 SetState(have_default ? State::kDefault : State::kAbstract);
7379 return;
7380 }
7381 break;
7382 case State::kDefault:
7383 have_default = true;
7384 FALLTHROUGH_INTENDED;
7385 case State::kAbstract:
7386 if (!interface_method->IsDefault()) {
7387 return; // Keep the same state. We do not need to check for masking.
7388 }
7389 // We do not record all overriding methods, so we need to walk over all
7390 // interfaces that could mask the `interface_method`. The provided
7391 // predicate `slow_is_masked()` does that.
7392 if (slow_is_masked()) {
7393 return; // Found an overriding method that masks `interface_method`.
7394 }
7395 break;
7396 case State::kDefaultConflict:
7397 return; // The state cannot change anymore.
7398 default:
7399 LOG(FATAL) << "Unexpected state: " << enum_cast<uint32_t>(GetState());
7400 UNREACHABLE();
7401 }
7402 // We have a new default method that's not masked by any other method.
7403 DCHECK(interface_method->IsDefault());
7404 if (have_default) {
7405 SetState(State::kDefaultConflict);
7406 } else {
7407 SetMainMethod(interface_method);
7408 SetState(State::kDefault);
7409 }
7410 }
7411
7412 // Determine if the given `iftable` contains in the given range a subinterface of `iface`
7413 // that declares a method with the same name and signature as 'interface_method'.
7414 //
7415 // Arguments
7416 // - iftable: The iftable we are searching for an overriding method.
7417 // - begin: The start of the range to search.
7418 // - end: The end of the range to search.
7419 // - iface: The interface we are checking to see if anything overrides.
7420 // - interface_method:
7421 // The interface method providing a name and signature we're searching for.
7422 //
7423 // Returns whether an overriding method was found in any subinterface of `iface`.
7424 static bool ContainsOverridingMethodOf(ObjPtr<mirror::IfTable> iftable,
7425 size_t begin,
7426 size_t end,
7427 ObjPtr<mirror::Class> iface,
7428 ArtMethod* interface_method)
7429 REQUIRES_SHARED(Locks::mutator_lock_) {
7430 for (size_t i = begin; i != end; ++i) {
7431 ObjPtr<mirror::Class> current_iface = iftable->GetInterface(i);
7432 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(kPointerSize)) {
7433 if (MethodSignatureEquals(&current_method, interface_method)) {
7434 // Check if the i'th interface is a subtype of this one.
7435 if (current_iface->Implements(iface)) {
7436 return true;
7437 }
7438 break;
7439 }
7440 }
7441 }
7442 return false;
7443 }
7444
7445 // Determine if the given `iftable` contains in the given range a subinterface of `iface`
7446 // that declares a method implemented by 'target'. This is an optimized version of
7447 // `ContainsOverridingMethodOf()` that searches implementation method arrays instead
7448 // of comparing signatures for declared interface methods.
7449 //
7450 // Arguments
7451 // - iftable: The iftable we are searching for an overriding method.
7452 // - begin: The start of the range to search.
7453 // - end: The end of the range to search.
7454 // - iface: The interface we are checking to see if anything overrides.
7455 // - target: The implementation method we're searching for.
7456 // Note that the new `iftable` is filled with vtable indexes for new interfaces,
7457 // so this needs to be the vtable index if we're searching that range.
7458 //
7459 // Returns whether the `target` was found in a method array for any subinterface of `iface`.
7460 template <typename TargetType>
7461 static bool ContainsImplementingMethod(ObjPtr<mirror::IfTable> iftable,
7462 size_t begin,
7463 size_t end,
7464 ObjPtr<mirror::Class> iface,
7465 TargetType target)
7466 REQUIRES_SHARED(Locks::mutator_lock_) {
7467 for (size_t i = begin; i != end; ++i) {
7468 if (MethodArrayContains(iftable->GetMethodArrayOrNull(i), target).first &&
7469 iftable->GetInterface(i)->Implements(iface)) {
7470 return true;
7471 }
7472 }
7473 return false;
7474 }
7475
7476 template <typename TargetType>
7477 static std::pair<bool, size_t> MethodArrayContains(ObjPtr<mirror::PointerArray> method_array,
7478 TargetType target)
7479 REQUIRES_SHARED(Locks::mutator_lock_) {
7480 size_t num_methods = (method_array != nullptr) ? method_array->GetLength() : 0u;
7481 for (size_t j = 0; j != num_methods; ++j) {
7482 if (method_array->GetElementPtrSize<TargetType, kPointerSize>(j) == target) {
7483 return {true, j};
7484 }
7485 }
7486 return {false, 0};
7487 }
7488
7489 ArtMethod* main_method_;
7490 uint32_t method_index_;
7491 State state_;
7492 };
7493
7494 class CopiedMethodRecordEmptyFn {
7495 public:
7496 void MakeEmpty(CopiedMethodRecord& item) const {
7497 item = CopiedMethodRecord();
7498 }
7499 bool IsEmpty(const CopiedMethodRecord& item) const {
7500 return item.GetMainMethod() == nullptr;
7501 }
7502 };
7503
7504 class CopiedMethodRecordHash {
7505 public:
7506 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7507 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7508 DCHECK(method != nullptr);
7509 return ComputeMethodHash(method);
7510 }
7511
7512 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7513 size_t operator()(const CopiedMethodRecord& record) const NO_THREAD_SAFETY_ANALYSIS {
7514 return (*this)(record.GetMainMethod());
7515 }
7516 };
7517
7518 class CopiedMethodRecordEqual {
7519 public:
7520 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7521 bool operator()(const CopiedMethodRecord& lhs_record,
7522 ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
7523 ArtMethod* lhs = lhs_record.GetMainMethod();
7524 DCHECK(lhs != nullptr);
7525 DCHECK(rhs != nullptr);
7526 return MethodSignatureEquals(lhs, rhs);
7527 }
7528
7529 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7530 bool operator()(const CopiedMethodRecord& lhs_record,
7531 const CopiedMethodRecord& rhs_record) const NO_THREAD_SAFETY_ANALYSIS {
7532 return (*this)(lhs_record, rhs_record.GetMainMethod());
7533 }
7534 };
7535
7536 using CopiedMethodRecordSet = ScopedArenaHashSet<CopiedMethodRecord,
7537 CopiedMethodRecordEmptyFn,
7538 CopiedMethodRecordHash,
7539 CopiedMethodRecordEqual>;
7540
Vladimir Markob91402f2021-12-21 15:55:06 +00007541 static constexpr size_t kMethodAlignment = ArtMethod::Alignment(kPointerSize);
7542 static constexpr size_t kMethodSize = ArtMethod::Size(kPointerSize);
7543
Vladimir Marko921094a2017-01-12 18:37:06 +00007544 ClassLinker* class_linker_;
7545 Handle<mirror::Class> klass_;
Vladimir Marko921094a2017-01-12 18:37:06 +00007546 Thread* const self_;
Vladimir Marko78f62d82022-01-10 16:25:19 +00007547 Runtime* const runtime_;
Vladimir Marko921094a2017-01-12 18:37:06 +00007548
7549 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7550 // the virtual methods array.
7551 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7552 // during cross compilation.
7553 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7554 ArenaStack stack_;
7555 ScopedArenaAllocator allocator_;
7556
Vladimir Markod5d11d92021-02-02 16:24:25 +00007557 // If there are multiple methods with the same signature in the superclass vtable
7558 // (which can happen with a new virtual method having the same signature as an
7559 // inaccessible package-private method from another package in the superclass),
7560 // we keep singly-linked lists in this single array that maps vtable index to the
7561 // next vtable index in the list, `dex::kDexNoIndex` denotes the end of a list.
7562 ArrayRef<uint32_t> same_signature_vtable_lists_;
7563
Vladimir Marko19366b82022-01-18 10:41:28 +00007564 // Avoid large allocation for a few copied method records.
Vladimir Markobc893672021-11-10 15:25:46 +00007565 // Keep the initial buffer on the stack to avoid arena allocations
7566 // if there are no special cases (the first arena allocation is costly).
Vladimir Marko19366b82022-01-18 10:41:28 +00007567 static constexpr size_t kCopiedMethodRecordInitialBufferSize = 16u;
7568 CopiedMethodRecord copied_method_records_initial_buffer_[kCopiedMethodRecordInitialBufferSize];
7569 CopiedMethodRecordSet copied_method_records_;
7570 size_t num_new_copied_methods_;
Vladimir Marko921094a2017-01-12 18:37:06 +00007571};
7572
Vladimir Markob91402f2021-12-21 15:55:06 +00007573template <PointerSize kPointerSize>
Vladimir Marko19366b82022-01-18 10:41:28 +00007574NO_INLINE
7575void ClassLinker::LinkMethodsHelper<kPointerSize>::ReallocMethods(ObjPtr<mirror::Class> klass) {
7576 // There should be no thread suspension in this function,
7577 // native allocations do not cause thread suspension.
7578 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Marko921094a2017-01-12 18:37:06 +00007579
Vladimir Marko19366b82022-01-18 10:41:28 +00007580 size_t num_new_copied_methods = num_new_copied_methods_;
7581 DCHECK_NE(num_new_copied_methods, 0u);
7582 const size_t old_method_count = klass->NumMethods();
7583 const size_t new_method_count = old_method_count + num_new_copied_methods;
Vladimir Marko921094a2017-01-12 18:37:06 +00007584
7585 // Attempt to realloc to save RAM if possible.
Vladimir Marko19366b82022-01-18 10:41:28 +00007586 LengthPrefixedArray<ArtMethod>* old_methods = klass->GetMethodsPtr();
Vladimir Marko921094a2017-01-12 18:37:06 +00007587 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7588 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7589 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7590 // CopyFrom has internal read barriers.
7591 //
7592 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7593 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
Vladimir Markob91402f2021-12-21 15:55:06 +00007594 kMethodSize,
7595 kMethodAlignment);
Vladimir Marko921094a2017-01-12 18:37:06 +00007596 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
Vladimir Markob91402f2021-12-21 15:55:06 +00007597 kMethodSize,
7598 kMethodAlignment);
Vladimir Marko921094a2017-01-12 18:37:06 +00007599 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7600 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Vladimir Marko19366b82022-01-18 10:41:28 +00007601 class_linker_->GetAllocatorForClassLoader(klass->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007602 self_, old_methods, old_methods_ptr_size, new_size));
7603 CHECK(methods != nullptr); // Native allocation failure aborts.
7604
Vladimir Marko921094a2017-01-12 18:37:06 +00007605 if (methods != old_methods) {
Vladimir Markob91402f2021-12-21 15:55:06 +00007606 StrideIterator<ArtMethod> out = methods->begin(kMethodSize, kMethodAlignment);
Vladimir Marko19366b82022-01-18 10:41:28 +00007607 // Copy over the old methods. The `ArtMethod::CopyFrom()` is only necessary to not miss
7608 // read barriers since `LinearAlloc::Realloc()` won't do read barriers when it copies.
7609 for (auto& m : klass->GetMethods(kPointerSize)) {
Vladimir Markob91402f2021-12-21 15:55:06 +00007610 out->CopyFrom(&m, kPointerSize);
Vladimir Marko921094a2017-01-12 18:37:06 +00007611 ++out;
7612 }
7613 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007614
7615 // Collect and sort copied method records by the vtable index. This places overriding
7616 // copied methods first, sorted by the vtable index already assigned in the superclass,
7617 // followed by copied methods with new signatures in the order in which we encountered
7618 // them when going over virtual methods of new interfaces.
7619 // This order is deterministic but implementation-defined.
7620 //
7621 // Avoid arena allocation for a few records (the first arena allocation is costly).
7622 constexpr size_t kSortedRecordsBufferSize = 16;
7623 CopiedMethodRecord* sorted_records_buffer[kSortedRecordsBufferSize];
7624 CopiedMethodRecord** sorted_records = (num_new_copied_methods <= kSortedRecordsBufferSize)
7625 ? sorted_records_buffer
7626 : allocator_.AllocArray<CopiedMethodRecord*>(num_new_copied_methods);
7627 size_t filled_sorted_records = 0u;
7628 for (CopiedMethodRecord& record : copied_method_records_) {
7629 if (record.GetState() != CopiedMethodRecord::State::kUseSuperMethod) {
7630 DCHECK_LT(filled_sorted_records, num_new_copied_methods);
7631 sorted_records[filled_sorted_records] = &record;
7632 ++filled_sorted_records;
Vladimir Marko921094a2017-01-12 18:37:06 +00007633 }
7634 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007635 DCHECK_EQ(filled_sorted_records, num_new_copied_methods);
7636 std::sort(sorted_records,
7637 sorted_records + num_new_copied_methods,
7638 [](const CopiedMethodRecord* lhs, const CopiedMethodRecord* rhs) {
7639 return lhs->GetMethodIndex() < rhs->GetMethodIndex();
7640 });
7641
7642 if (klass->IsInterface()) {
7643 // Some records may have been pruned. Update method indexes in collected records.
7644 size_t interface_method_index = klass->NumDeclaredVirtualMethods();
7645 for (size_t i = 0; i != num_new_copied_methods; ++i) {
7646 CopiedMethodRecord* record = sorted_records[i];
7647 DCHECK_LE(interface_method_index, record->GetMethodIndex());
7648 record->SetMethodIndex(interface_method_index);
7649 ++interface_method_index;
Vladimir Marko921094a2017-01-12 18:37:06 +00007650 }
7651 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007652
7653 // Add copied methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007654 methods->SetSize(new_method_count);
Vladimir Marko19366b82022-01-18 10:41:28 +00007655 for (size_t i = 0; i != num_new_copied_methods; ++i) {
7656 const CopiedMethodRecord* record = sorted_records[i];
7657 ArtMethod* interface_method = record->GetMainMethod();
7658 DCHECK(!interface_method->IsCopied());
7659 ArtMethod& new_method = methods->At(old_method_count + i, kMethodSize, kMethodAlignment);
7660 new_method.CopyFrom(interface_method, kPointerSize);
7661 new_method.SetMethodIndex(dchecked_integral_cast<uint16_t>(record->GetMethodIndex()));
7662 switch (record->GetState()) {
7663 case CopiedMethodRecord::State::kAbstractSingle:
7664 case CopiedMethodRecord::State::kAbstract: {
7665 DCHECK(!klass->IsInterface()); // We do not create miranda methods for interfaces.
7666 uint32_t access_flags = new_method.GetAccessFlags();
7667 DCHECK_EQ(access_flags & (kAccAbstract | kAccIntrinsic | kAccDefault), kAccAbstract)
7668 << "Miranda method should be abstract but not intrinsic or default!";
7669 new_method.SetAccessFlags(access_flags | kAccCopied);
7670 break;
7671 }
7672 case CopiedMethodRecord::State::kDefaultSingle:
7673 case CopiedMethodRecord::State::kDefault: {
7674 DCHECK(!klass->IsInterface()); // We do not copy default methods for interfaces.
7675 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7676 // verified yet it shouldn't have methods that are skipping access checks.
7677 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7678 // methods are skip_access_checks.
7679 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
7680 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7681 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7682 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7683 break;
7684 }
7685 case CopiedMethodRecord::State::kDefaultConflict: {
7686 // This is a type of default method (there are default method impls, just a conflict)
7687 // so mark this as a default. We use the `kAccAbstract` flag to distinguish it from
7688 // invokable copied default method without using a separate access flag but the default
7689 // conflicting method is technically not abstract and ArtMethod::IsAbstract() shall
7690 // return false. Also clear the kAccSkipAccessChecks bit since this class hasn't been
7691 // verified yet it shouldn't have methods that are skipping access checks. Also clear
7692 // potential kAccSingleImplementation to avoid CHA trying to inline the default method.
7693 uint32_t access_flags = new_method.GetAccessFlags();
7694 DCHECK_EQ(access_flags & (kAccNative | kAccIntrinsic), 0u);
7695 constexpr uint32_t kSetFlags = kAccDefault | kAccAbstract | kAccCopied;
7696 constexpr uint32_t kMaskFlags = ~(kAccSkipAccessChecks | kAccSingleImplementation);
7697 new_method.SetAccessFlags((access_flags | kSetFlags) & kMaskFlags);
7698 DCHECK(new_method.IsDefaultConflicting());
7699 DCHECK(!new_method.IsAbstract());
7700 // The actual method might or might not be marked abstract since we just copied it from
7701 // a (possibly default) interface method. We need to set its entry point to be the bridge
7702 // so that the compiler will not invoke the implementation of whatever method we copied
7703 // from.
7704 EnsureThrowsInvocationError(class_linker_, &new_method);
7705 break;
7706 }
7707 default:
7708 LOG(FATAL) << "Unexpected state: " << enum_cast<uint32_t>(record->GetState());
7709 UNREACHABLE();
7710 }
7711 }
7712
7713 if (VLOG_IS_ON(class_linker)) {
7714 LogNewVirtuals(methods);
7715 }
7716
7717 class_linker_->UpdateClassMethods(klass, methods);
Vladimir Marko921094a2017-01-12 18:37:06 +00007718}
7719
Vladimir Markob91402f2021-12-21 15:55:06 +00007720template <PointerSize kPointerSize>
Vladimir Marko0441d202022-02-18 13:55:15 +00007721bool ClassLinker::LinkMethodsHelper<kPointerSize>::FinalizeIfTable(
7722 Handle<mirror::Class> klass,
7723 MutableHandle<mirror::IfTable> iftable,
7724 Handle<mirror::PointerArray> vtable,
Vladimir Marko51718132022-02-07 16:31:08 +00007725 bool is_klass_abstract,
7726 bool is_super_abstract,
Vladimir Marko19366b82022-01-18 10:41:28 +00007727 bool* out_new_conflict,
7728 ArtMethod** out_imt) {
Vladimir Marko19366b82022-01-18 10:41:28 +00007729 size_t ifcount = iftable->Count();
Vladimir Marko0441d202022-02-18 13:55:15 +00007730 // We do not need a read barrier here as the length is constant, both from-space and
7731 // to-space `IfTable`s shall yield the same result. See also `Class::GetIfTableCount()`.
7732 size_t super_ifcount =
7733 klass->GetSuperClass<kDefaultVerifyFlags, kWithoutReadBarrier>()->GetIfTableCount();
Vladimir Marko921094a2017-01-12 18:37:06 +00007734
Vladimir Marko0441d202022-02-18 13:55:15 +00007735 ClassLinker* class_linker = nullptr;
Vladimir Marko51718132022-02-07 16:31:08 +00007736 ArtMethod* unimplemented_method = nullptr;
7737 ArtMethod* imt_conflict_method = nullptr;
7738 uintptr_t imt_methods_begin = 0u;
7739 size_t imt_methods_size = 0u;
7740 DCHECK_EQ(klass->ShouldHaveImt(), !is_klass_abstract);
7741 DCHECK_EQ(klass->GetSuperClass()->ShouldHaveImt(), !is_super_abstract);
7742 if (!is_klass_abstract) {
Vladimir Marko0441d202022-02-18 13:55:15 +00007743 class_linker = class_linker_;
Vladimir Marko51718132022-02-07 16:31:08 +00007744 unimplemented_method = runtime_->GetImtUnimplementedMethod();
7745 imt_conflict_method = runtime_->GetImtConflictMethod();
7746 if (is_super_abstract) {
7747 // There was no IMT in superclass to copy to `out_imt[]`, so we need
7748 // to fill it with all implementation methods from superclass.
7749 DCHECK_EQ(imt_methods_begin, 0u);
7750 imt_methods_size = std::numeric_limits<size_t>::max(); // No method at the last byte.
7751 } else {
7752 // If the superclass has IMT, we have already copied it to `out_imt[]` and
7753 // we do not need to call `SetIMTRef()` for interfaces from superclass when
7754 // the implementation method is already in the superclass, only for new methods.
7755 // For simplicity, use the entire method array including direct methods.
7756 LengthPrefixedArray<ArtMethod>* const new_methods = klass->GetMethodsPtr();
7757 if (new_methods != nullptr) {
7758 DCHECK_NE(new_methods->size(), 0u);
7759 imt_methods_begin = reinterpret_cast<uintptr_t>(&new_methods->At(0));
7760 imt_methods_size = new_methods->size() * kMethodSize;
7761 }
7762 }
7763 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007764
Vladimir Marko0441d202022-02-18 13:55:15 +00007765 auto update_imt = [=](ObjPtr<mirror::Class> iface, size_t j, ArtMethod* implementation)
7766 REQUIRES_SHARED(Locks::mutator_lock_) {
7767 // Place method in imt if entry is empty, place conflict otherwise.
7768 ArtMethod** imt_ptr = &out_imt[iface->GetVirtualMethod(j, kPointerSize)->GetImtIndex()];
7769 class_linker->SetIMTRef(unimplemented_method,
7770 imt_conflict_method,
7771 implementation,
7772 /*out*/out_new_conflict,
7773 /*out*/imt_ptr);
7774 };
7775
Vladimir Marko19366b82022-01-18 10:41:28 +00007776 // For interfaces inherited from superclass, the new method arrays are empty,
7777 // so use vtable indexes from implementation methods from the superclass method array.
7778 for (size_t i = 0; i != super_ifcount; ++i) {
7779 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
Vladimir Marko0441d202022-02-18 13:55:15 +00007780 DCHECK(method_array == klass->GetSuperClass()->GetIfTable()->GetMethodArrayOrNull(i));
Vladimir Marko19366b82022-01-18 10:41:28 +00007781 if (method_array == nullptr) {
7782 continue;
7783 }
7784 size_t num_methods = method_array->GetLength();
7785 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Vladimir Marko0441d202022-02-18 13:55:15 +00007786 size_t j = 0;
7787 // First loop has method array shared with the super class.
7788 for (; j != num_methods; ++j) {
Vladimir Marko19366b82022-01-18 10:41:28 +00007789 ArtMethod* super_implementation =
Vladimir Marko0441d202022-02-18 13:55:15 +00007790 method_array->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7791 size_t vtable_index = super_implementation->GetMethodIndex();
7792 ArtMethod* implementation =
7793 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(vtable_index);
7794 // Check if we need to update IMT with this method, see above.
7795 if (reinterpret_cast<uintptr_t>(implementation) - imt_methods_begin < imt_methods_size) {
7796 update_imt(iface, j, implementation);
7797 }
7798 if (implementation != super_implementation) {
7799 // Copy-on-write and move to the next loop.
7800 Thread* self = self_;
7801 StackHandleScope<2u> hs(self);
7802 Handle<mirror::PointerArray> old_method_array = hs.NewHandle(method_array);
7803 HandleWrapperObjPtr<mirror::Class> h_iface = hs.NewHandleWrapper(&iface);
7804 if (ifcount == super_ifcount && iftable.Get() == klass->GetSuperClass()->GetIfTable()) {
7805 ObjPtr<mirror::IfTable> new_iftable = ObjPtr<mirror::IfTable>::DownCast(
7806 mirror::ObjectArray<mirror::Object>::CopyOf(
7807 iftable, self, ifcount * mirror::IfTable::kMax));
7808 if (new_iftable == nullptr) {
7809 return false;
7810 }
7811 iftable.Assign(new_iftable);
7812 }
7813 method_array = ObjPtr<mirror::PointerArray>::DownCast(
7814 mirror::Array::CopyOf(old_method_array, self, num_methods));
7815 if (method_array == nullptr) {
7816 return false;
7817 }
7818 iftable->SetMethodArray(i, method_array);
7819 method_array->SetElementPtrSize(j, implementation, kPointerSize);
7820 ++j;
7821 break;
7822 }
7823 }
7824 // Second loop (if non-empty) has method array different from the superclass.
7825 for (; j != num_methods; ++j) {
7826 ArtMethod* super_implementation =
7827 method_array->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
Vladimir Marko19366b82022-01-18 10:41:28 +00007828 size_t vtable_index = super_implementation->GetMethodIndex();
7829 ArtMethod* implementation =
7830 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(vtable_index);
7831 method_array->SetElementPtrSize(j, implementation, kPointerSize);
Vladimir Marko51718132022-02-07 16:31:08 +00007832 // Check if we need to update IMT with this method, see above.
7833 if (reinterpret_cast<uintptr_t>(implementation) - imt_methods_begin < imt_methods_size) {
Vladimir Marko0441d202022-02-18 13:55:15 +00007834 update_imt(iface, j, implementation);
Vladimir Marko51718132022-02-07 16:31:08 +00007835 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007836 }
7837 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007838
Vladimir Marko19366b82022-01-18 10:41:28 +00007839 // New interface method arrays contain vtable indexes. Translate them to methods.
Vladimir Marko51718132022-02-07 16:31:08 +00007840 DCHECK_EQ(klass->ShouldHaveImt(), !is_klass_abstract);
Vladimir Marko19366b82022-01-18 10:41:28 +00007841 for (size_t i = super_ifcount; i != ifcount; ++i) {
7842 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
7843 if (method_array == nullptr) {
7844 continue;
Vladimir Marko921094a2017-01-12 18:37:06 +00007845 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007846 size_t num_methods = method_array->GetLength();
7847 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
7848 for (size_t j = 0; j != num_methods; ++j) {
7849 size_t vtable_index = method_array->GetElementPtrSize<size_t, kPointerSize>(j);
7850 ArtMethod* implementation =
7851 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(vtable_index);
7852 method_array->SetElementPtrSize(j, implementation, kPointerSize);
Vladimir Marko51718132022-02-07 16:31:08 +00007853 if (!is_klass_abstract) {
Vladimir Marko0441d202022-02-18 13:55:15 +00007854 update_imt(iface, j, implementation);
Vladimir Marko51718132022-02-07 16:31:08 +00007855 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007856 }
7857 }
Vladimir Marko0441d202022-02-18 13:55:15 +00007858
7859 return true;
Vladimir Marko921094a2017-01-12 18:37:06 +00007860}
7861
Vladimir Marko19366b82022-01-18 10:41:28 +00007862NO_INLINE
7863static void ThrowIllegalAccessErrorForImplementingMethod(ObjPtr<mirror::Class> klass,
7864 ArtMethod* vtable_method,
7865 ArtMethod* interface_method)
7866 REQUIRES_SHARED(Locks::mutator_lock_) {
7867 DCHECK(!vtable_method->IsAbstract());
7868 DCHECK(!vtable_method->IsPublic());
7869 ThrowIllegalAccessError(
7870 klass,
7871 "Method '%s' implementing interface method '%s' is not public",
7872 vtable_method->PrettyMethod().c_str(),
7873 interface_method->PrettyMethod().c_str());
Vladimir Marko921094a2017-01-12 18:37:06 +00007874}
7875
Vladimir Markob91402f2021-12-21 15:55:06 +00007876template <PointerSize kPointerSize>
Vladimir Marko0441d202022-02-18 13:55:15 +00007877ObjPtr<mirror::PointerArray> ClassLinker::LinkMethodsHelper<kPointerSize>::AllocPointerArray(
7878 Thread* self, size_t length) {
7879 using PointerArrayType = std::conditional_t<
7880 kPointerSize == PointerSize::k64, mirror::LongArray, mirror::IntArray>;
7881 ObjPtr<mirror::Array> array = PointerArrayType::Alloc(self, length);
7882 return ObjPtr<mirror::PointerArray>::DownCast(array);
7883}
7884
7885template <PointerSize kPointerSize>
7886bool ClassLinker::LinkMethodsHelper<kPointerSize>::AllocateIfTableMethodArrays(
7887 Thread* self,
7888 Handle<mirror::Class> klass,
7889 Handle<mirror::IfTable> iftable) {
7890 DCHECK(!klass->IsInterface());
7891 DCHECK(klass_->HasSuperClass());
7892 const size_t ifcount = iftable->Count();
7893 // We do not need a read barrier here as the length is constant, both from-space and
7894 // to-space `IfTable`s shall yield the same result. See also `Class::GetIfTableCount()`.
7895 size_t super_ifcount =
7896 klass->GetSuperClass<kDefaultVerifyFlags, kWithoutReadBarrier>()->GetIfTableCount();
7897 if (ifcount == super_ifcount) {
7898 DCHECK(iftable.Get() == klass_->GetSuperClass()->GetIfTable());
7899 return true;
7900 }
7901
7902 if (kIsDebugBuild) {
7903 // The method array references for superclass interfaces have been copied.
7904 // We shall allocate new arrays if needed (copy-on-write) in `FinalizeIfTable()`.
7905 ObjPtr<mirror::IfTable> super_iftable = klass_->GetSuperClass()->GetIfTable();
7906 for (size_t i = 0; i != super_ifcount; ++i) {
7907 CHECK(iftable->GetInterface(i) == super_iftable->GetInterface(i));
7908 CHECK(iftable->GetMethodArrayOrNull(i) == super_iftable->GetMethodArrayOrNull(i));
7909 }
7910 }
7911
7912 for (size_t i = super_ifcount; i < ifcount; ++i) {
7913 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
7914 if (num_methods > 0) {
7915 ObjPtr<mirror::PointerArray> method_array = AllocPointerArray(self, num_methods);
7916 if (UNLIKELY(method_array == nullptr)) {
7917 self->AssertPendingOOMException();
7918 return false;
7919 }
7920 iftable->SetMethodArray(i, method_array);
7921 }
7922 }
7923 return true;
7924}
7925
7926template <PointerSize kPointerSize>
Vladimir Markobed84ef2022-01-21 13:57:14 +00007927size_t ClassLinker::LinkMethodsHelper<kPointerSize>::AssignVTableIndexes(
Vladimir Marko19366b82022-01-18 10:41:28 +00007928 ObjPtr<mirror::Class> klass,
7929 ObjPtr<mirror::Class> super_class,
Vladimir Marko51718132022-02-07 16:31:08 +00007930 bool is_super_abstract,
Vladimir Marko19366b82022-01-18 10:41:28 +00007931 size_t num_virtual_methods,
7932 ObjPtr<mirror::IfTable> iftable) {
Vladimir Marko8670e042021-12-21 17:55:48 +00007933 DCHECK(!klass->IsInterface());
7934 DCHECK(klass->HasSuperClass());
7935 DCHECK(klass->GetSuperClass() == super_class);
Vladimir Marko8670e042021-12-21 17:55:48 +00007936
7937 // There should be no thread suspension unless we want to throw an exception.
Vladimir Marko7ddae992022-01-18 14:27:20 +00007938 // (We are using `ObjPtr<>` and raw vtable pointers that are invalidated by thread suspension.)
Vladimir Marko8670e042021-12-21 17:55:48 +00007939 std::optional<ScopedAssertNoThreadSuspension> sants(__FUNCTION__);
7940
7941 // Prepare a hash table with virtual methods from the superclass.
7942 // For the unlikely cases that there are multiple methods with the same signature
7943 // but different vtable indexes, keep an array with indexes of the previous
7944 // methods with the same signature (walked as singly-linked lists).
Vladimir Marko7ddae992022-01-18 14:27:20 +00007945 uint8_t* raw_super_vtable;
7946 size_t super_vtable_length;
Vladimir Marko51718132022-02-07 16:31:08 +00007947 if (is_super_abstract) {
7948 DCHECK(!super_class->ShouldHaveEmbeddedVTable());
Vladimir Marko7ddae992022-01-18 14:27:20 +00007949 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTableDuringLinking();
7950 DCHECK(super_vtable != nullptr);
7951 raw_super_vtable = reinterpret_cast<uint8_t*>(super_vtable.Ptr()) +
7952 mirror::Array::DataOffset(static_cast<size_t>(kPointerSize)).Uint32Value();
7953 super_vtable_length = super_vtable->GetLength();
Vladimir Marko51718132022-02-07 16:31:08 +00007954 } else {
7955 DCHECK(super_class->ShouldHaveEmbeddedVTable());
7956 raw_super_vtable = reinterpret_cast<uint8_t*>(super_class.Ptr()) +
7957 mirror::Class::EmbeddedVTableOffset(kPointerSize).Uint32Value();
7958 super_vtable_length = super_class->GetEmbeddedVTableLength();
Vladimir Marko7ddae992022-01-18 14:27:20 +00007959 }
7960 VTableAccessor super_vtable_accessor(raw_super_vtable, super_vtable_length);
Vladimir Marko8670e042021-12-21 17:55:48 +00007961 static constexpr double kMinLoadFactor = 0.3;
7962 static constexpr double kMaxLoadFactor = 0.5;
Vladimir Marko19366b82022-01-18 10:41:28 +00007963 static constexpr size_t kMaxStackBuferSize = 256;
7964 const size_t super_vtable_buffer_size = super_vtable_length * 3;
7965 const size_t declared_virtuals_buffer_size = num_virtual_methods * 3;
7966 const size_t total_buffer_size = super_vtable_buffer_size + declared_virtuals_buffer_size;
7967 uint32_t* super_vtable_buffer_ptr = (total_buffer_size <= kMaxStackBuferSize)
7968 ? reinterpret_cast<uint32_t*>(alloca(total_buffer_size * sizeof(uint32_t)))
7969 : allocator_.AllocArray<uint32_t>(total_buffer_size);
7970 uint32_t* declared_virtuals_buffer_ptr = super_vtable_buffer_ptr + super_vtable_buffer_size;
Vladimir Marko7ddae992022-01-18 14:27:20 +00007971 VTableSignatureSet super_vtable_signatures(
Vladimir Marko8670e042021-12-21 17:55:48 +00007972 kMinLoadFactor,
7973 kMaxLoadFactor,
Vladimir Marko7ddae992022-01-18 14:27:20 +00007974 VTableSignatureHash(super_vtable_accessor),
7975 VTableSignatureEqual(super_vtable_accessor),
Vladimir Marko19366b82022-01-18 10:41:28 +00007976 super_vtable_buffer_ptr,
7977 super_vtable_buffer_size,
Vladimir Marko8670e042021-12-21 17:55:48 +00007978 allocator_.Adapter());
Vladimir Markobed84ef2022-01-21 13:57:14 +00007979 ArrayRef<uint32_t> same_signature_vtable_lists;
Vladimir Marko8670e042021-12-21 17:55:48 +00007980 // Insert the first `mirror::Object::kVTableLength` indexes with pre-calculated hashes.
7981 DCHECK_GE(super_vtable_length, mirror::Object::kVTableLength);
7982 for (uint32_t i = 0; i != mirror::Object::kVTableLength; ++i) {
7983 size_t hash = class_linker_->object_virtual_method_hashes_[i];
Vladimir Marko163ebe22022-01-07 12:35:36 +00007984 // There are no duplicate signatures in `java.lang.Object`, so use `HashSet<>::PutWithHash()`.
7985 // This avoids equality comparison for the three `java.lang.Object.wait()` overloads.
7986 super_vtable_signatures.PutWithHash(i, hash);
Vladimir Marko8670e042021-12-21 17:55:48 +00007987 }
7988 // Insert the remaining indexes, check for duplicate signatures.
7989 if (super_vtable_length > mirror::Object::kVTableLength) {
7990 for (size_t i = mirror::Object::kVTableLength; i < super_vtable_length; ++i) {
7991 // Use `super_vtable_accessor` for getting the method for hash calculation.
7992 // Letting `HashSet<>::insert()` use the internal accessor copy in the hash
7993 // function prevents the compiler from optimizing this properly because the
7994 // compiler cannot prove that the accessor copy is immutable.
7995 size_t hash = ComputeMethodHash(super_vtable_accessor.GetVTableEntry(i));
7996 auto [it, inserted] = super_vtable_signatures.InsertWithHash(i, hash);
7997 if (UNLIKELY(!inserted)) {
Vladimir Markobed84ef2022-01-21 13:57:14 +00007998 if (same_signature_vtable_lists.empty()) {
7999 same_signature_vtable_lists = ArrayRef<uint32_t>(
8000 allocator_.AllocArray<uint32_t>(super_vtable_length), super_vtable_length);
8001 std::fill_n(same_signature_vtable_lists.data(), super_vtable_length, dex::kDexNoIndex);
Vladimir Markod5d11d92021-02-02 16:24:25 +00008002 same_signature_vtable_lists_ = same_signature_vtable_lists;
Vladimir Marko8670e042021-12-21 17:55:48 +00008003 }
8004 DCHECK_LT(*it, i);
Vladimir Markobed84ef2022-01-21 13:57:14 +00008005 same_signature_vtable_lists[i] = *it;
Vladimir Marko8670e042021-12-21 17:55:48 +00008006 *it = i;
8007 }
8008 }
8009 }
8010
8011 // For each declared virtual method, look for a superclass virtual method
8012 // to override and assign a new vtable index if no method was overridden.
Vladimir Marko19366b82022-01-18 10:41:28 +00008013 DeclaredVirtualSignatureSet declared_virtual_signatures(
8014 kMinLoadFactor,
8015 kMaxLoadFactor,
8016 DeclaredVirtualSignatureHash(klass),
8017 DeclaredVirtualSignatureEqual(klass),
8018 declared_virtuals_buffer_ptr,
8019 declared_virtuals_buffer_size,
8020 allocator_.Adapter());
Vladimir Marko8670e042021-12-21 17:55:48 +00008021 const bool is_proxy_class = klass->IsProxyClass();
8022 size_t vtable_length = super_vtable_length;
Vladimir Marko19366b82022-01-18 10:41:28 +00008023 for (size_t i = 0; i != num_virtual_methods; ++i) {
Vladimir Marko8670e042021-12-21 17:55:48 +00008024 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
Vladimir Marko19366b82022-01-18 10:41:28 +00008025 DCHECK(!virtual_method->IsStatic()) << virtual_method->PrettyMethod();
Vladimir Marko8670e042021-12-21 17:55:48 +00008026 ArtMethod* signature_method = UNLIKELY(is_proxy_class)
8027 ? virtual_method->GetInterfaceMethodForProxyUnchecked(kPointerSize)
8028 : virtual_method;
8029 size_t hash = ComputeMethodHash(signature_method);
Vladimir Marko19366b82022-01-18 10:41:28 +00008030 declared_virtual_signatures.PutWithHash(i, hash);
Vladimir Marko8670e042021-12-21 17:55:48 +00008031 auto it = super_vtable_signatures.FindWithHash(signature_method, hash);
8032 if (it != super_vtable_signatures.end()) {
8033 size_t super_index = *it;
8034 DCHECK_LT(super_index, super_vtable_length);
8035 ArtMethod* super_method = super_vtable_accessor.GetVTableEntry(super_index);
8036 // Historical note: Before Android 4.1, an inaccessible package-private
8037 // superclass method would have been incorrectly overridden.
8038 bool overrides = klass->CanAccessMember(super_method->GetDeclaringClass(),
8039 super_method->GetAccessFlags());
Vladimir Markod5d11d92021-02-02 16:24:25 +00008040 if (overrides && super_method->IsFinal()) {
8041 sants.reset();
8042 ThrowLinkageError(klass, "Method %s overrides final method in class %s",
8043 virtual_method->PrettyMethod().c_str(),
8044 super_method->GetDeclaringClassDescriptor());
8045 return 0u;
8046 }
Vladimir Markobed84ef2022-01-21 13:57:14 +00008047 if (UNLIKELY(!same_signature_vtable_lists.empty())) {
Vladimir Markod5d11d92021-02-02 16:24:25 +00008048 // We may override more than one method according to JLS, see b/211854716 .
8049 // We record the highest overridden vtable index here so that we can walk
8050 // the list to find other overridden methods when constructing the vtable.
8051 // However, we walk all the methods to check for final method overriding.
Vladimir Marko8670e042021-12-21 17:55:48 +00008052 size_t current_index = super_index;
Vladimir Markobed84ef2022-01-21 13:57:14 +00008053 while (same_signature_vtable_lists[current_index] != dex::kDexNoIndex) {
8054 DCHECK_LT(same_signature_vtable_lists[current_index], current_index);
8055 current_index = same_signature_vtable_lists[current_index];
Vladimir Marko8670e042021-12-21 17:55:48 +00008056 ArtMethod* current_method = super_vtable_accessor.GetVTableEntry(current_index);
8057 if (klass->CanAccessMember(current_method->GetDeclaringClass(),
8058 current_method->GetAccessFlags())) {
Vladimir Markod5d11d92021-02-02 16:24:25 +00008059 if (current_method->IsFinal()) {
8060 sants.reset();
8061 ThrowLinkageError(klass, "Method %s overrides final method in class %s",
8062 virtual_method->PrettyMethod().c_str(),
8063 current_method->GetDeclaringClassDescriptor());
8064 return 0u;
8065 }
8066 if (!overrides) {
8067 overrides = true;
8068 super_index = current_index;
8069 super_method = current_method;
8070 }
Vladimir Marko8670e042021-12-21 17:55:48 +00008071 }
8072 }
8073 }
8074 if (overrides) {
Vladimir Marko8670e042021-12-21 17:55:48 +00008075 virtual_method->SetMethodIndex(super_index);
8076 continue;
8077 }
8078 }
8079 // The method does not override any method from superclass, so it needs a new vtable index.
8080 virtual_method->SetMethodIndex(vtable_length);
8081 ++vtable_length;
8082 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008083
8084 // Assign vtable indexes for interface methods in new interfaces and store them
8085 // in implementation method arrays. These shall be replaced by actual method
8086 // pointers later. We do not need to do this for superclass interfaces as we can
8087 // get these vtable indexes from implementation methods in superclass iftable.
8088 // Record data for copied methods which shall be referenced by the vtable.
8089 const size_t ifcount = iftable->Count();
8090 ObjPtr<mirror::IfTable> super_iftable = super_class->GetIfTable();
8091 const size_t super_ifcount = super_iftable->Count();
8092 for (size_t i = ifcount; i != super_ifcount; ) {
8093 --i;
8094 DCHECK_LT(i, ifcount);
8095 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
8096 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
8097 size_t num_methods = (method_array != nullptr) ? method_array->GetLength() : 0u;
8098 for (size_t j = 0; j != num_methods; ++j) {
8099 ArtMethod* interface_method = iface->GetVirtualMethod(j, kPointerSize);
8100 size_t hash = ComputeMethodHash(interface_method);
8101 ArtMethod* vtable_method = nullptr;
8102 bool found = false;
8103 auto it1 = declared_virtual_signatures.FindWithHash(interface_method, hash);
8104 if (it1 != declared_virtual_signatures.end()) {
8105 vtable_method = klass->GetVirtualMethodDuringLinking(*it1, kPointerSize);
8106 found = true;
8107 } else {
8108 auto it2 = super_vtable_signatures.FindWithHash(interface_method, hash);
8109 if (it2 != super_vtable_signatures.end()) {
Vladimir Marko608a9152022-04-04 14:56:12 +01008110 // If there are multiple vtable methods with the same signature, the one with
8111 // the highest vtable index is not nessarily the one in most-derived class.
8112 // Find the most-derived method. See b/211854716 .
Vladimir Marko19366b82022-01-18 10:41:28 +00008113 vtable_method = super_vtable_accessor.GetVTableEntry(*it2);
Vladimir Marko608a9152022-04-04 14:56:12 +01008114 if (UNLIKELY(!same_signature_vtable_lists.empty())) {
8115 size_t current_index = *it2;
8116 while (same_signature_vtable_lists[current_index] != dex::kDexNoIndex) {
8117 DCHECK_LT(same_signature_vtable_lists[current_index], current_index);
8118 current_index = same_signature_vtable_lists[current_index];
8119 ArtMethod* current_method = super_vtable_accessor.GetVTableEntry(current_index);
8120 ObjPtr<mirror::Class> current_class = current_method->GetDeclaringClass();
8121 if (current_class->IsSubClass(vtable_method->GetDeclaringClass())) {
8122 vtable_method = current_method;
8123 }
8124 }
8125 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008126 found = true;
8127 }
8128 }
8129 uint32_t vtable_index = vtable_length;
8130 if (found) {
8131 DCHECK(vtable_method != nullptr);
8132 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Vladimir Marko608a9152022-04-04 14:56:12 +01008133 // FIXME: Delay the exception until we actually try to call the method. b/211854716
Vladimir Marko19366b82022-01-18 10:41:28 +00008134 sants.reset();
8135 ThrowIllegalAccessErrorForImplementingMethod(klass, vtable_method, interface_method);
8136 return 0u;
8137 }
8138 vtable_index = vtable_method->GetMethodIndexDuringLinking();
8139 if (!vtable_method->IsOverridableByDefaultMethod()) {
8140 method_array->SetElementPtrSize(j, vtable_index, kPointerSize);
8141 continue;
8142 }
8143 }
8144
8145 auto [it, inserted] = copied_method_records_.InsertWithHash(
8146 CopiedMethodRecord(interface_method, vtable_index), hash);
8147 if (found) {
8148 DCHECK_EQ(vtable_index, it->GetMethodIndex());
8149 } else if (inserted) {
8150 DCHECK_EQ(vtable_index, it->GetMethodIndex());
8151 DCHECK_EQ(vtable_index, vtable_length);
8152 ++vtable_length;
8153 } else {
8154 vtable_index = it->GetMethodIndex();
8155 }
8156 method_array->SetElementPtrSize(j, it->GetMethodIndex(), kPointerSize);
8157 if (inserted) {
8158 it->SetState(interface_method->IsAbstract() ? CopiedMethodRecord::State::kAbstractSingle
8159 : CopiedMethodRecord::State::kDefaultSingle);
8160 } else {
8161 it->UpdateState(iface, interface_method, vtable_index, iftable, ifcount, i);
8162 }
8163 }
8164 }
8165 // Finalize copied method records and check if we can reuse some methods from superclass vtable.
8166 size_t num_new_copied_methods = copied_method_records_.size();
8167 for (CopiedMethodRecord& record : copied_method_records_) {
8168 uint32_t vtable_index = record.GetMethodIndex();
8169 if (vtable_index < super_vtable_length) {
8170 ArtMethod* super_method = super_vtable_accessor.GetVTableEntry(record.GetMethodIndex());
8171 DCHECK(super_method->IsOverridableByDefaultMethod());
8172 record.FinalizeState(
8173 super_method, vtable_index, iftable, ifcount, super_iftable, super_ifcount);
8174 if (record.GetState() == CopiedMethodRecord::State::kUseSuperMethod) {
8175 --num_new_copied_methods;
8176 }
8177 }
8178 }
8179 num_new_copied_methods_ = num_new_copied_methods;
8180
Vladimir Marko8670e042021-12-21 17:55:48 +00008181 if (UNLIKELY(!IsUint<16>(vtable_length))) {
8182 sants.reset();
8183 ThrowClassFormatError(klass, "Too many methods defined on class: %zd", vtable_length);
8184 return 0u;
8185 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008186
Vladimir Marko8670e042021-12-21 17:55:48 +00008187 return vtable_length;
8188}
8189
8190template <PointerSize kPointerSize>
Vladimir Marko19366b82022-01-18 10:41:28 +00008191bool ClassLinker::LinkMethodsHelper<kPointerSize>::FindCopiedMethodsForInterface(
8192 ObjPtr<mirror::Class> klass,
8193 size_t num_virtual_methods,
8194 ObjPtr<mirror::IfTable> iftable) {
8195 DCHECK(klass->IsInterface());
8196 DCHECK(klass->HasSuperClass());
8197 DCHECK(klass->GetSuperClass()->IsObjectClass());
8198 DCHECK_EQ(klass->GetSuperClass()->GetIfTableCount(), 0);
8199
8200 // There should be no thread suspension unless we want to throw an exception.
8201 // (We are using `ObjPtr<>`s that are invalidated by thread suspension.)
8202 std::optional<ScopedAssertNoThreadSuspension> sants(__FUNCTION__);
8203
8204 // Prepare a `HashSet<>` with the declared virtual methods. These mask any methods
8205 // from superinterfaces, so we can filter out matching superinterface methods.
8206 static constexpr double kMinLoadFactor = 0.3;
8207 static constexpr double kMaxLoadFactor = 0.5;
8208 static constexpr size_t kMaxStackBuferSize = 256;
8209 const size_t declared_virtuals_buffer_size = num_virtual_methods * 3;
8210 uint32_t* declared_virtuals_buffer_ptr = (declared_virtuals_buffer_size <= kMaxStackBuferSize)
8211 ? reinterpret_cast<uint32_t*>(alloca(declared_virtuals_buffer_size * sizeof(uint32_t)))
8212 : allocator_.AllocArray<uint32_t>(declared_virtuals_buffer_size);
8213 DeclaredVirtualSignatureSet declared_virtual_signatures(
8214 kMinLoadFactor,
8215 kMaxLoadFactor,
8216 DeclaredVirtualSignatureHash(klass),
8217 DeclaredVirtualSignatureEqual(klass),
8218 declared_virtuals_buffer_ptr,
8219 declared_virtuals_buffer_size,
8220 allocator_.Adapter());
8221 for (size_t i = 0; i != num_virtual_methods; ++i) {
8222 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
8223 DCHECK(!virtual_method->IsStatic()) << virtual_method->PrettyMethod();
8224 size_t hash = ComputeMethodHash(virtual_method);
8225 declared_virtual_signatures.PutWithHash(i, hash);
8226 }
8227
8228 // We do not create miranda methods for interface classes, so we do not need to track
8229 // non-default (abstract) interface methods. The downside is that we cannot use the
8230 // optimized code paths with `CopiedMethodRecord::State::kDefaultSingle` and since
8231 // we do not fill method arrays for interfaces, the method search actually has to
8232 // compare signatures instead of searching for the implementing method.
8233 const size_t ifcount = iftable->Count();
8234 size_t new_method_index = num_virtual_methods;
8235 for (size_t i = ifcount; i != 0u; ) {
8236 --i;
8237 DCHECK_LT(i, ifcount);
8238 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
8239 if (!iface->HasDefaultMethods()) {
8240 continue; // No default methods to process.
8241 }
8242 size_t num_methods = iface->NumDeclaredVirtualMethods();
8243 for (size_t j = 0; j != num_methods; ++j) {
8244 ArtMethod* interface_method = iface->GetVirtualMethod(j, kPointerSize);
8245 if (!interface_method->IsDefault()) {
8246 continue; // Do not process this non-default method.
8247 }
8248 size_t hash = ComputeMethodHash(interface_method);
8249 auto it1 = declared_virtual_signatures.FindWithHash(interface_method, hash);
8250 if (it1 != declared_virtual_signatures.end()) {
8251 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(*it1, kPointerSize);
8252 if (!virtual_method->IsAbstract() && !virtual_method->IsPublic()) {
8253 sants.reset();
8254 ThrowIllegalAccessErrorForImplementingMethod(klass, virtual_method, interface_method);
8255 return false;
8256 }
8257 continue; // This default method is masked by a method declared in this interface.
8258 }
8259
8260 CopiedMethodRecord new_record(interface_method, new_method_index);
8261 auto it = copied_method_records_.FindWithHash(new_record, hash);
8262 if (it == copied_method_records_.end()) {
8263 // Pretend that there is another default method and try to update the state.
8264 // If the `interface_method` is not masked, the state shall change to
8265 // `kDefaultConflict`; if it is masked, the state remains `kDefault`.
8266 new_record.SetState(CopiedMethodRecord::State::kDefault);
8267 new_record.UpdateStateForInterface(iface, interface_method, iftable, ifcount, i);
8268 if (new_record.GetState() == CopiedMethodRecord::State::kDefaultConflict) {
8269 // Insert the new record with the state `kDefault`.
8270 new_record.SetState(CopiedMethodRecord::State::kDefault);
8271 copied_method_records_.PutWithHash(new_record, hash);
8272 DCHECK_EQ(new_method_index, new_record.GetMethodIndex());
8273 ++new_method_index;
8274 }
8275 } else {
8276 it->UpdateStateForInterface(iface, interface_method, iftable, ifcount, i);
8277 }
8278 }
8279 }
8280
8281 // Prune records without conflict. (Method indexes are updated in `ReallocMethods()`.)
8282 // We do not copy normal default methods to subinterfaces, instead we find the
8283 // default method with `Class::FindVirtualMethodForInterfaceSuper()` when needed.
8284 size_t num_new_copied_methods = copied_method_records_.size();
8285 for (CopiedMethodRecord& record : copied_method_records_) {
8286 if (record.GetState() != CopiedMethodRecord::State::kDefaultConflict) {
8287 DCHECK(record.GetState() == CopiedMethodRecord::State::kDefault);
8288 record.SetState(CopiedMethodRecord::State::kUseSuperMethod);
8289 --num_new_copied_methods;
8290 }
8291 }
8292 num_new_copied_methods_ = num_new_copied_methods;
8293
8294 return true;
8295}
8296
8297
8298template <PointerSize kPointerSize>
Vladimir Markob91402f2021-12-21 15:55:06 +00008299FLATTEN
Vladimir Marko78f62d82022-01-10 16:25:19 +00008300bool ClassLinker::LinkMethodsHelper<kPointerSize>::LinkMethods(
Vladimir Markobc893672021-11-10 15:25:46 +00008301 Thread* self,
Vladimir Marko78f62d82022-01-10 16:25:19 +00008302 Handle<mirror::Class> klass,
8303 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
8304 bool* out_new_conflict,
8305 ArtMethod** out_imt) {
Vladimir Markobc893672021-11-10 15:25:46 +00008306 const size_t num_virtual_methods = klass->NumVirtualMethods();
8307 if (klass->IsInterface()) {
8308 // No vtable.
8309 if (!IsUint<16>(num_virtual_methods)) {
8310 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
8311 return false;
8312 }
8313 bool has_defaults = false;
8314 // Assign each method an IMT index and set the default flag.
8315 for (size_t i = 0; i < num_virtual_methods; ++i) {
Vladimir Markob91402f2021-12-21 15:55:06 +00008316 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
Vladimir Markobc893672021-11-10 15:25:46 +00008317 m->SetMethodIndex(i);
8318 if (!m->IsAbstract()) {
8319 // If the dex file does not support default methods, throw ClassFormatError.
8320 // This check is necessary to protect from odd cases, such as native default
8321 // methods, that the dex file verifier permits for old dex file versions. b/157170505
8322 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
8323 // currently running CTS tests for default methods with dex file version 035 which
8324 // does not support default methods. So, we limit this to native methods. b/157718952
8325 if (m->IsNative()) {
8326 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
8327 ThrowClassFormatError(klass.Get(),
8328 "Dex file does not support default method '%s'",
8329 m->PrettyMethod().c_str());
8330 return false;
8331 }
Vladimir Markofd0aec42022-01-27 14:27:24 +00008332 if (!m->IsPublic()) {
8333 // The verifier should have caught the non-public method for dex version 37.
8334 // Just warn and skip it since this is from before default-methods so we don't
8335 // really need to care that it has code.
8336 LOG(WARNING) << "Default interface method " << m->PrettyMethod() << " is not public! "
8337 << "This will be a fatal error in subsequent versions of android. "
8338 << "Continuing anyway.";
8339 }
Vladimir Markobc893672021-11-10 15:25:46 +00008340 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
8341 has_defaults = true;
8342 }
8343 }
8344 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
8345 // during initialization. This is a performance optimization. We could simply traverse the
8346 // virtual_methods_ array again during initialization.
8347 if (has_defaults) {
8348 klass->SetHasDefaultMethods();
8349 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008350 ObjPtr<mirror::IfTable> iftable = SetupInterfaceLookupTable(
8351 self, klass, &allocator_, NonProxyInterfacesAccessor(class_linker_, klass));
8352 if (UNLIKELY(iftable == nullptr)) {
8353 self->AssertPendingException();
8354 return false;
8355 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008356 size_t ifcount = iftable->Count();
8357 bool have_super_with_defaults = false;
8358 for (size_t i = 0; i != ifcount; ++i) {
8359 if (iftable->GetInterface(i)->HasDefaultMethods()) {
8360 have_super_with_defaults = true;
8361 break;
8362 }
8363 }
8364 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8365 if (have_super_with_defaults) {
8366 if (!FindCopiedMethodsForInterface(klass.Get(), num_virtual_methods, iftable)) {
8367 self->AssertPendingException();
8368 return false;
8369 }
8370 if (num_new_copied_methods_ != 0u) {
8371 // Re-check the number of methods.
8372 size_t final_num_virtual_methods = num_virtual_methods + num_new_copied_methods_;
8373 if (!IsUint<16>(final_num_virtual_methods)) {
8374 ThrowClassFormatError(
8375 klass.Get(), "Too many methods on interface: %zu", final_num_virtual_methods);
8376 return false;
8377 }
8378 ReallocMethods(klass.Get());
8379 }
8380 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008381 klass->SetIfTable(iftable);
Vladimir Marko19366b82022-01-18 10:41:28 +00008382 if (kIsDebugBuild) {
8383 // May cause thread suspension, so do this after we're done with `ObjPtr<> iftable`.
8384 ClobberOldMethods(old_methods, klass->GetMethodsPtr());
8385 }
8386 return true;
Vladimir Markob91402f2021-12-21 15:55:06 +00008387 } else if (LIKELY(klass->HasSuperClass())) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00008388 // We set up the interface lookup table now because we need it to determine if we need
8389 // to update any vtable entries with new default method implementations.
Vladimir Markobc893672021-11-10 15:25:46 +00008390 StackHandleScope<3> hs(self);
Vladimir Marko0441d202022-02-18 13:55:15 +00008391 MutableHandle<mirror::IfTable> iftable = hs.NewHandle(UNLIKELY(klass->IsProxyClass())
Vladimir Marko78f62d82022-01-10 16:25:19 +00008392 ? SetupInterfaceLookupTable(self, klass, &allocator_, ProxyInterfacesAccessor(interfaces))
8393 : SetupInterfaceLookupTable(
8394 self, klass, &allocator_, NonProxyInterfacesAccessor(class_linker_, klass)));
8395 if (UNLIKELY(iftable == nullptr)) {
8396 self->AssertPendingException();
8397 return false;
8398 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008399
Vladimir Marko51718132022-02-07 16:31:08 +00008400 // Copy the IMT from superclass if present and needed. Update with new methods later.
Vladimir Marko0441d202022-02-18 13:55:15 +00008401 Handle<mirror::Class> super_class = hs.NewHandle(klass->GetSuperClass());
Vladimir Marko51718132022-02-07 16:31:08 +00008402 bool is_klass_abstract = klass->IsAbstract();
8403 bool is_super_abstract = super_class->IsAbstract();
8404 DCHECK_EQ(klass->ShouldHaveImt(), !is_klass_abstract);
8405 DCHECK_EQ(super_class->ShouldHaveImt(), !is_super_abstract);
8406 if (!is_klass_abstract && !is_super_abstract) {
8407 ImTable* super_imt = super_class->GetImt(kPointerSize);
8408 for (size_t i = 0; i < ImTable::kSize; ++i) {
8409 out_imt[i] = super_imt->Get(i, kPointerSize);
8410 }
8411 }
8412
8413 // If there are no new virtual methods and no new interfaces, we can simply reuse
8414 // the vtable from superclass. We may need to make a copy if it's embedded.
Vladimir Marko0441d202022-02-18 13:55:15 +00008415 const size_t super_vtable_length = super_class->GetVTableLength();
Vladimir Marko0f71b192022-02-02 17:20:12 +00008416 if (num_virtual_methods == 0 && iftable.Get() == super_class->GetIfTable()) {
Vladimir Marko51718132022-02-07 16:31:08 +00008417 DCHECK_EQ(is_super_abstract, !super_class->ShouldHaveEmbeddedVTable());
8418 if (is_super_abstract) {
8419 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
8420 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
8421 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
8422 klass->SetVTable(super_vtable);
8423 // No IMT in the super class, we need to reconstruct it from the iftable.
8424 if (!is_klass_abstract && iftable->Count() != 0) {
8425 class_linker_->FillIMTFromIfTable(iftable.Get(),
8426 runtime_->GetImtUnimplementedMethod(),
8427 runtime_->GetImtConflictMethod(),
8428 klass.Get(),
8429 /*create_conflict_tables=*/false,
8430 /*ignore_copied_methods=*/false,
8431 out_new_conflict,
8432 out_imt);
8433 }
8434 } else {
Vladimir Marko0441d202022-02-18 13:55:15 +00008435 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, super_vtable_length);
Vladimir Marko8670e042021-12-21 17:55:48 +00008436 if (UNLIKELY(vtable == nullptr)) {
8437 self->AssertPendingOOMException();
Vladimir Markobc893672021-11-10 15:25:46 +00008438 return false;
8439 }
Vladimir Marko8670e042021-12-21 17:55:48 +00008440 for (size_t i = 0; i < super_vtable_length; i++) {
8441 vtable->SetElementPtrSize(
8442 i, super_class->GetEmbeddedVTableEntry(i, kPointerSize), kPointerSize);
8443 }
8444 klass->SetVTable(vtable);
Vladimir Marko51718132022-02-07 16:31:08 +00008445 // The IMT was already copied from superclass if `klass` is not abstract.
Vladimir Marko8670e042021-12-21 17:55:48 +00008446 }
Vladimir Markobed84ef2022-01-21 13:57:14 +00008447 klass->SetIfTable(iftable.Get());
Vladimir Marko8670e042021-12-21 17:55:48 +00008448 return true;
8449 }
8450
Vladimir Markobed84ef2022-01-21 13:57:14 +00008451 // Allocate method arrays, so that we can link interface methods without thread suspension,
8452 // otherwise GC could miss visiting newly allocated copied methods.
8453 // TODO: Do not allocate copied methods during linking, store only records about what
8454 // we need to allocate and allocate it at the end. Start with superclass iftable and
8455 // perform copy-on-write when needed to facilitate maximum memory sharing.
Vladimir Marko0441d202022-02-18 13:55:15 +00008456 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8457 self->AssertPendingOOMException();
Vladimir Markobed84ef2022-01-21 13:57:14 +00008458 return false;
8459 }
8460
Vladimir Marko51718132022-02-07 16:31:08 +00008461 size_t final_vtable_size = AssignVTableIndexes(
8462 klass.Get(), super_class.Get(), is_super_abstract, num_virtual_methods, iftable.Get());
Vladimir Marko8670e042021-12-21 17:55:48 +00008463 if (final_vtable_size == 0u) {
8464 self->AssertPendingException();
8465 return false;
8466 }
8467 DCHECK(IsUint<16>(final_vtable_size));
8468
8469 // Allocate the new vtable.
Vladimir Marko0441d202022-02-18 13:55:15 +00008470 Handle<mirror::PointerArray> vtable = hs.NewHandle(AllocPointerArray(self, final_vtable_size));
Vladimir Marko8670e042021-12-21 17:55:48 +00008471 if (UNLIKELY(vtable == nullptr)) {
8472 self->AssertPendingOOMException();
8473 return false;
8474 }
8475
Vladimir Marko19366b82022-01-18 10:41:28 +00008476 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8477 if (num_new_copied_methods_ != 0u) {
8478 ReallocMethods(klass.Get());
8479 }
8480
Vladimir Marko8670e042021-12-21 17:55:48 +00008481 // Store new virtual methods in the new vtable.
Vladimir Markod5d11d92021-02-02 16:24:25 +00008482 ArrayRef<uint32_t> same_signature_vtable_lists = same_signature_vtable_lists_;
Vladimir Marko8670e042021-12-21 17:55:48 +00008483 for (ArtMethod& virtual_method : klass->GetVirtualMethodsSliceUnchecked(kPointerSize)) {
Vladimir Markod5d11d92021-02-02 16:24:25 +00008484 uint32_t vtable_index = virtual_method.GetMethodIndexDuringLinking();
Vladimir Marko8670e042021-12-21 17:55:48 +00008485 vtable->SetElementPtrSize(vtable_index, &virtual_method, kPointerSize);
Vladimir Markod5d11d92021-02-02 16:24:25 +00008486 if (UNLIKELY(vtable_index < same_signature_vtable_lists.size())) {
8487 // We may override more than one method according to JLS, see b/211854716 .
8488 // If we do, arbitrarily update the method index to the lowest overridden vtable index.
8489 while (same_signature_vtable_lists[vtable_index] != dex::kDexNoIndex) {
8490 DCHECK_LT(same_signature_vtable_lists[vtable_index], vtable_index);
8491 vtable_index = same_signature_vtable_lists[vtable_index];
8492 ArtMethod* current_method = super_class->GetVTableEntry(vtable_index, kPointerSize);
8493 if (klass->CanAccessMember(current_method->GetDeclaringClass(),
8494 current_method->GetAccessFlags())) {
8495 DCHECK(!current_method->IsFinal());
8496 vtable->SetElementPtrSize(vtable_index, &virtual_method, kPointerSize);
8497 virtual_method.SetMethodIndex(vtable_index);
8498 }
8499 }
8500 }
Vladimir Marko8670e042021-12-21 17:55:48 +00008501 }
8502
8503 // For non-overridden vtable slots, copy a method from `super_class`.
8504 for (size_t j = 0; j != super_vtable_length; ++j) {
Vladimir Marko19366b82022-01-18 10:41:28 +00008505 if (vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j) == nullptr) {
8506 ArtMethod* super_method = super_class->GetVTableEntry(j, kPointerSize);
8507 vtable->SetElementPtrSize(j, super_method, kPointerSize);
Vladimir Markobc893672021-11-10 15:25:46 +00008508 }
8509 }
Vladimir Marko8670e042021-12-21 17:55:48 +00008510
Vladimir Marko51718132022-02-07 16:31:08 +00008511 // Update the `iftable` (and IMT) with finalized virtual methods.
Vladimir Marko0441d202022-02-18 13:55:15 +00008512 if (!FinalizeIfTable(klass,
8513 iftable,
8514 vtable,
8515 is_klass_abstract,
8516 is_super_abstract,
8517 out_new_conflict,
8518 out_imt)) {
8519 self->AssertPendingOOMException();
8520 return false;
8521 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008522
Vladimir Markobc893672021-11-10 15:25:46 +00008523 klass->SetVTable(vtable.Get());
Vladimir Marko19366b82022-01-18 10:41:28 +00008524 klass->SetIfTable(iftable.Get());
8525 if (kIsDebugBuild) {
8526 CheckVTable(self, klass, kPointerSize);
8527 ClobberOldMethods(old_methods, klass->GetMethodsPtr());
8528 }
8529 return true;
Vladimir Markobc893672021-11-10 15:25:46 +00008530 } else {
Vladimir Marko78f62d82022-01-10 16:25:19 +00008531 return LinkJavaLangObjectMethods(self, klass);
Vladimir Markobc893672021-11-10 15:25:46 +00008532 }
Vladimir Markobc893672021-11-10 15:25:46 +00008533}
8534
Vladimir Markob91402f2021-12-21 15:55:06 +00008535template <PointerSize kPointerSize>
Vladimir Marko78f62d82022-01-10 16:25:19 +00008536bool ClassLinker::LinkMethodsHelper<kPointerSize>::LinkJavaLangObjectMethods(
Vladimir Markob91402f2021-12-21 15:55:06 +00008537 Thread* self,
8538 Handle<mirror::Class> klass) {
8539 DCHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(class_linker_));
8540 DCHECK_EQ(klass->NumVirtualMethods(), mirror::Object::kVTableLength);
8541 static_assert(IsUint<16>(mirror::Object::kVTableLength));
Vladimir Marko0441d202022-02-18 13:55:15 +00008542 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, mirror::Object::kVTableLength);
Vladimir Markob91402f2021-12-21 15:55:06 +00008543 if (UNLIKELY(vtable == nullptr)) {
8544 self->AssertPendingOOMException();
8545 return false;
8546 }
8547 for (size_t i = 0; i < mirror::Object::kVTableLength; ++i) {
8548 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
8549 vtable->SetElementPtrSize(i, virtual_method, kPointerSize);
8550 virtual_method->SetMethodIndex(i);
8551 }
8552 klass->SetVTable(vtable);
8553 InitializeObjectVirtualMethodHashes(
8554 klass.Get(),
8555 kPointerSize,
8556 ArrayRef<uint32_t>(class_linker_->object_virtual_method_hashes_));
Vladimir Marko78f62d82022-01-10 16:25:19 +00008557 // The interface table is already allocated but there are no interface methods to link.
8558 DCHECK(klass->GetIfTable() != nullptr);
8559 DCHECK_EQ(klass->GetIfTableCount(), 0);
Vladimir Markob91402f2021-12-21 15:55:06 +00008560 return true;
8561}
8562
Vladimir Markobc893672021-11-10 15:25:46 +00008563// Populate the class vtable and itable. Compute return type indices.
8564bool ClassLinker::LinkMethods(Thread* self,
8565 Handle<mirror::Class> klass,
8566 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
8567 bool* out_new_conflict,
8568 ArtMethod** out_imt) {
8569 self->AllowThreadSuspension();
Vladimir Markobc893672021-11-10 15:25:46 +00008570 // Link virtual methods then interface methods.
8571 Runtime* const runtime = Runtime::Current();
Vladimir Markob91402f2021-12-21 15:55:06 +00008572 if (LIKELY(GetImagePointerSize() == kRuntimePointerSize)) {
8573 LinkMethodsHelper<kRuntimePointerSize> helper(this, klass, self, runtime);
Vladimir Marko78f62d82022-01-10 16:25:19 +00008574 return helper.LinkMethods(self, klass, interfaces, out_new_conflict, out_imt);
Vladimir Markob91402f2021-12-21 15:55:06 +00008575 } else {
8576 constexpr PointerSize kOtherPointerSize =
8577 (kRuntimePointerSize == PointerSize::k64) ? PointerSize::k32 : PointerSize::k64;
8578 LinkMethodsHelper<kOtherPointerSize> helper(this, klass, self, runtime);
Vladimir Marko78f62d82022-01-10 16:25:19 +00008579 return helper.LinkMethods(self, klass, interfaces, out_new_conflict, out_imt);
Vladimir Markob91402f2021-12-21 15:55:06 +00008580 }
Vladimir Markobc893672021-11-10 15:25:46 +00008581}
8582
Vladimir Marko42bee502021-01-28 14:58:35 +00008583class ClassLinker::LinkFieldsHelper {
8584 public:
8585 static bool LinkFields(ClassLinker* class_linker,
8586 Thread* self,
8587 Handle<mirror::Class> klass,
8588 bool is_static,
8589 size_t* class_size)
8590 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008591
Vladimir Marko42bee502021-01-28 14:58:35 +00008592 private:
8593 enum class FieldTypeOrder : uint16_t;
8594 class FieldGaps;
8595
8596 struct FieldTypeOrderAndIndex {
8597 FieldTypeOrder field_type_order;
8598 uint16_t field_index;
8599 };
8600
8601 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8602
8603 template <size_t kSize>
8604 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8605 REQUIRES_SHARED(Locks::mutator_lock_);
8606};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008607
Vladimir Markoc7993d52021-01-27 15:20:56 +00008608// We use the following order of field types for assigning offsets.
8609// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008610enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008611 kReference = 0u,
8612 kLong,
8613 kDouble,
8614 kInt,
8615 kFloat,
8616 kChar,
8617 kShort,
8618 kBoolean,
8619 kByte,
8620
8621 kLast64BitType = kDouble,
8622 kLast32BitType = kFloat,
8623 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008624};
8625
Vladimir Markoc7993d52021-01-27 15:20:56 +00008626ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008627ClassLinker::LinkFieldsHelper::FieldTypeOrder
8628ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008629 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008630 case 'J':
8631 return FieldTypeOrder::kLong;
8632 case 'D':
8633 return FieldTypeOrder::kDouble;
8634 case 'I':
8635 return FieldTypeOrder::kInt;
8636 case 'F':
8637 return FieldTypeOrder::kFloat;
8638 case 'C':
8639 return FieldTypeOrder::kChar;
8640 case 'S':
8641 return FieldTypeOrder::kShort;
8642 case 'Z':
8643 return FieldTypeOrder::kBoolean;
8644 case 'B':
8645 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008646 default:
8647 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8648 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008649 }
8650}
8651
8652// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008653class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008654 public:
8655 template <uint32_t kSize>
8656 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8657 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8658 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8659 uint32_t gap_start = field_offset.Uint32Value();
8660 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8661 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8662 }
8663 return field_offset;
8664 }
8665
8666 template <uint32_t kSize>
8667 bool HasGap() const {
8668 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8669 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8670 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8671 gap4_offset_ != kNoOffset;
8672 }
8673
8674 template <uint32_t kSize>
8675 MemberOffset ReleaseGap() {
8676 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8677 uint32_t result;
8678 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8679 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8680 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8681 result = gap1_offset_;
8682 gap1_offset_ = kNoOffset;
8683 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8684 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8685 result = gap2_offset_;
8686 gap2_offset_ = kNoOffset;
8687 if (kSize < 2u) {
8688 AddGaps<1u>(result + kSize, result + 2u);
8689 }
8690 } else {
8691 DCHECK_NE(gap4_offset_, kNoOffset);
8692 result = gap4_offset_;
8693 gap4_offset_ = kNoOffset;
8694 if (kSize < 4u) {
8695 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8696 }
8697 }
8698 return MemberOffset(result);
8699 }
8700
8701 private:
8702 template <uint32_t kGapsToCheck>
8703 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8704 if ((kGapsToCheck & 1u) != 0u) {
8705 DCHECK_LT(gap_start, gap_end);
8706 DCHECK_ALIGNED(gap_end, 2u);
8707 if ((gap_start & 1u) != 0u) {
8708 DCHECK_EQ(gap1_offset_, kNoOffset);
8709 gap1_offset_ = gap_start;
8710 gap_start += 1u;
8711 if (kGapsToCheck == 1u || gap_start == gap_end) {
8712 DCHECK_EQ(gap_start, gap_end);
8713 return;
8714 }
8715 }
8716 }
8717
8718 if ((kGapsToCheck & 2u) != 0u) {
8719 DCHECK_LT(gap_start, gap_end);
8720 DCHECK_ALIGNED(gap_start, 2u);
8721 DCHECK_ALIGNED(gap_end, 4u);
8722 if ((gap_start & 2u) != 0u) {
8723 DCHECK_EQ(gap2_offset_, kNoOffset);
8724 gap2_offset_ = gap_start;
8725 gap_start += 2u;
8726 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8727 DCHECK_EQ(gap_start, gap_end);
8728 return;
8729 }
8730 }
8731 }
8732
8733 if ((kGapsToCheck & 4u) != 0u) {
8734 DCHECK_LT(gap_start, gap_end);
8735 DCHECK_ALIGNED(gap_start, 4u);
8736 DCHECK_ALIGNED(gap_end, 8u);
8737 DCHECK_EQ(gap_start + 4u, gap_end);
8738 DCHECK_EQ(gap4_offset_, kNoOffset);
8739 gap4_offset_ = gap_start;
8740 return;
8741 }
8742
8743 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8744 << " after checking " << kGapsToCheck;
8745 }
8746
8747 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8748
8749 uint32_t gap4_offset_ = kNoOffset;
8750 uint32_t gap2_offset_ = kNoOffset;
8751 uint32_t gap1_offset_ = kNoOffset;
8752};
8753
8754template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008755ALWAYS_INLINE
8756MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8757 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008758 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8759 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8760 field->SetOffset(field_offset);
8761 return MemberOffset(field_offset.Uint32Value() + kSize);
8762}
8763
Vladimir Marko42bee502021-01-28 14:58:35 +00008764bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8765 Thread* self,
8766 Handle<mirror::Class> klass,
8767 bool is_static,
8768 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008769 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008770 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008771 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8772 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008773
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008774 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008775 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008776 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008777 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8778 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008779 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008780 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008781 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008782 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008783 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008784 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008785 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008786 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008787
David Sehr709b0702016-10-13 09:12:37 -07008788 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008789
Brian Carlstromdbc05252011-09-09 01:59:59 -07008790 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008791 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008792 //
8793 // The overall sort order order is:
8794 // 1) All object reference fields, sorted alphabetically.
8795 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8796 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8797 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8798 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8799 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8800 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8801 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8802 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8803 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008804 // (References are first to increase the chance of reference visiting
8805 // being able to take a fast path using a bitmap of references at the
8806 // start of the object, see `Class::reference_instance_offsets_`.)
8807 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008808 // Once the fields are sorted in this order we will attempt to fill any gaps
8809 // that might be present in the memory layout of the structure.
8810 // Note that we shall not fill gaps between the superclass fields.
8811
8812 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008813 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008814 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008815 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8816 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8817 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8818 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008819 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008820 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008821 } else {
8822 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008823 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008824 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008825 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008826 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008827 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008828 for (size_t i = 0; i != num_fields; ++i) {
8829 ArtField* field = &fields->At(i);
8830 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008831 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8832 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008833 // Insert references to the start, other fields to the end.
8834 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008835 if (field_type_order == FieldTypeOrder::kReference) {
8836 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008837 ++num_reference_fields;
8838 } else {
8839 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008840 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008841 }
8842 }
8843 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008844
Vladimir Marko42bee502021-01-28 14:58:35 +00008845 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008846 DCHECK(std::is_sorted(
8847 sorted_fields.begin(),
8848 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008849 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8850 ArtField* lhs_field = &fields->At(lhs.field_index);
8851 ArtField* rhs_field = &fields->At(rhs.field_index);
8852 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8853 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8854 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8855 lhs.field_index < rhs.field_index);
8856 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008857 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008858 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008859 DCHECK(std::is_sorted(
8860 sorted_fields.begin() + primitive_fields_start,
8861 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008862 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8863 ArtField* lhs_field = &fields->At(lhs.field_index);
8864 ArtField* rhs_field = &fields->At(rhs.field_index);
8865 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8866 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8867 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8868 lhs.field_index > rhs.field_index);
8869 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008870 }));
8871 // Sort the primitive fields by the field type order, then field index.
8872 std::sort(sorted_fields.begin() + primitive_fields_start,
8873 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008874 [](const auto& lhs, const auto& rhs) {
8875 if (lhs.field_type_order != rhs.field_type_order) {
8876 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008877 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008878 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008879 }
8880 });
8881 // Primitive fields are now sorted by field size (descending), then type, then field index.
8882 DCHECK(std::is_sorted(
8883 sorted_fields.begin() + primitive_fields_start,
8884 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008885 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8886 ArtField* lhs_field = &fields->At(lhs.field_index);
8887 ArtField* rhs_field = &fields->At(rhs.field_index);
8888 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008889 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008890 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008891 CHECK_NE(rhs_type, Primitive::kPrimNot);
8892 if (lhs_type != rhs_type) {
8893 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8894 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8895 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8896 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008897 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008898 }
8899 }));
8900
8901 // Process reference fields.
8902 FieldGaps field_gaps;
8903 size_t index = 0u;
8904 if (num_reference_fields != 0u) {
8905 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8906 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8907 for (; index != num_reference_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008908 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008909 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008910 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008911 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008912 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008913 if (index != num_fields &&
8914 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008915 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008916 while (index != num_fields &&
8917 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8918 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008919 field_offset = AssignFieldOffset<8u>(field, field_offset);
8920 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008921 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008922 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008923 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008924 if (index != num_fields &&
8925 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008926 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8927 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008928 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008929 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8930 ++index;
8931 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8932 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008933 while (index != num_fields &&
8934 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8935 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008936 field_offset = AssignFieldOffset<4u>(field, field_offset);
8937 ++index;
8938 }
8939 }
8940 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008941 if (index != num_fields &&
8942 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008943 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8944 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008945 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008946 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008947 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008948 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8949 ++index;
8950 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008951 while (index != num_fields &&
8952 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8953 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008954 field_offset = AssignFieldOffset<2u>(field, field_offset);
8955 ++index;
8956 }
8957 }
8958 // Process 8-bit fields.
8959 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008960 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008961 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8962 }
8963 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008964 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008965 field_offset = AssignFieldOffset<1u>(field, field_offset);
8966 }
8967
Ian Rogers7b078e82014-09-10 14:44:24 -07008968 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008969
Elliott Hughesadb460d2011-10-05 17:02:34 -07008970 // 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 +00008971 DCHECK_IMPLIES(class_linker->init_done_, !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
Vladimir Marko42bee502021-01-28 14:58:35 +00008972 if (!is_static &&
8973 UNLIKELY(!class_linker->init_done_) &&
8974 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008975 // We know there are no non-reference fields in the Reference classes, and we know
8976 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008977 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008978 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008979 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008980 --num_reference_fields;
8981 }
8982
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008983 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008984 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008985 if (is_static) {
8986 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008987 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008988 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008989 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008990 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008991 if (num_reference_fields == 0 || super_class == nullptr) {
8992 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008993 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008994 if (super_class == nullptr ||
8995 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8996 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008997 }
8998 }
8999 if (kIsDebugBuild) {
9000 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
9001 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009002 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07009003 while (cur_super != nullptr) {
9004 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
9005 cur_super = cur_super->GetSuperClass();
9006 }
9007 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07009008 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07009009 } else {
9010 // Check that there is at least num_reference_fields other than Object.class.
9011 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07009012 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07009013 }
9014 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07009015 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07009016 std::string temp;
9017 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
9018 size_t previous_size = klass->GetObjectSize();
9019 if (previous_size != 0) {
9020 // Make sure that we didn't originally have an incorrect size.
9021 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07009022 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07009023 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009024 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009025 }
Vladimir Marko76649e82014-11-10 18:32:59 +00009026
9027 if (kIsDebugBuild) {
9028 // Make sure that the fields array is ordered by name but all reference
9029 // offsets are at the beginning as far as alignment allows.
9030 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00009031 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00009032 : klass->GetFirstReferenceInstanceFieldOffset();
9033 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
9034 num_reference_fields *
9035 sizeof(mirror::HeapReference<mirror::Object>));
9036 MemberOffset current_ref_offset = start_ref_offset;
9037 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07009038 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009039 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07009040 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
9041 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00009042 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07009043 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00009044 // NOTE: The field names can be the same. This is not possible in the Java language
9045 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07009046 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00009047 }
9048 Primitive::Type type = field->GetTypeAsPrimitiveType();
9049 bool is_primitive = type != Primitive::kPrimNot;
9050 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
9051 strcmp("referent", field->GetName()) == 0) {
9052 is_primitive = true; // We lied above, so we have to expect a lie here.
9053 }
9054 MemberOffset offset = field->GetOffsetDuringLinking();
9055 if (is_primitive) {
9056 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
9057 // Shuffled before references.
9058 size_t type_size = Primitive::ComponentSize(type);
9059 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
9060 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
9061 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
9062 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
9063 }
9064 } else {
9065 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
9066 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
9067 sizeof(mirror::HeapReference<mirror::Object>));
9068 }
9069 }
9070 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
9071 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009072 return true;
9073}
9074
Vladimir Marko42bee502021-01-28 14:58:35 +00009075bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
9076 CHECK(klass != nullptr);
9077 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
9078}
9079
9080bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
9081 CHECK(klass != nullptr);
9082 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
9083}
9084
Vladimir Marko76649e82014-11-10 18:32:59 +00009085// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07009086void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009087 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009088 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009089 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009090 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009091 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009092 // Compute reference offsets unless our superclass overflowed.
9093 if (reference_offsets != mirror::Class::kClassWalkSuper) {
9094 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00009095 if (num_reference_fields != 0u) {
9096 // All of the fields that contain object references are guaranteed be grouped in memory
9097 // starting at an appropriately aligned address after super class object data.
9098 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
9099 sizeof(mirror::HeapReference<mirror::Object>));
9100 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009101 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00009102 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009103 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009104 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00009105 reference_offsets |= (0xffffffffu << start_bit) &
9106 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07009107 }
9108 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07009109 }
9110 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07009111 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009112}
9113
Vladimir Marko18090d12018-06-01 16:53:12 +01009114ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
9115 ObjPtr<mirror::DexCache> dex_cache) {
9116 StackHandleScope<1> hs(Thread::Current());
9117 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
9118 return DoResolveString(string_idx, h_dex_cache);
9119}
9120
9121ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
9122 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00009123 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07009124 uint32_t utf16_length;
9125 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009126 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00009127 if (string != nullptr) {
9128 dex_cache->SetResolvedString(string_idx, string);
9129 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00009130 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009131}
9132
Vladimir Marko18090d12018-06-01 16:53:12 +01009133ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
9134 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009135 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00009136 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00009137 uint32_t utf16_length;
9138 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08009139 ObjPtr<mirror::String> string =
9140 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00009141 if (string != nullptr) {
9142 dex_cache->SetResolvedString(string_idx, string);
9143 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00009144 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00009145}
9146
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009147ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01009148 ObjPtr<mirror::Class> referrer) {
9149 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
9150}
9151
9152ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009153 ObjPtr<mirror::DexCache> dex_cache,
9154 ObjPtr<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009155 DCHECK(dex_cache->GetClassLoader() == class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009156 const DexFile& dex_file = *dex_cache->GetDexFile();
9157 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Vladimir Markoc63d9672021-03-31 15:50:39 +01009158 ObjPtr<mirror::Class> type = LookupResolvedType(descriptor, class_loader);
9159 if (type != nullptr) {
9160 DCHECK(type->IsResolved());
9161 dex_cache->SetResolvedType(type_idx, type);
9162 }
9163 return type;
9164}
9165
9166ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const char* descriptor,
9167 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009168 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
9169 ObjPtr<mirror::Class> type = nullptr;
9170 if (descriptor[1] == '\0') {
9171 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
9172 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00009173 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009174 } else {
9175 Thread* const self = Thread::Current();
9176 DCHECK(self != nullptr);
9177 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
9178 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01009179 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009180 }
Vladimir Markoc63d9672021-03-31 15:50:39 +01009181 return (type != nullptr && type->IsResolved()) ? type : nullptr;
Mathieu Chartierb8901302016-09-30 10:27:43 -07009182}
9183
Andreas Gampeb0625e02019-05-01 12:43:31 -07009184template <typename RefType>
9185ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01009186 StackHandleScope<2> hs(Thread::Current());
9187 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9188 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
9189 return DoResolveType(type_idx, dex_cache, class_loader);
9190}
9191
Andreas Gampe4835d212018-11-21 14:55:10 -08009192// Instantiate the above.
9193template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9194 ArtField* referrer);
9195template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9196 ArtMethod* referrer);
9197template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9198 ObjPtr<mirror::Class> referrer);
9199
Vladimir Marko09c5ca42018-05-31 15:15:31 +01009200ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009201 Handle<mirror::DexCache> dex_cache,
9202 Handle<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009203 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009204 Thread* self = Thread::Current();
9205 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
9206 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
9207 if (resolved != nullptr) {
9208 // TODO: we used to throw here if resolved's class loader was not the
9209 // boot class loader. This was to permit different classes with the
9210 // same name to be loaded simultaneously by different loaders
9211 dex_cache->SetResolvedType(type_idx, resolved);
9212 } else {
9213 CHECK(self->IsExceptionPending())
9214 << "Expected pending exception for failed resolution of: " << descriptor;
9215 // Convert a ClassNotFoundException to a NoClassDefFoundError.
9216 StackHandleScope<1> hs(self);
9217 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009218 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009219 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
9220 self->ClearException();
9221 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
9222 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009223 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009224 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00009225 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07009226 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00009227 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009228}
9229
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009230ArtMethod* ClassLinker::FindResolvedMethod(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);
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009235 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
9236 // functions can optimize the search if the dex_cache is the same as the DexCache
9237 // of the class, with fall-back to name and signature search otherwise.
9238 ArtMethod* resolved = nullptr;
9239 if (klass->IsInterface()) {
9240 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9241 } else {
9242 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9243 }
9244 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009245 if (resolved != nullptr &&
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009246 // We pass AccessMethod::kNone instead of kLinking to not warn yet on the
9247 // access, as we'll be looking if the method can be accessed through an
9248 // interface.
David Brazdilf50ac102018-10-17 18:00:06 +01009249 hiddenapi::ShouldDenyAccessToMember(resolved,
9250 hiddenapi::AccessContext(class_loader, dex_cache),
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009251 hiddenapi::AccessMethod::kNone)) {
9252 // The resolved method that we have found cannot be accessed due to
9253 // hiddenapi (typically it is declared up the hierarchy and is not an SDK
9254 // method). Try to find an interface method from the implemented interfaces which is
Nicolas Geoffrayaf61f502021-03-31 16:03:50 +00009255 // part of the SDK.
9256 ArtMethod* itf_method = klass->FindAccessibleInterfaceMethod(resolved, image_pointer_size_);
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009257 if (itf_method == nullptr) {
9258 // No interface method. Call ShouldDenyAccessToMember again but this time
9259 // with AccessMethod::kLinking to ensure that an appropriate warning is
9260 // logged.
9261 hiddenapi::ShouldDenyAccessToMember(resolved,
9262 hiddenapi::AccessContext(class_loader, dex_cache),
9263 hiddenapi::AccessMethod::kLinking);
9264 resolved = nullptr;
9265 } else {
9266 // We found an interface method that is accessible, continue with the resolved method.
9267 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009268 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009269 if (resolved != nullptr) {
9270 // In case of jmvti, the dex file gets verified before being registered, so first
9271 // check if it's registered before checking class tables.
9272 const DexFile& dex_file = *dex_cache->GetDexFile();
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00009273 DCHECK_IMPLIES(
9274 IsDexFileRegistered(Thread::Current(), dex_file),
9275 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009276 << "DexFile referrer: " << dex_file.GetLocation()
9277 << " ClassLoader: " << DescribeLoaders(class_loader, "");
9278 // Be a good citizen and update the dex cache to speed subsequent calls.
David Srbecky5de5efe2021-02-15 21:23:00 +00009279 dex_cache->SetResolvedMethod(method_idx, resolved);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009280 // Disable the following invariant check as the verifier breaks it. b/73760543
9281 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
9282 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
9283 // << "Method: " << resolved->PrettyMethod() << ", "
9284 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
9285 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009286 }
9287 return resolved;
9288}
9289
David Brazdil4525e0b2018-04-05 16:57:32 +01009290// Returns true if `method` is either null or hidden.
9291// Does not print any warnings if it is hidden.
9292static bool CheckNoSuchMethod(ArtMethod* method,
9293 ObjPtr<mirror::DexCache> dex_cache,
9294 ObjPtr<mirror::ClassLoader> class_loader)
9295 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009296 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
David Brazdil4525e0b2018-04-05 16:57:32 +01009297 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01009298 hiddenapi::ShouldDenyAccessToMember(method,
9299 hiddenapi::AccessContext(class_loader, dex_cache),
9300 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01009301}
9302
9303ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
9304 ObjPtr<mirror::DexCache> dex_cache,
9305 ObjPtr<mirror::ClassLoader> class_loader,
9306 uint32_t method_idx) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009307 DCHECK(dex_cache->GetClassLoader() == class_loader);
David Brazdil4525e0b2018-04-05 16:57:32 +01009308 if (klass->IsInterface()) {
9309 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9310 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
9311 } else {
9312 // If there was an interface method with the same signature, we would have
9313 // found it in the "copied" methods. Only DCHECK that the interface method
9314 // really does not exist.
9315 if (kIsDebugBuild) {
9316 ArtMethod* method =
9317 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
Nicolas Geoffray24642182022-02-14 14:40:51 +00009318 CHECK(CheckNoSuchMethod(method, dex_cache, class_loader) ||
9319 (klass->FindAccessibleInterfaceMethod(method, image_pointer_size_) == nullptr));
David Brazdil4525e0b2018-04-05 16:57:32 +01009320 }
9321 return nullptr;
9322 }
9323}
9324
Vladimir Marko89011192017-12-11 13:45:05 +00009325ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009326 Handle<mirror::DexCache> dex_cache,
9327 Handle<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009328 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
David Srbecky5de5efe2021-02-15 21:23:00 +00009329 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009330 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009331 if (resolved != nullptr) {
9332 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009333 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9334 return resolved;
9335 }
9336 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009337 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009338 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009339 if (klass == nullptr) {
9340 Thread::Current()->AssertPendingException();
9341 return nullptr;
9342 }
9343 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009344 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9345 } else {
9346 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009347 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009348 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009349 hiddenapi::ShouldDenyAccessToMember(
9350 resolved,
9351 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9352 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009353 resolved = nullptr;
9354 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009355 return resolved;
9356}
9357
Vladimir Markof44d36c2017-03-14 14:18:46 +00009358ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9359 ObjPtr<mirror::DexCache> dex_cache,
9360 ObjPtr<mirror::ClassLoader> class_loader,
9361 bool is_static) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009362 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009363 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009364 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009365 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9366 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009367 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009368 }
9369 if (klass == nullptr) {
9370 // The class has not been resolved yet, so the field is also unresolved.
9371 return nullptr;
9372 }
9373 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009374
David Brazdil1ab0fa82018-05-04 11:28:03 +01009375 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009376}
9377
Vladimir Markoe11dd502017-12-08 14:09:45 +00009378ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009379 Handle<mirror::DexCache> dex_cache,
9380 Handle<mirror::ClassLoader> class_loader) {
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());
David Srbecky5de5efe2021-02-15 21:23:00 +00009383 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009384 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009385 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009386 return resolved;
9387 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009388 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009389 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009390 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009391 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009392 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009393 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009394 }
9395
David Brazdil1ab0fa82018-05-04 11:28:03 +01009396 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9397 if (resolved == nullptr) {
9398 const char* name = dex_file.GetFieldName(field_id);
9399 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009400 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009401 }
9402 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009403}
9404
David Brazdil1ab0fa82018-05-04 11:28:03 +01009405ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9406 ObjPtr<mirror::DexCache> dex_cache,
9407 ObjPtr<mirror::ClassLoader> class_loader,
9408 uint32_t field_idx,
9409 bool is_static) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009410 DCHECK(dex_cache->GetClassLoader() == class_loader);
Vladimir Markob10668c2021-06-10 09:52:53 +01009411 ArtField* resolved = is_static ? klass->FindStaticField(dex_cache, field_idx)
9412 : klass->FindInstanceField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009413 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009414 hiddenapi::ShouldDenyAccessToMember(resolved,
9415 hiddenapi::AccessContext(class_loader, dex_cache),
9416 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009417 resolved = nullptr;
9418 }
9419
9420 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009421 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009422 }
9423
9424 return resolved;
9425}
9426
9427ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9428 ObjPtr<mirror::DexCache> dex_cache,
9429 ObjPtr<mirror::ClassLoader> class_loader,
9430 uint32_t field_idx) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009431 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
Vladimir Markob10668c2021-06-10 09:52:53 +01009432 ArtField* resolved = klass->FindField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009433
9434 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009435 hiddenapi::ShouldDenyAccessToMember(resolved,
9436 hiddenapi::AccessContext(class_loader, dex_cache),
9437 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009438 resolved = nullptr;
9439 }
9440
9441 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009442 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009443 }
9444
9445 return resolved;
9446}
9447
Vladimir Markoaf940202017-12-08 15:01:18 +00009448ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9449 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009450 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009451 Handle<mirror::DexCache> dex_cache,
9452 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009453 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009454 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009455 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
Narayan Kamath25352fc2016-08-03 12:46:58 +01009456
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009457 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009458 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009459 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009460 }
9461
Narayan Kamath25352fc2016-08-03 12:46:58 +01009462 StackHandleScope<4> hs(self);
9463
9464 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009465 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009466 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009467 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009468 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009469 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009470 DCHECK(self->IsExceptionPending());
9471 return nullptr;
9472 }
9473
9474 // Then resolve the argument types.
9475 //
9476 // TODO: Is there a better way to figure out the number of method arguments
9477 // other than by looking at the shorty ?
9478 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9479
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009480 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009481 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9482 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009483 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009484 DCHECK(self->IsExceptionPending());
9485 return nullptr;
9486 }
9487
9488 DexFileParameterIterator it(dex_file, proto_id);
9489 int32_t i = 0;
9490 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9491 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009492 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009493 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009494 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009495 DCHECK(self->IsExceptionPending());
9496 return nullptr;
9497 }
9498
9499 method_params->Set(i++, param_class.Get());
9500 }
9501
9502 DCHECK(!it.HasNext());
9503
9504 Handle<mirror::MethodType> type = hs.NewHandle(
9505 mirror::MethodType::Create(self, return_type, method_params));
Nicolas Geoffray4aebd582021-07-23 15:27:31 +01009506 if (type != nullptr) {
9507 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9508 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01009509
9510 return type.Get();
9511}
9512
Vladimir Markoaf940202017-12-08 15:01:18 +00009513ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009514 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009515 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009516 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009517 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9518 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009519 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009520}
9521
Vladimir Marko5aead702019-03-27 11:00:36 +00009522ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009523 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009524 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009525 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009526 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009527 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9528 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009529 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009530 bool is_static;
9531 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009532 switch (handle_type) {
9533 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009534 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009535 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009536 is_static = true;
9537 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009538 break;
9539 }
9540 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009541 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009542 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009543 is_static = true;
9544 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009545 break;
9546 }
9547 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009548 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009549 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009550 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009551 num_params = 2;
9552 break;
9553 }
9554 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009555 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009556 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009557 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009558 num_params = 1;
9559 break;
9560 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009561 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009562 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009563 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009564 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009565 case DexFile::MethodHandleType::kInvokeInterface:
9566 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009567 }
9568
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009569 ArtField* target_field =
9570 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9571 if (LIKELY(target_field != nullptr)) {
9572 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9573 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9574 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9575 ThrowIllegalAccessErrorField(referring_class, target_field);
9576 return nullptr;
9577 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009578 if (UNLIKELY(is_put && target_field->IsFinal())) {
9579 ThrowIllegalAccessErrorField(referring_class, target_field);
9580 return nullptr;
9581 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009582 } else {
9583 DCHECK(Thread::Current()->IsExceptionPending());
9584 return nullptr;
9585 }
9586
9587 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009588 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009589 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9590 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009591 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009592 DCHECK(self->IsExceptionPending());
9593 return nullptr;
9594 }
9595
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009596 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009597 Handle<mirror::Class> return_type;
9598 switch (handle_type) {
9599 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009600 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009601 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009602 break;
9603 }
9604 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009605 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009606 break;
9607 }
9608 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009609 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009610 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009611 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009612 break;
9613 }
9614 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009615 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009616 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009617 break;
9618 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009619 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009620 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009621 case DexFile::MethodHandleType::kInvokeConstructor:
9622 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009623 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009624 UNREACHABLE();
9625 }
9626
9627 for (int32_t i = 0; i < num_params; ++i) {
9628 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9629 DCHECK(self->IsExceptionPending());
9630 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009631 }
9632 }
9633
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009634 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009635 DCHECK(self->IsExceptionPending());
9636 return nullptr;
9637 }
9638
9639 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009640 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9641 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009642 DCHECK(self->IsExceptionPending());
9643 return nullptr;
9644 }
Orion Hodson631827d2017-04-10 14:53:47 +01009645
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009646 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9647 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9648}
9649
Vladimir Marko5aead702019-03-27 11:00:36 +00009650ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009651 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009652 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009653 ArtMethod* referrer) {
9654 DexFile::MethodHandleType handle_type =
9655 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9656 mirror::MethodHandle::Kind kind;
9657 uint32_t receiver_count = 0;
9658 ArtMethod* target_method = nullptr;
9659 switch (handle_type) {
9660 case DexFile::MethodHandleType::kStaticPut:
9661 case DexFile::MethodHandleType::kStaticGet:
9662 case DexFile::MethodHandleType::kInstancePut:
9663 case DexFile::MethodHandleType::kInstanceGet:
9664 UNREACHABLE();
9665 case DexFile::MethodHandleType::kInvokeStatic: {
9666 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9667 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009668 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9669 method_handle.field_or_method_idx_,
9670 referrer,
9671 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009672 break;
9673 }
9674 case DexFile::MethodHandleType::kInvokeInstance: {
9675 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9676 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009677 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9678 method_handle.field_or_method_idx_,
9679 referrer,
9680 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009681 break;
9682 }
9683 case DexFile::MethodHandleType::kInvokeConstructor: {
9684 // Constructors are currently implemented as a transform. They
9685 // are special cased later in this method.
9686 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9687 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009688 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9689 method_handle.field_or_method_idx_,
9690 referrer,
9691 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009692 break;
9693 }
9694 case DexFile::MethodHandleType::kInvokeDirect: {
9695 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9696 receiver_count = 1;
9697 StackHandleScope<2> hs(self);
9698 // A constant method handle with type kInvokeDirect can refer to
9699 // a method that is private or to a method in a super class. To
9700 // disambiguate the two options, we resolve the method ignoring
9701 // the invocation type to determine if the method is private. We
9702 // then resolve again specifying the intended invocation type to
9703 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009704 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009705 hs.NewHandle(referrer->GetDexCache()),
9706 hs.NewHandle(referrer->GetClassLoader()));
9707 if (UNLIKELY(target_method == nullptr)) {
9708 break;
9709 }
9710
9711 if (target_method->IsPrivate()) {
9712 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009713 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9714 method_handle.field_or_method_idx_,
9715 referrer,
9716 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009717 } else {
9718 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009719 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9720 method_handle.field_or_method_idx_,
9721 referrer,
9722 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009723 if (UNLIKELY(target_method == nullptr)) {
9724 break;
9725 }
9726 // Find the method specified in the parent in referring class
9727 // so invoke-super invokes the method in the parent of the
9728 // referrer.
9729 target_method =
9730 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9731 kRuntimePointerSize);
9732 }
9733 break;
9734 }
9735 case DexFile::MethodHandleType::kInvokeInterface: {
9736 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9737 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009738 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9739 method_handle.field_or_method_idx_,
9740 referrer,
9741 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009742 break;
9743 }
Orion Hodson631827d2017-04-10 14:53:47 +01009744 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009745
9746 if (UNLIKELY(target_method == nullptr)) {
9747 DCHECK(Thread::Current()->IsExceptionPending());
9748 return nullptr;
9749 }
9750
9751 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9752 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9753 uint32_t access_flags = target_method->GetAccessFlags();
9754 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9755 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9756 return nullptr;
9757 }
9758
9759 // Calculate the number of parameters from the method shorty. We add the
9760 // receiver count (0 or 1) and deduct one for the return value.
9761 uint32_t shorty_length;
9762 target_method->GetShorty(&shorty_length);
9763 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9764
Orion Hodsonecd58562018-09-24 11:27:33 +01009765 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009766 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009767 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9768 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9769 if (method_params.Get() == nullptr) {
9770 DCHECK(self->IsExceptionPending());
9771 return nullptr;
9772 }
9773
Orion Hodsonecd58562018-09-24 11:27:33 +01009774 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009775 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009776 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009777 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009778 // Insert receiver. Use the class identified in the method handle rather than the declaring
9779 // class of the resolved method which may be super class or default interface method
9780 // (b/115964401).
9781 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9782 // receiver_class should have been resolved when resolving the target method.
9783 DCHECK(receiver_class != nullptr);
9784 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009785 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009786
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009787 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009788 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009789 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009790 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009791 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009792 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009793 if (nullptr == klass) {
9794 DCHECK(self->IsExceptionPending());
9795 return nullptr;
9796 }
9797 method_params->Set(index++, klass);
9798 it.Next();
9799 }
9800
Orion Hodsonecd58562018-09-24 11:27:33 +01009801 Handle<mirror::Class> return_type =
9802 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009803 if (UNLIKELY(return_type.IsNull())) {
9804 DCHECK(self->IsExceptionPending());
9805 return nullptr;
9806 }
9807
9808 Handle<mirror::MethodType>
9809 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9810 if (UNLIKELY(method_type.IsNull())) {
9811 DCHECK(self->IsExceptionPending());
9812 return nullptr;
9813 }
9814
9815 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9816 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9817 Handle<mirror::MethodHandlesLookup> lookup =
9818 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9819 return lookup->FindConstructor(self, constructor_class, method_type);
9820 }
9821
9822 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9823 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9824}
9825
Vladimir Markoaf940202017-12-08 15:01:18 +00009826ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9827 uint32_t method_handle_idx,
9828 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009829 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009830 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009831 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009832 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9833 case DexFile::MethodHandleType::kStaticPut:
9834 case DexFile::MethodHandleType::kStaticGet:
9835 case DexFile::MethodHandleType::kInstancePut:
9836 case DexFile::MethodHandleType::kInstanceGet:
9837 return ResolveMethodHandleForField(self, method_handle, referrer);
9838 case DexFile::MethodHandleType::kInvokeStatic:
9839 case DexFile::MethodHandleType::kInvokeInstance:
9840 case DexFile::MethodHandleType::kInvokeConstructor:
9841 case DexFile::MethodHandleType::kInvokeDirect:
9842 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009843 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009844 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009845}
9846
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009847bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9848 return (entry_point == GetQuickResolutionStub()) ||
9849 (quick_resolution_trampoline_ == entry_point);
9850}
9851
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009852bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9853 return (entry_point == GetQuickToInterpreterBridge()) ||
9854 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9855}
9856
9857bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9858 return (entry_point == GetQuickGenericJniStub()) ||
9859 (quick_generic_jni_trampoline_ == entry_point);
9860}
9861
David Sehra49e0532017-08-25 08:05:29 -07009862bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009863 return entry_point == GetJniDlsymLookupStub() ||
9864 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009865}
9866
Vladimir Markofa458ac2020-02-12 14:08:07 +00009867bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9868 return entry_point == GetJniDlsymLookupCriticalStub() ||
9869 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9870}
9871
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009872const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9873 return GetQuickGenericJniStub();
9874}
9875
Alex Lightdb01a092017-04-03 15:39:55 -07009876void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9877 DCHECK(method->IsObsolete());
9878 // We cannot mess with the entrypoints of native methods because they are used to determine how
9879 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9880 if (!method->IsNative()) {
9881 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9882 }
9883}
9884
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009885void ClassLinker::DumpForSigQuit(std::ostream& os) {
Hans Boehmfb3ad722021-08-16 16:53:17 +00009886 ScopedObjectAccess soa(Thread::Current());
9887 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009888 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9889 << NumNonZygoteClasses() << "\n";
Hans Boehmfb3ad722021-08-16 16:53:17 +00009890 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009891 os << "Dumping registered class loaders\n";
9892 size_t class_loader_index = 0;
9893 for (const ClassLoaderData& class_loader : class_loaders_) {
9894 ObjPtr<mirror::ClassLoader> loader =
Hans Boehmfb3ad722021-08-16 16:53:17 +00009895 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009896 if (loader != nullptr) {
9897 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9898 bool saw_one_dex_file = false;
David Srbecky6fbcc292021-02-23 01:05:32 +00009899 for (const auto& entry : dex_caches_) {
9900 const DexCacheData& dex_cache = entry.second;
9901 if (dex_cache.class_table == class_loader.class_table) {
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009902 if (saw_one_dex_file) {
9903 os << ":";
9904 }
9905 saw_one_dex_file = true;
David Srbecky6fbcc292021-02-23 01:05:32 +00009906 os << entry.first->GetLocation();
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009907 }
9908 }
9909 os << "]";
9910 bool found_parent = false;
9911 if (loader->GetParent() != nullptr) {
9912 size_t parent_index = 0;
9913 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9914 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
Hans Boehmfb3ad722021-08-16 16:53:17 +00009915 soa.Self()->DecodeJObject(class_loader2.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009916 if (loader2 == loader->GetParent()) {
9917 os << ", parent #" << parent_index;
9918 found_parent = true;
9919 break;
9920 }
9921 parent_index++;
9922 }
9923 if (!found_parent) {
9924 os << ", unregistered parent of type "
9925 << loader->GetParent()->GetClass()->PrettyDescriptor();
9926 }
9927 } else {
9928 os << ", no parent";
9929 }
9930 os << "\n";
9931 }
9932 }
9933 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009934 Runtime* runtime = Runtime::Current();
9935 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9936 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009937}
9938
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009939class CountClassesVisitor : public ClassLoaderVisitor {
9940 public:
9941 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9942
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009943 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009944 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009945 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009946 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009947 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9948 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009949 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009950 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009951
9952 size_t num_zygote_classes;
9953 size_t num_non_zygote_classes;
9954};
9955
9956size_t ClassLinker::NumZygoteClasses() const {
9957 CountClassesVisitor visitor;
9958 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009959 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009960}
9961
9962size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009963 CountClassesVisitor visitor;
9964 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009965 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009966}
9967
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009968size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009969 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009970 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009971 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009972}
9973
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009974pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009975 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009976}
9977
9978pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009979 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009980}
9981
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009982void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009983 DCHECK(!init_done_);
9984
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009985 DCHECK(klass != nullptr);
9986 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009987
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009988 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009989 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009990 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9991 int32_t index = static_cast<int32_t>(class_root);
9992 DCHECK(class_roots->Get(index) == nullptr);
9993 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009994}
9995
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009996ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9997 Thread* self,
9998 const std::vector<const DexFile*>& dex_files,
9999 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010000 Handle<mirror::ClassLoader> parent_loader,
Brad Stenning9c924e82021-10-11 19:09:00 -070010001 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries,
10002 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries_after) {
Calin Juravle7865ac72017-06-28 11:03:12 -070010003
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010004 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010005
Mathieu Chartierc7853442015-03-27 14:35:38 -070010006 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -080010007 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010008
Vladimir Marko4098a7a2017-11-06 16:00:51 +000010009 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -080010010 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010011 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070010012 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -070010013 mirror::ObjectArray<mirror::Object>::Alloc(self,
10014 dex_elements_class.Get(),
10015 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010016 Handle<mirror::Class> h_dex_element_class =
10017 hs.NewHandle(dex_elements_class->GetComponentType());
10018
Mathieu Chartierc7853442015-03-27 14:35:38 -070010019 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -080010020 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -070010021 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010022
Andreas Gampe08883de2016-11-08 13:20:52 -080010023 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +000010024 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010025
Andreas Gampe08883de2016-11-08 13:20:52 -080010026 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +000010027 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -080010028
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010029 // Fill the elements array.
10030 int32_t index = 0;
10031 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -080010032 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010033
Calin Juravle7865ac72017-06-28 11:03:12 -070010034 // CreateWellKnownClassLoader is only used by gtests and compiler.
10035 // 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 -070010036 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
10037 self,
10038 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -080010039 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +010010040 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010041
Mathieu Chartier3738e982017-05-12 16:07:28 -070010042 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
10043 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010044 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -070010045 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -080010046 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -070010047 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010048
Mathieu Chartierfbc31082016-01-24 11:59:56 -080010049 Handle<mirror::String> h_file_name = hs2.NewHandle(
10050 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -080010051 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -080010052 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
10053
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010054 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -080010055 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -070010056 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010057
10058 h_dex_elements->Set(index, h_element.Get());
10059 index++;
10060 }
10061 DCHECK_EQ(index, h_dex_elements->GetLength());
10062
10063 // Create DexPathList.
10064 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -070010065 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -080010066 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010067 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -070010068 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -080010069 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
10070 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
10071 // elements.
10072 {
10073 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
10074 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
10075 DCHECK(native_lib_dirs != nullptr);
10076 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
10077 DCHECK(list_class != nullptr);
10078 {
10079 StackHandleScope<1> h_list_scope(self);
10080 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
10081 bool list_init = EnsureInitialized(self, h_list_class, true, true);
10082 DCHECK(list_init);
10083 list_class = h_list_class.Get();
10084 }
10085 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
10086 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
10087 // is fine for testing. While it violates a Java-code invariant (the elementData field is
10088 // normally never null), as long as one does not try to add elements, this will still
10089 // work.
10090 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
10091 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010092
Calin Juravle7865ac72017-06-28 11:03:12 -070010093 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010094 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
10095 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -070010096 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010097 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -070010098 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -080010099 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -070010100 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -070010101 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010102
10103 // Make a pretend boot-classpath.
10104 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -070010105 ArtField* const parent_field =
Vladimir Markoe300c4e2021-06-08 16:00:05 +010010106 jni::DecodeArtField(WellKnownClasses::java_lang_ClassLoader_parent);
Roland Levillainf39c9eb2015-05-26 15:02:07 +010010107 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010108 if (parent_loader.Get() == nullptr) {
10109 ScopedObjectAccessUnchecked soa(self);
10110 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
10111 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
10112 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
10113 } else {
10114 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
10115 }
Calin Juravle7865ac72017-06-28 11:03:12 -070010116
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010117 ArtField* shared_libraries_field =
10118 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
10119 DCHECK(shared_libraries_field != nullptr);
10120 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
10121
Brad Stenning9c924e82021-10-11 19:09:00 -070010122 ArtField* shared_libraries_after_field =
10123 jni::DecodeArtField(
10124 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
10125 DCHECK(shared_libraries_after_field != nullptr);
10126 shared_libraries_after_field->SetObject<false>(h_class_loader.Get(),
10127 shared_libraries_after.Get());
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010128 return h_class_loader.Get();
10129}
10130
10131jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
10132 const std::vector<const DexFile*>& dex_files,
10133 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010134 jobject parent_loader,
Brad Stenning9c924e82021-10-11 19:09:00 -070010135 jobject shared_libraries,
10136 jobject shared_libraries_after) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010137 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
10138 WellKnownClasses::dalvik_system_PathClassLoader) ||
10139 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +000010140 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
10141 self->GetJniEnv()->IsSameObject(loader_class,
10142 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010143
10144 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
10145 // We could move the jobject to the callers, but all call-sites do this...
10146 ScopedObjectAccessUnchecked soa(self);
10147
10148 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Brad Stenning9c924e82021-10-11 19:09:00 -070010149 StackHandleScope<5> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010150
10151 Handle<mirror::Class> h_loader_class =
10152 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010153 Handle<mirror::ClassLoader> h_parent =
10154 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
10155 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
10156 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Brad Stenning9c924e82021-10-11 19:09:00 -070010157 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries_after =
10158 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries_after));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010159
10160 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
10161 self,
10162 dex_files,
10163 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010164 h_parent,
Brad Stenning9c924e82021-10-11 19:09:00 -070010165 h_shared_libraries,
10166 h_shared_libraries_after);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010167
10168 // Make it a global ref and return.
10169 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010170 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010171 return soa.Env()->NewGlobalRef(local_ref.get());
10172}
10173
Calin Juravle7865ac72017-06-28 11:03:12 -070010174jobject ClassLinker::CreatePathClassLoader(Thread* self,
10175 const std::vector<const DexFile*>& dex_files) {
10176 return CreateWellKnownClassLoader(self,
10177 dex_files,
10178 WellKnownClasses::dalvik_system_PathClassLoader,
10179 nullptr);
10180}
10181
Andreas Gampe8ac75952015-06-02 21:01:45 -070010182void ClassLinker::DropFindArrayClassCache() {
10183 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
10184 find_array_class_cache_next_victim_ = 0;
10185}
10186
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010187void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010188 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010189 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -070010190 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010191 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
10192 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010193 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +010010194 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010195 }
10196 }
10197}
10198
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010199void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10200 for (const ClassLoaderData& data : class_loaders_) {
10201 LinearAlloc* alloc = data.allocator;
10202 if (alloc != nullptr && !visitor->Visit(alloc)) {
10203 break;
10204 }
10205 }
10206}
10207
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010208void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10209 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010210 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010211 Thread* const self = Thread::Current();
10212 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010213 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010214 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010215 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010216 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10217 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010218 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010219 }
10220}
10221
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010222void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010223 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010224 std::vector<ClassLoaderData> to_delete;
10225 // Do the delete outside the lock to avoid lock violation in jit code cache.
10226 {
10227 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10228 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10229 const ClassLoaderData& data = *it;
10230 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010231 ObjPtr<mirror::ClassLoader> class_loader =
10232 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010233 if (class_loader != nullptr) {
10234 ++it;
10235 } else {
10236 VLOG(class_linker) << "Freeing class loader";
10237 to_delete.push_back(data);
10238 it = class_loaders_.erase(it);
10239 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010240 }
10241 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010242 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010243 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010244 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010245 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010246}
10247
Mathieu Chartier65975772016-08-05 10:46:36 -070010248class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10249 public:
10250 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10251 : method_(method),
10252 pointer_size_(pointer_size) {}
10253
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010254 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010255 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10256 holder_ = klass;
10257 }
10258 // Return false to stop searching if holder_ is not null.
10259 return holder_ == nullptr;
10260 }
10261
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010262 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010263 const ArtMethod* const method_;
10264 const PointerSize pointer_size_;
10265};
10266
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010267ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010268 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10269 CHECK(method->IsCopied());
10270 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10271 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010272 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010273}
10274
Calin Juravle33787682019-07-26 14:27:18 -070010275bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10276 REQUIRES_SHARED(Locks::mutator_lock_) {
10277 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10278 LOG(FATAL) << "UNREACHABLE";
10279 UNREACHABLE();
10280}
10281
10282bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10283 REQUIRES_SHARED(Locks::mutator_lock_) {
10284 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10285 LOG(FATAL) << "UNREACHABLE";
10286 UNREACHABLE();
10287}
10288
10289bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10290 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10291 LOG(FATAL) << "UNREACHABLE";
10292 UNREACHABLE();
10293}
10294
Calin Juravle2c2724c2021-01-14 19:54:23 -080010295void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10296 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10297 LOG(FATAL) << "UNREACHABLE";
10298 UNREACHABLE();
10299}
10300
Guo Li1ee02902022-07-13 15:57:31 +080010301void ClassLinker::RemoveDexFromCaches(const DexFile& dex_file) {
10302 ReaderMutexLock mu(Thread::Current(), *Locks::dex_lock_);
10303
10304 auto it = dex_caches_.find(&dex_file);
10305 if (it != dex_caches_.end()) {
10306 dex_caches_.erase(it);
10307 }
10308}
10309
Roland Levillain0e840272018-08-23 19:55:30 +010010310// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010311template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010312 Thread* self,
10313 ObjPtr<mirror::Class> java_lang_Class,
10314 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010315template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010316 Thread* self,
10317 ObjPtr<mirror::Class> java_lang_Class,
10318 uint32_t class_size);
10319
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010320} // namespace art