blob: 9538f8a1d47f5ebc768420d4c30d230b1ada9a67 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070019#include <unistd.h>
20
Alex Lighteb7c1442015-08-31 13:17:42 -070021#include <algorithm>
Brian Carlstromdbc05252011-09-09 01:59:59 -070022#include <deque>
Vladimir Markobf121912019-06-04 13:49:05 +010023#include <forward_list>
Ian Rogerscf7f1912014-10-22 22:06:39 -070024#include <iostream>
Vladimir Marko21300532017-01-24 18:06:55 +000025#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070026#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070027#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070028#include <string>
Andreas Gampe9f3928f2019-02-04 11:19:31 -080029#include <string_view>
Alex Lighteb7c1442015-08-31 13:17:42 -070030#include <tuple>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070031#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070032#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070033
Andreas Gampe46ee31b2016-12-14 10:11:49 -080034#include "android-base/stringprintf.h"
35
Mathieu Chartierc7853442015-03-27 14:35:38 -070036#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070037#include "art_method-inl.h"
Vladimir Markobf121912019-06-04 13:49:05 +010038#include "barrier.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070039#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080040#include "base/casts.h"
Andreas Gampe19f54162019-05-14 16:16:28 -070041#include "base/file_utils.h"
Vladimir Marko782fb712020-12-23 12:47:31 +000042#include "base/hash_map.h"
43#include "base/hash_set.h"
David Sehr67bf42e2018-02-26 16:43:04 -080044#include "base/leb128.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080045#include "base/logging.h"
Eric Holk74584e62021-02-18 14:39:17 -080046#include "base/metrics/metrics.h"
Vladimir Markobf121912019-06-04 13:49:05 +010047#include "base/mutex-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080048#include "base/os.h"
49#include "base/quasi_atomic.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070050#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010051#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080052#include "base/stl_util.h"
Vladimir Markob9c29f62019-03-20 14:22:51 +000053#include "base/string_view_cpp20.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080054#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010055#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080056#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080057#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070058#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070059#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070061#include "class_loader_utils.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010062#include "class_root-inl.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070063#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000064#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010065#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080066#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070067#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080068#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080069#include "dex/dex_file-inl.h"
70#include "dex/dex_file_exception_helpers.h"
71#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080072#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000073#include "dex/utf.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010074#include "entrypoints/entrypoint_utils-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070075#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070076#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070077#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080078#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000079#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070080#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070081#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070082#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070083#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000084#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070085#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070086#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070087#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080088#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070089#include "imt_conflict_table.h"
90#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070091#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070092#include "interpreter/interpreter.h"
Nicolas Geoffray0315efa2020-06-26 11:42:39 +010093#include "interpreter/mterp/nterp.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000094#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080095#include "jit/jit.h"
96#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010097#include "jni/java_vm_ext.h"
98#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070099#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -0700100#include "mirror/array-alloc-inl.h"
101#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000102#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -0700103#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800104#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700105#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -0700106#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800107#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -0700108#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700109#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100110#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700111#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800112#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700113#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100114#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000115#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700116#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800117#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000118#include "mirror/object-refvisitor-inl.h"
Alex Lighta9bbc082019-11-14 14:51:41 -0800119#include "mirror/object.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700120#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700121#include "mirror/object_array-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000122#include "mirror/object_array.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700123#include "mirror/object_reference.h"
124#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800125#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700126#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800127#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700128#include "mirror/string-inl.h"
Andreas Gampe501c3b02019-04-17 21:54:27 +0000129#include "mirror/throwable.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100130#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700131#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700132#include "nativehelper/scoped_local_ref.h"
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000133#include "nterp_helpers.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700134#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700135#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700136#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700137#include "oat_file_assistant.h"
138#include "oat_file_manager.h"
139#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700140#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700141#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800142#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700143#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700144#include "thread-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000145#include "thread.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700146#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700147#include "trace.h"
Vladimir Markob68bb7a2020-03-17 10:55:25 +0000148#include "transaction.h"
Nicolas Geoffray6df45112021-02-07 21:51:58 +0000149#include "vdex_file.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700150#include "verifier/class_verifier.h"
Nicolas Geoffray80789962021-04-30 16:50:39 +0100151#include "verifier/verifier_deps.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700152#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700153
154namespace art {
155
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800156using android::base::StringPrintf;
157
Orion Hodson5880c772020-07-28 20:12:08 +0100158static constexpr bool kCheckImageObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700159static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700160
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161static void ThrowNoClassDefFoundError(const char* fmt, ...)
162 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700163 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700164static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700165 va_list args;
166 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800167 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000168 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800169 va_end(args);
170}
171
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100172static ObjPtr<mirror::Object> GetErroneousStateError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700173 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700174 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
175 if (ext == nullptr) {
176 return nullptr;
177 } else {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100178 return ext->GetErroneousStateError();
Alex Lightd6251582016-10-31 11:12:30 -0700179 }
180}
181
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100182static bool IsVerifyError(ObjPtr<mirror::Object> obj)
Alex Lightd6251582016-10-31 11:12:30 -0700183 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100184 // This is slow, but we only use it for rethrowing an error, and for DCHECK.
185 return obj->GetClass()->DescriptorEquals("Ljava/lang/VerifyError;");
186}
187
188// Helper for ThrowEarlierClassFailure. Throws the stored error.
189static void HandleEarlierErroneousStateError(Thread* self,
190 ClassLinker* class_linker,
191 ObjPtr<mirror::Class> c)
192 REQUIRES_SHARED(Locks::mutator_lock_) {
193 ObjPtr<mirror::Object> obj = GetErroneousStateError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800194 DCHECK(obj != nullptr);
195 self->AssertNoPendingException();
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100196 DCHECK(!obj->IsClass());
197 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
198 ObjPtr<mirror::Class> error_class = obj->GetClass();
199 CHECK(throwable_class->IsAssignableFrom(error_class));
200 self->SetException(obj->AsThrowable());
Andreas Gampe99babb62015-11-02 16:20:00 -0800201 self->AssertPendingException();
202}
203
Nicolas Geoffray66934ef2021-07-07 14:56:23 +0100204static void UpdateClassAfterVerification(Handle<mirror::Class> klass,
205 PointerSize pointer_size,
206 verifier::FailureKind failure_kind)
Andreas Gampe5b20b352018-10-11 19:03:20 -0700207 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000208 Runtime* runtime = Runtime::Current();
209 ClassLinker* class_linker = runtime->GetClassLinker();
Nicolas Geoffray2990b882021-11-30 15:48:49 +0000210 if (klass->IsVerified() && (failure_kind == verifier::FailureKind::kNoFailure)) {
Andreas Gampe5b20b352018-10-11 19:03:20 -0700211 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +0100212 }
213
214 // Now that the class has passed verification, try to set nterp entrypoints
215 // to methods that currently use the switch interpreter.
216 if (interpreter::CanRuntimeUseNterp()) {
217 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +0000218 if (class_linker->IsQuickToInterpreterBridge(m.GetEntryPointFromQuickCompiledCode())) {
219 runtime->GetInstrumentation()->InitializeMethodsCode(&m, /*aot_code=*/nullptr);
220 }
Nicolas Geoffray00391822019-12-10 10:17:23 +0000221 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700222 }
223}
224
Vladimir Markobf121912019-06-04 13:49:05 +0100225// Callback responsible for making a batch of classes visibly initialized
226// after all threads have called it from a checkpoint, ensuring visibility.
227class ClassLinker::VisiblyInitializedCallback final
228 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
229 public:
230 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
231 : class_linker_(class_linker),
232 num_classes_(0u),
233 thread_visibility_counter_(0),
234 barriers_() {
235 std::fill_n(classes_, kMaxClasses, nullptr);
236 }
237
238 bool IsEmpty() const {
239 DCHECK_LE(num_classes_, kMaxClasses);
240 return num_classes_ == 0u;
241 }
242
243 bool IsFull() const {
244 DCHECK_LE(num_classes_, kMaxClasses);
245 return num_classes_ == kMaxClasses;
246 }
247
248 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
249 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
250 DCHECK(!IsFull());
251 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
252 ++num_classes_;
253 }
254
255 void AddBarrier(Barrier* barrier) {
256 barriers_.push_front(barrier);
257 }
258
259 std::forward_list<Barrier*> GetAndClearBarriers() {
260 std::forward_list<Barrier*> result;
261 result.swap(barriers_);
262 result.reverse(); // Return barriers in insertion order.
263 return result;
264 }
265
266 void MakeVisible(Thread* self) {
267 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
268 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
269 AdjustThreadVisibilityCounter(self, count);
270 }
271
272 void Run(Thread* self) override {
273 self->ClearMakeVisiblyInitializedCounter();
274 AdjustThreadVisibilityCounter(self, -1);
275 }
276
277 private:
278 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
279 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
280 if (old + adjustment == 0) {
281 // All threads passed the checkpoint. Mark classes as visibly initialized.
282 {
283 ScopedObjectAccess soa(self);
284 StackHandleScope<1u> hs(self);
285 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
286 JavaVMExt* vm = self->GetJniEnv()->GetVm();
287 for (size_t i = 0, num = num_classes_; i != num; ++i) {
288 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
289 vm->DeleteWeakGlobalRef(self, classes_[i]);
290 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100291 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100292 class_linker_->FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100293 }
294 }
295 num_classes_ = 0u;
296 }
297 class_linker_->VisiblyInitializedCallbackDone(self, this);
298 }
299 }
300
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100301 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100302
303 ClassLinker* const class_linker_;
304 size_t num_classes_;
305 jweak classes_[kMaxClasses];
306
307 // The thread visibility counter starts at 0 and it is incremented by the number of
308 // threads that need to run this callback (by the thread that request the callback
309 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
310 // whether after the increment or after a decrement, we know that `Run()` was executed
311 // for all threads and therefore we can mark the classes as visibly initialized.
312 std::atomic<ssize_t> thread_visibility_counter_;
313
314 // List of barries to `Pass()` for threads that wait for the callback to complete.
315 std::forward_list<Barrier*> barriers_;
316};
317
318void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
319 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
320 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
321 }
322 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
323 if (wait) {
324 maybe_barrier.emplace(0);
325 }
326 int wait_count = 0;
327 VisiblyInitializedCallback* callback = nullptr;
328 {
329 MutexLock lock(self, visibly_initialized_callback_lock_);
330 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
331 callback = visibly_initialized_callback_.release();
332 running_visibly_initialized_callbacks_.push_front(*callback);
333 }
334 if (wait) {
335 DCHECK(maybe_barrier.has_value());
336 Barrier* barrier = std::addressof(*maybe_barrier);
337 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
338 cb.AddBarrier(barrier);
339 ++wait_count;
340 }
341 }
342 }
343 if (callback != nullptr) {
344 callback->MakeVisible(self);
345 }
346 if (wait_count != 0) {
347 DCHECK(maybe_barrier.has_value());
348 maybe_barrier->Increment(self, wait_count);
349 }
350}
351
352void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
353 VisiblyInitializedCallback* callback) {
354 MutexLock lock(self, visibly_initialized_callback_lock_);
355 // Pass the barriers if requested.
356 for (Barrier* barrier : callback->GetAndClearBarriers()) {
357 barrier->Pass(self);
358 }
359 // Remove the callback from the list of running callbacks.
360 auto before = running_visibly_initialized_callbacks_.before_begin();
361 auto it = running_visibly_initialized_callbacks_.begin();
362 DCHECK(it != running_visibly_initialized_callbacks_.end());
363 while (std::addressof(*it) != callback) {
364 before = it;
365 ++it;
366 DCHECK(it != running_visibly_initialized_callbacks_.end());
367 }
368 running_visibly_initialized_callbacks_.erase_after(before);
369 // Reuse or destroy the callback object.
370 if (visibly_initialized_callback_ == nullptr) {
371 visibly_initialized_callback_.reset(callback);
372 } else {
373 delete callback;
374 }
375}
376
Alex Lightfb119572019-09-18 15:04:53 -0700377void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
378 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
379 if (cb != nullptr) {
380 cb->MakeVisible(self);
381 }
382 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
383 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
384}
385
Vladimir Markobf121912019-06-04 13:49:05 +0100386ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
387 Thread* self, Handle<mirror::Class> klass) {
388 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
389 // Thanks to the x86 memory model, we do not need any memory fences and
390 // we can immediately mark the class as visibly initialized.
391 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100392 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100393 return nullptr;
394 }
395 if (Runtime::Current()->IsActiveTransaction()) {
396 // Transactions are single-threaded, so we can mark the class as visibly intialized.
397 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
398 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100399 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100400 return nullptr;
401 }
402 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
403 MutexLock lock(self, visibly_initialized_callback_lock_);
404 if (visibly_initialized_callback_ == nullptr) {
405 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
406 }
407 DCHECK(!visibly_initialized_callback_->IsFull());
408 visibly_initialized_callback_->AddClass(self, klass.Get());
409
410 if (visibly_initialized_callback_->IsFull()) {
411 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
412 running_visibly_initialized_callbacks_.push_front(*callback);
413 return callback;
414 } else {
415 return nullptr;
416 }
417}
418
Vladimir Marko86c87522020-05-11 16:55:55 +0100419const void* ClassLinker::RegisterNative(
420 Thread* self, ArtMethod* method, const void* native_method) {
421 CHECK(method->IsNative()) << method->PrettyMethod();
422 CHECK(native_method != nullptr) << method->PrettyMethod();
423 void* new_native_method = nullptr;
424 Runtime* runtime = Runtime::Current();
425 runtime->GetRuntimeCallbacks()->RegisterNativeMethod(method,
426 native_method,
427 /*out*/&new_native_method);
428 if (method->IsCriticalNative()) {
429 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
430 // Remove old registered method if any.
431 auto it = critical_native_code_with_clinit_check_.find(method);
432 if (it != critical_native_code_with_clinit_check_.end()) {
433 critical_native_code_with_clinit_check_.erase(it);
434 }
435 // To ensure correct memory visibility, we need the class to be visibly
436 // initialized before we can set the JNI entrypoint.
437 if (method->GetDeclaringClass()->IsVisiblyInitialized()) {
438 method->SetEntryPointFromJni(new_native_method);
439 } else {
440 critical_native_code_with_clinit_check_.emplace(method, new_native_method);
441 }
442 } else {
443 method->SetEntryPointFromJni(new_native_method);
444 }
445 return new_native_method;
446}
447
448void ClassLinker::UnregisterNative(Thread* self, ArtMethod* method) {
449 CHECK(method->IsNative()) << method->PrettyMethod();
450 // Restore stub to lookup native pointer via dlsym.
451 if (method->IsCriticalNative()) {
452 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
453 auto it = critical_native_code_with_clinit_check_.find(method);
454 if (it != critical_native_code_with_clinit_check_.end()) {
455 critical_native_code_with_clinit_check_.erase(it);
456 }
457 method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
458 } else {
459 method->SetEntryPointFromJni(GetJniDlsymLookupStub());
460 }
461}
462
463const void* ClassLinker::GetRegisteredNative(Thread* self, ArtMethod* method) {
464 if (method->IsCriticalNative()) {
465 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
466 auto it = critical_native_code_with_clinit_check_.find(method);
467 if (it != critical_native_code_with_clinit_check_.end()) {
468 return it->second;
469 }
470 const void* native_code = method->GetEntryPointFromJni();
471 return IsJniDlsymLookupCriticalStub(native_code) ? nullptr : native_code;
472 } else {
473 const void* native_code = method->GetEntryPointFromJni();
474 return IsJniDlsymLookupStub(native_code) ? nullptr : native_code;
475 }
476}
477
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800478void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
479 bool wrap_in_no_class_def,
480 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700481 // The class failed to initialize on a previous attempt, so we want to throw
482 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
483 // failed in verification, in which case v2 5.4.1 says we need to re-throw
484 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800485 Runtime* const runtime = Runtime::Current();
486 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700487 std::string extra;
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100488 ObjPtr<mirror::Object> verify_error = GetErroneousStateError(c);
Vladimir Markobb206de2019-03-28 10:30:32 +0000489 if (verify_error != nullptr) {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100490 DCHECK(!verify_error->IsClass());
491 extra = verify_error->AsThrowable()->Dump();
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700492 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800493 if (log) {
494 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
495 << ": " << extra;
496 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700497 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700498
David Sehr709b0702016-10-13 09:12:37 -0700499 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800500 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800501 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700502 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700503 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000504 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700505 } else {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100506 ObjPtr<mirror::Object> erroneous_state_error = GetErroneousStateError(c);
507 if (erroneous_state_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800508 // Rethrow stored error.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100509 HandleEarlierErroneousStateError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800510 }
Alex Lightd6251582016-10-31 11:12:30 -0700511 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
512 // might have meant to go down the earlier if statement with the original error but it got
513 // swallowed by the OOM so we end up here.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100514 if (erroneous_state_error == nullptr ||
515 (wrap_in_no_class_def && !IsVerifyError(erroneous_state_error))) {
Andreas Gampecb086952015-11-02 16:20:00 -0800516 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
517 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
518 // exception will be a cause.
519 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700520 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700521 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700522 }
523}
524
Brian Carlstromb23eab12014-10-08 17:55:21 -0700525static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700526 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700527 if (VLOG_IS_ON(class_linker)) {
528 std::string temp;
529 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000530 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700531 }
532}
533
534static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700535 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700536 Thread* self = Thread::Current();
537 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700538
539 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700540 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700541
David Srbecky346fd962020-07-27 16:51:00 +0100542 // Boot classpath classes should not fail initialization. This is a consistency debug check.
543 // This cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800544 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800545 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800546 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
547 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
548 // could have caused the error.
549 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
550 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
551 << " failed initialization: "
552 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800553 }
554
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700555 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700556 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
557 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700558
Elliott Hughesa4f94742012-05-29 16:28:38 -0700559 // We only wrap non-Error exceptions; an Error can just be used as-is.
560 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000561 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700562 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700563 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700564}
565
Andreas Gampe87658f32019-04-18 18:39:02 +0000566ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700567 : boot_class_table_(new ClassTable()),
568 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800569 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800570 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700571 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000572 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700573 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000574 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000575 jni_dlsym_lookup_trampoline_(nullptr),
Vladimir Markofa458ac2020-02-12 14:08:07 +0000576 jni_dlsym_lookup_critical_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800577 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800578 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100579 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800580 quick_to_interpreter_bridge_trampoline_(nullptr),
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000581 nterp_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700582 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100583 visibly_initialized_callback_lock_("visibly initialized callback lock"),
584 visibly_initialized_callback_(nullptr),
Vladimir Marko86c87522020-05-11 16:55:55 +0100585 critical_native_code_with_clinit_check_lock_("critical native code with clinit check lock"),
586 critical_native_code_with_clinit_check_(),
Andreas Gampe7dface32017-07-25 21:32:59 -0700587 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
588 // For CHA disabled during Aot, see b/34193647.
589
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700590 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700591 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
592 "Array cache size wrong.");
593 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700594}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700595
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800596void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700597 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800598 if (c2 == nullptr) {
599 LOG(FATAL) << "Could not find class " << descriptor;
600 UNREACHABLE();
601 }
602 if (c1.Get() != c2) {
603 std::ostringstream os1, os2;
604 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
605 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
606 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
607 << ". This is most likely the result of a broken build. Make sure that "
608 << "libcore and art projects match.\n\n"
609 << os1.str() << "\n\n" << os2.str();
610 UNREACHABLE();
611 }
612}
613
Vladimir Marko78f62d82022-01-10 16:25:19 +0000614ObjPtr<mirror::IfTable> AllocIfTable(Thread* self,
615 size_t ifcount,
616 ObjPtr<mirror::Class> iftable_class)
617 REQUIRES_SHARED(Locks::mutator_lock_) {
618 DCHECK(iftable_class->IsArrayClass());
619 DCHECK(iftable_class->GetComponentType()->IsObjectClass());
620 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
621 mirror::IfTable::Alloc(self, iftable_class, ifcount * mirror::IfTable::kMax)));
622}
623
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800624bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
625 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800626 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700627
Mathieu Chartiere401d142015-04-22 13:56:20 -0700628 Thread* const self = Thread::Current();
629 Runtime* const runtime = Runtime::Current();
630 gc::Heap* const heap = runtime->GetHeap();
631
Jeff Haodcdc85b2015-12-04 14:06:18 -0800632 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700633 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700634
Mathieu Chartiere401d142015-04-22 13:56:20 -0700635 // Use the pointer size from the runtime since we are probably creating the image.
636 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
637
Elliott Hughes30646832011-10-13 16:59:46 -0700638 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700639 // The GC can't handle an object with a null class since we can't get the size of this object.
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800640 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700641 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700642 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700643 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
644 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000645 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100646 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800647 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100648 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700649 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700650 if (kUseBakerReadBarrier) {
651 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800652 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700653 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700654 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800655 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700656 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700657
Elliott Hughes418d20f2011-09-22 14:00:39 -0700658 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700659 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700660 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700661 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700662 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700663
Ian Rogers23435d02012-09-24 11:23:12 -0700664 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700665 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700666 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800667 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700668 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700669 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000670 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700671
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700672 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800673 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
674 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100675 runtime->SetSentinel(heap->AllocNonMovableObject(self,
676 java_lang_Object.Get(),
677 java_lang_Object->GetObjectSize(),
678 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700679
Igor Murashkin86083f72017-10-27 10:59:04 -0700680 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000681 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700682 // It might seem the lock here is unnecessary, however all the SubtypeCheck
683 // functions are annotated to require locks all the way down.
684 //
685 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
686 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000687 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
688 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700689 }
690
Ian Rogers23435d02012-09-24 11:23:12 -0700691 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700692 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700693 AllocClass(self, java_lang_Class.Get(),
694 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700695 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700696
Roland Levillain0e840272018-08-23 19:55:30 +0100697 // Setup java.lang.String.
698 //
699 // We make this class non-movable for the unlikely case where it were to be
700 // moved by a sticky-bit (minor) collection when using the Generational
701 // Concurrent Copying (CC) collector, potentially creating a stale reference
702 // in the `klass_` field of one of its instances allocated in the Large-Object
703 // Space (LOS) -- see the comment about the dirty card scanning logic in
704 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700705 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700706 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100707 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700708 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000709 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400710
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700711 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700712 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700713 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700714 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000715 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700716
Ian Rogers23435d02012-09-24 11:23:12 -0700717 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700718 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100719 mirror::ObjectArray<mirror::Class>::Alloc(self,
720 object_array_class.Get(),
721 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700722 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100723 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
724 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
725 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
726 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100727 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
728 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700729
Mathieu Chartier6beced42016-11-15 15:51:31 -0800730 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
Vladimir Marko78f62d82022-01-10 16:25:19 +0000731 java_lang_Object->SetIfTable(AllocIfTable(self, 0, object_array_class.Get()));
Mathieu Chartier6beced42016-11-15 15:51:31 -0800732
Vladimir Marko02610552018-06-04 14:38:00 +0100733 // Create array interface entries to populate once we can load system classes.
Vladimir Marko78f62d82022-01-10 16:25:19 +0000734 object_array_class->SetIfTable(AllocIfTable(self, 2, object_array_class.Get()));
Vladimir Marko02610552018-06-04 14:38:00 +0100735 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
736
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700737 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100738 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
739 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
740 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
741 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
742 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
743 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
744 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
745 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
746 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700747
Vladimir Marko70e2a762019-07-12 16:49:00 +0100748 // Allocate the primitive array classes. We need only the native pointer
749 // array at this point (int[] or long[], depending on architecture) but
750 // we shall perform the same setup steps for all primitive array classes.
751 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
752 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
753 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
754 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
755 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
756 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
757 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
758 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700759
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700760 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700761
Ian Rogers52813c92012-10-11 11:50:38 -0700762 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700763 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700764 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100765 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100766 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700767 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000768 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700769
Alex Lightd6251582016-10-31 11:12:30 -0700770
771 // Setup dalvik.system.ClassExt
772 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
773 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100774 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000775 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700776
Mathieu Chartier66f19252012-09-18 08:57:04 -0700777 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700778 Handle<mirror::Class> object_array_string(hs.NewHandle(
779 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700780 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700781 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100782 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700783
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000784 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700785 // Create runtime resolution and imt conflict methods.
786 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000787 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
788 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700789
Ian Rogers23435d02012-09-24 11:23:12 -0700790 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
791 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
792 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800793 if (boot_class_path.empty()) {
794 *error_msg = "Boot classpath is empty.";
795 return false;
796 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800797 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800798 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800799 *error_msg = "Null dex file.";
800 return false;
801 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800802 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800803 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700804 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700805
806 // now we can use FindSystemClass
807
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700808 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
809 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700810 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800811 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700812 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000813 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Vladimir Markofa458ac2020-02-12 14:08:07 +0000814 jni_dlsym_lookup_critical_trampoline_ = GetJniDlsymLookupCriticalStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700815 quick_resolution_trampoline_ = GetQuickResolutionStub();
816 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000817 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700818 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000819 nterp_trampoline_ = interpreter::GetNterpEntryPoint();
Alex Light64ad14d2014-08-19 14:23:13 -0700820 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700821
Alex Lightd6251582016-10-31 11:12:30 -0700822 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000823 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800824 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700825 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000826 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800827 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000828 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800829 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700830 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000831 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700832 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
833 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700834
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800835 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
836 // in class_table_.
837 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700838
Vladimir Marko70e2a762019-07-12 16:49:00 +0100839 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
840 // arrays - can't be done until Object has a vtable and component classes are loaded.
841 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
842 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
843 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
844 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
845 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
846 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
847 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
848 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
849 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
850 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
851 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700852
Ian Rogers23435d02012-09-24 11:23:12 -0700853 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700854 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800855 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700856 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800857 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700858 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
859 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100860 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
861 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700862
Vladimir Markob10668c2021-06-10 09:52:53 +0100863 // Check Class[] and Object[]'s interfaces.
864 CHECK_EQ(java_lang_Cloneable.Get(), class_array_class->GetDirectInterface(0));
865 CHECK_EQ(java_io_Serializable.Get(), class_array_class->GetDirectInterface(1));
866 CHECK_EQ(java_lang_Cloneable.Get(), object_array_class->GetDirectInterface(0));
867 CHECK_EQ(java_io_Serializable.Get(), object_array_class->GetDirectInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700868
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700869 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100870 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700871
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800872 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700873
Ian Rogers23435d02012-09-24 11:23:12 -0700874 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100875 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
876 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700877
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700878 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100879 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700880 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100881 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700882
883 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700884 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
885 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100886 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700887
888 // Create java.lang.reflect.Constructor.class root and array root.
889 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
890 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100891 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700892 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
893 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100894 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700895
896 // Create java.lang.reflect.Method.class root and array root.
897 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
898 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100899 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700900 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
901 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100902 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700903
Orion Hodson005ac512017-10-24 15:43:43 +0100904 // Create java.lang.invoke.CallSite.class root
905 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
906 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100907 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100908
Narayan Kamathafa48272016-08-03 12:46:58 +0100909 // Create java.lang.invoke.MethodType.class root
910 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
911 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100912 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100913
914 // Create java.lang.invoke.MethodHandleImpl.class root
915 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
916 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100917 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100918 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100919
Orion Hodsonc069a302017-01-18 09:23:12 +0000920 // Create java.lang.invoke.MethodHandles.Lookup.class root
921 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
922 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100923 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000924
Orion Hodson005ac512017-10-24 15:43:43 +0100925 // Create java.lang.invoke.VarHandle.class root
926 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000927 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100928 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100929
930 // Create java.lang.invoke.FieldVarHandle.class root
931 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
932 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100933 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100934
Orion Hodsondd411962021-06-25 08:55:22 +0100935 // Create java.lang.invoke.StaticFieldVarHandle.class root
936 class_root = FindSystemClass(self, "Ljava/lang/invoke/StaticFieldVarHandle;");
937 CHECK(class_root != nullptr);
938 SetClassRoot(ClassRoot::kJavaLangInvokeStaticFieldVarHandle, class_root);
939
Orion Hodson005ac512017-10-24 15:43:43 +0100940 // Create java.lang.invoke.ArrayElementVarHandle.class root
941 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
942 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100943 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100944
945 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
946 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
947 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100948 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100949
950 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
951 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
952 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100953 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000954
Narayan Kamath000e1882016-10-24 17:14:25 +0100955 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
956 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100957 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100958
Brian Carlstrom1f870082011-08-23 16:02:11 -0700959 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700960 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000961 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800962 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700963 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700964 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
965 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700966 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700967 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700968 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700969 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700970 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700971 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700972 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700973 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700974 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700975 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700976 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700977 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700978
Ian Rogers23435d02012-09-24 11:23:12 -0700979 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700980 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700981 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700982 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100983 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700984
jeffhao8cd6dda2012-02-22 10:15:34 -0800985 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700986 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100987 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100988 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700989 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100990 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
991 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
992 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700993 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000994 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
995 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700996
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700997 // Create conflict tables that depend on the class linker.
998 runtime->FixupConflictTables();
999
Ian Rogers98379392014-02-24 16:53:16 -08001000 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001001
Brian Carlstroma004aa92012-02-08 18:05:09 -08001002 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001003
1004 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001005}
1006
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001007static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1008 REQUIRES_SHARED(Locks::mutator_lock_) {
1009 // Find String.<init> -> StringFactory bindings.
1010 ObjPtr<mirror::Class> string_factory_class =
1011 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1012 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001013 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001014 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1015 // Update the primordial thread.
1016 self->InitStringEntryPoints();
1017}
1018
Ian Rogers98379392014-02-24 16:53:16 -08001019void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001020 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001021
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001022 CreateStringInitBindings(self, this);
1023
Brian Carlstrom16192862011-09-12 17:50:06 -07001024 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001025 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001026 // as the types of the field can't be resolved prior to the runtime being
1027 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001028 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001029 Handle<mirror::Class> java_lang_ref_Reference =
1030 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001031 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1032 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001033
Mathieu Chartierc7853442015-03-27 14:35:38 -07001034 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001035 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1036 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001037
Mathieu Chartierc7853442015-03-27 14:35:38 -07001038 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001039 CHECK_STREQ(queue->GetName(), "queue");
1040 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001041
Mathieu Chartierc7853442015-03-27 14:35:38 -07001042 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001043 CHECK_STREQ(queueNext->GetName(), "queueNext");
1044 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001045
Mathieu Chartierc7853442015-03-27 14:35:38 -07001046 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001047 CHECK_STREQ(referent->GetName(), "referent");
1048 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001049
Mathieu Chartierc7853442015-03-27 14:35:38 -07001050 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001051 CHECK_STREQ(zombie->GetName(), "zombie");
1052 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001053
Brian Carlstroma663ea52011-08-19 23:33:41 -07001054 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001055 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001056 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001057 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001058 CHECK(klass != nullptr);
1059 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001060 // note SetClassRoot does additional validation.
1061 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001062 }
1063
Vladimir Marko02610552018-06-04 14:38:00 +01001064 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001065
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001066 // disable the slow paths in FindClass and CreatePrimitiveClass now
1067 // that Object, Class, and Object[] are setup
1068 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001069
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001070 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1071 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1072 // ensure that the class will be initialized.
1073 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001074 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001075
1076 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1077 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1078 // Strange, but don't crash.
1079 LOG(WARNING) << "Could not prepare StackOverflowError.";
1080 self->ClearException();
1081 }
1082 }
1083
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001084 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001085}
1086
Vladimir Markodcfcce42018-06-27 10:00:28 +00001087void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001088 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1089 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001090 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001091 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001092 Handle<mirror::Class> h_class(hs.NewHandle(c));
David Srbecky08110ef2020-05-20 19:33:43 +01001093 if (!EnsureInitialized(self, h_class, true, true)) {
1094 LOG(FATAL) << "Exception when initializing " << h_class->PrettyClass()
1095 << ": " << self->GetException()->Dump();
1096 }
Vladimir Markodcfcce42018-06-27 10:00:28 +00001097 } else {
1098 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001099 }
1100 }
1101}
1102
Vladimir Marko8670e042021-12-21 17:55:48 +00001103ALWAYS_INLINE
1104static uint32_t ComputeMethodHash(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1105 DCHECK(!method->IsRuntimeMethod());
1106 DCHECK(!method->IsProxyMethod());
1107 DCHECK(!method->IsObsolete());
1108 // Do not use `ArtMethod::GetNameView()` to avoid unnecessary runtime/proxy/obsolete method
1109 // checks. It is safe to avoid the read barrier here, see `ArtMethod::GetDexFile()`.
1110 const DexFile& dex_file = method->GetDeclaringClass<kWithoutReadBarrier>()->GetDexFile();
1111 const dex::MethodId& method_id = dex_file.GetMethodId(method->GetDexMethodIndex());
1112 std::string_view name = dex_file.GetMethodNameView(method_id);
1113 return ComputeModifiedUtf8Hash(name);
1114}
1115
Vladimir Markobed84ef2022-01-21 13:57:14 +00001116ALWAYS_INLINE
1117static bool MethodSignatureEquals(ArtMethod* lhs, ArtMethod* rhs)
1118 REQUIRES_SHARED(Locks::mutator_lock_) {
1119 DCHECK(!lhs->IsRuntimeMethod());
1120 DCHECK(!lhs->IsProxyMethod());
1121 DCHECK(!lhs->IsObsolete());
1122 DCHECK(!rhs->IsRuntimeMethod());
1123 DCHECK(!rhs->IsProxyMethod());
1124 DCHECK(!rhs->IsObsolete());
1125 // Do not use `ArtMethod::GetDexFile()` to avoid unnecessary obsolete method checks.
1126 // It is safe to avoid the read barrier here, see `ArtMethod::GetDexFile()`.
1127 const DexFile& lhs_dex_file = lhs->GetDeclaringClass<kWithoutReadBarrier>()->GetDexFile();
1128 const DexFile& rhs_dex_file = rhs->GetDeclaringClass<kWithoutReadBarrier>()->GetDexFile();
1129 const dex::MethodId& lhs_mid = lhs_dex_file.GetMethodId(lhs->GetDexMethodIndex());
1130 const dex::MethodId& rhs_mid = rhs_dex_file.GetMethodId(rhs->GetDexMethodIndex());
1131 if (&lhs_dex_file == &rhs_dex_file) {
1132 return lhs_mid.name_idx_ == rhs_mid.name_idx_ &&
1133 lhs_mid.proto_idx_ == rhs_mid.proto_idx_;
1134 } else {
1135 return
1136 lhs_dex_file.GetMethodNameView(lhs_mid) == rhs_dex_file.GetMethodNameView(rhs_mid) &&
1137 lhs_dex_file.GetMethodSignature(lhs_mid) == rhs_dex_file.GetMethodSignature(rhs_mid);
1138 }
1139}
1140
Vladimir Marko43354742021-02-03 15:37:01 +00001141static void InitializeObjectVirtualMethodHashes(ObjPtr<mirror::Class> java_lang_Object,
1142 PointerSize pointer_size,
1143 /*out*/ ArrayRef<uint32_t> virtual_method_hashes)
1144 REQUIRES_SHARED(Locks::mutator_lock_) {
1145 ArraySlice<ArtMethod> virtual_methods = java_lang_Object->GetVirtualMethods(pointer_size);
1146 DCHECK_EQ(virtual_method_hashes.size(), virtual_methods.size());
1147 for (size_t i = 0; i != virtual_method_hashes.size(); ++i) {
Vladimir Marko8670e042021-12-21 17:55:48 +00001148 virtual_method_hashes[i] = ComputeMethodHash(&virtual_methods[i]);
Vladimir Marko43354742021-02-03 15:37:01 +00001149 }
1150}
1151
Jeff Haodcdc85b2015-12-04 14:06:18 -08001152struct TrampolineCheckData {
1153 const void* quick_resolution_trampoline;
1154 const void* quick_imt_conflict_trampoline;
1155 const void* quick_generic_jni_trampoline;
1156 const void* quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001157 const void* nterp_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001158 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001159 ArtMethod* m;
1160 bool error;
1161};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001162
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001163bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1164 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001165 CHECK(!init_done_);
1166
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001167 Runtime* const runtime = Runtime::Current();
1168 Thread* const self = Thread::Current();
1169 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001170 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1171 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001172 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1173 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001174 if (!ValidPointerSize(pointer_size_unchecked)) {
1175 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001176 return false;
1177 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001178 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001179 if (!runtime->IsAotCompiler()) {
1180 // Only the Aot compiler supports having an image with a different pointer size than the
1181 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1182 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001183 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001184 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001185 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001186 sizeof(void*));
1187 return false;
1188 }
1189 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001190 DCHECK(!runtime->HasResolutionMethod());
1191 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1192 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1193 runtime->SetImtUnimplementedMethod(
1194 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1195 runtime->SetCalleeSaveMethod(
1196 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1197 CalleeSaveType::kSaveAllCalleeSaves);
1198 runtime->SetCalleeSaveMethod(
1199 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1200 CalleeSaveType::kSaveRefsOnly);
1201 runtime->SetCalleeSaveMethod(
1202 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1203 CalleeSaveType::kSaveRefsAndArgs);
1204 runtime->SetCalleeSaveMethod(
1205 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1206 CalleeSaveType::kSaveEverything);
1207 runtime->SetCalleeSaveMethod(
1208 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1209 CalleeSaveType::kSaveEverythingForClinit);
1210 runtime->SetCalleeSaveMethod(
1211 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1212 CalleeSaveType::kSaveEverythingForSuspendCheck);
1213
Jeff Haodcdc85b2015-12-04 14:06:18 -08001214 std::vector<const OatFile*> oat_files =
1215 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1216 DCHECK(!oat_files.empty());
1217 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001218 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001219 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001220 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1221 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1222 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1223 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001224 nterp_trampoline_ = default_oat_header.GetNterpTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001225 if (kIsDebugBuild) {
1226 // Check that the other images use the same trampoline.
1227 for (size_t i = 1; i < oat_files.size(); ++i) {
1228 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001229 const void* ith_jni_dlsym_lookup_trampoline_ =
1230 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001231 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1232 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001233 const void* ith_quick_resolution_trampoline =
1234 ith_oat_header.GetQuickResolutionTrampoline();
1235 const void* ith_quick_imt_conflict_trampoline =
1236 ith_oat_header.GetQuickImtConflictTrampoline();
1237 const void* ith_quick_generic_jni_trampoline =
1238 ith_oat_header.GetQuickGenericJniTrampoline();
1239 const void* ith_quick_to_interpreter_bridge_trampoline =
1240 ith_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001241 const void* ith_nterp_trampoline =
1242 ith_oat_header.GetNterpTrampoline();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001243 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001244 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001245 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001246 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1247 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001248 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_ ||
1249 ith_nterp_trampoline != nterp_trampoline_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001250 // Make sure that all methods in this image do not contain those trampolines as
1251 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1252 TrampolineCheckData data;
1253 data.error = false;
1254 data.pointer_size = GetImagePointerSize();
1255 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1256 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1257 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1258 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001259 data.nterp_trampoline = ith_nterp_trampoline;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001260 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001261 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1262 if (obj->IsClass()) {
1263 ObjPtr<mirror::Class> klass = obj->AsClass();
1264 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1265 const void* entrypoint =
1266 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1267 if (entrypoint == data.quick_resolution_trampoline ||
1268 entrypoint == data.quick_imt_conflict_trampoline ||
1269 entrypoint == data.quick_generic_jni_trampoline ||
1270 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1271 data.m = &m;
1272 data.error = true;
1273 return;
1274 }
1275 }
1276 }
1277 };
1278 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001279 if (data.error) {
1280 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001281 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001282 *error_msg = "Found an ArtMethod with a bad entrypoint";
1283 return false;
1284 }
1285 }
1286 }
1287 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001288
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001289 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001290 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001291 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001292 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001293
Vladimir Marko024d69f2019-06-13 10:52:32 +01001294 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1295 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1296 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1297 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1298 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1299 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001300
Vladimir Markod1908512018-11-22 14:57:28 +00001301 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001302 // Boot class loader, use a null handle.
1303 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001304 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001305 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001306 /*out*/&dex_files,
1307 error_msg)) {
1308 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001309 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001310 // Append opened dex files at the end.
1311 boot_dex_files_.insert(boot_dex_files_.end(),
1312 std::make_move_iterator(dex_files.begin()),
1313 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001314 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001315 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
Jared Duke95bb9952021-08-11 15:07:25 -07001316 OatDexFile::MadviseDexFileAtLoad(*dex_file);
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001317 }
Vladimir Marko43354742021-02-03 15:37:01 +00001318 InitializeObjectVirtualMethodHashes(GetClassRoot<mirror::Object>(this),
1319 image_pointer_size_,
1320 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Ian Rogers98379392014-02-24 16:53:16 -08001321 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001322
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001323 VLOG(startup) << __FUNCTION__ << " exiting";
1324 return true;
1325}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001326
Vladimir Marko4433c432018-12-04 14:57:47 +00001327void ClassLinker::AddExtraBootDexFiles(
1328 Thread* self,
1329 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1330 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001331 AppendToBootClassPath(self, dex_file.get());
Orion Hodson771708f2021-01-06 15:45:16 +00001332 if (kIsDebugBuild) {
1333 for (const auto& boot_dex_file : boot_dex_files_) {
1334 DCHECK_NE(boot_dex_file->GetLocation(), dex_file->GetLocation());
1335 }
1336 }
Vladimir Marko4433c432018-12-04 14:57:47 +00001337 boot_dex_files_.push_back(std::move(dex_file));
1338 }
1339}
1340
Jeff Hao5872d7c2016-04-27 11:07:41 -07001341bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001342 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001343 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001344 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1345 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001346}
1347
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001348class CHAOnDeleteUpdateClassVisitor {
1349 public:
1350 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1351 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1352 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1353 self_(Thread::Current()) {}
1354
1355 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1356 // This class is going to be unloaded. Tell CHA about it.
1357 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1358 return true;
1359 }
1360 private:
1361 const LinearAlloc* allocator_;
1362 const ClassHierarchyAnalysis* cha_;
1363 const PointerSize pointer_size_;
1364 const Thread* self_;
1365};
1366
Chris Wailes0c61be42018-09-26 17:27:34 -07001367/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001368 * A class used to ensure that all references to strings interned in an AppImage have been
1369 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001370 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001371class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001372 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001373 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1374 const InternTable::UnorderedSet& image_interns)
1375 : space_(space),
1376 image_interns_(image_interns),
1377 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001378
Chris Wailes0c61be42018-09-26 17:27:34 -07001379 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001380 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001381 if (referred_obj != nullptr &&
1382 space_.HasAddress(referred_obj.Ptr()) &&
1383 referred_obj->IsString()) {
1384 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001385 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1386 if (it != image_interns_.end() && it->Read() == referred_str) {
1387 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001388 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001389 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001390 }
1391
Chris Wailes0c61be42018-09-26 17:27:34 -07001392 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001393 mirror::CompressedReference<mirror::Object>* root) const
1394 REQUIRES_SHARED(Locks::mutator_lock_) {
1395 if (!root->IsNull()) {
1396 VisitRoot(root);
1397 }
1398 }
1399
Chris Wailes0c61be42018-09-26 17:27:34 -07001400 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001401 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001402 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001403 }
1404
1405 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001406 void operator()(ObjPtr<mirror::Object> obj,
1407 MemberOffset offset,
1408 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001409 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001410 // References within image or across images don't need a read barrier.
1411 ObjPtr<mirror::Object> referred_obj =
1412 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1413 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001414 }
1415
1416 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1417 ObjPtr<mirror::Reference> ref) const
1418 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001419 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001420 }
1421
Vladimir Marko8e05f092019-06-10 11:10:38 +01001422 size_t GetCount() const {
1423 return count_;
1424 }
1425
1426 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001427 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001428 const InternTable::UnorderedSet& image_interns_;
1429 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001430};
1431
Chris Wailes0c61be42018-09-26 17:27:34 -07001432/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001433 * This function counts references to strings interned in the AppImage.
1434 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001435 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001436size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1437 const InternTable::UnorderedSet& image_interns)
1438 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001439 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1440 const ImageHeader& image_header = space.GetImageHeader();
1441 const uint8_t* target_base = space.GetMemMap()->Begin();
1442 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001443
1444 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1445 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001446
Vladimir Marko8e05f092019-06-10 11:10:38 +01001447 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001448 bitmap->VisitMarkedRange(objects_begin,
1449 objects_end,
1450 [&space, &visitor](mirror::Object* obj)
1451 REQUIRES_SHARED(Locks::mutator_lock_) {
1452 if (space.HasAddress(obj)) {
1453 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001454 obj->VisitReferences</* kVisitNativeRoots= */ true,
1455 kVerifyNone,
1456 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001457 } else {
1458 // Don't visit native roots for non-dex-cache as they can't contain
1459 // native references to strings. This is verified during compilation
1460 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001461 obj->VisitReferences</* kVisitNativeRoots= */ false,
1462 kVerifyNone,
1463 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001464 }
1465 }
1466 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001467 return visitor.GetCount();
1468}
1469
1470template <typename Visitor>
1471static void VisitInternedStringReferences(
1472 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001473 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1474 const uint8_t* target_base = space->Begin();
1475 const ImageSection& sro_section =
1476 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1477 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1478
1479 VLOG(image)
1480 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1481 << num_string_offsets;
1482
1483 const auto* sro_base =
1484 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1485
1486 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1487 uint32_t base_offset = sro_base[offset_index].first;
1488
David Srbecky86d6cd52020-12-02 18:13:10 +00001489 uint32_t raw_member_offset = sro_base[offset_index].second;
1490 DCHECK_ALIGNED(base_offset, 2);
1491 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001492
David Srbecky86d6cd52020-12-02 18:13:10 +00001493 ObjPtr<mirror::Object> obj_ptr =
1494 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1495 MemberOffset member_offset(raw_member_offset);
1496 ObjPtr<mirror::String> referred_string =
1497 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001498 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001499 kWithoutReadBarrier,
1500 /* kIsVolatile= */ false>(member_offset);
1501 DCHECK(referred_string != nullptr);
1502
1503 ObjPtr<mirror::String> visited = visitor(referred_string);
1504 if (visited != referred_string) {
1505 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1506 /* kCheckTransaction= */ false,
1507 kVerifyNone,
1508 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001509 }
1510 }
1511}
1512
1513static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1514 REQUIRES_SHARED(Locks::mutator_lock_) {
1515 InternTable::UnorderedSet image_interns;
1516 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1517 if (section.Size() > 0) {
1518 size_t read_count;
1519 const uint8_t* data = space->Begin() + section.Offset();
1520 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1521 image_set.swap(image_interns);
1522 }
1523 size_t num_recorded_refs = 0u;
1524 VisitInternedStringReferences(
1525 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001526 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1527 REQUIRES_SHARED(Locks::mutator_lock_) {
1528 auto it = image_interns.find(GcRoot<mirror::String>(str));
1529 CHECK(it != image_interns.end());
1530 CHECK(it->Read() == str);
1531 ++num_recorded_refs;
1532 return str;
1533 });
1534 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1535 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001536}
1537
Andreas Gampe2af99022017-04-25 08:32:59 -07001538// new_class_set is the set of classes that were read from the class table section in the image.
1539// If there was no class table section, it is null.
1540// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001541class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001542 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001543 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001544 ClassLinker* class_linker,
1545 gc::space::ImageSpace* space,
1546 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001547 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001548 REQUIRES(!Locks::dex_lock_)
1549 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001550
Chris Wailesfbeef462018-10-19 14:16:35 -07001551 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001552 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001553};
1554
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001555void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001556 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001557 gc::space::ImageSpace* space,
1558 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001559 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001560 REQUIRES(!Locks::dex_lock_)
1561 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001562 ScopedTrace app_image_timing("AppImage:Updating");
1563
Vladimir Marko8e05f092019-06-10 11:10:38 +01001564 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1565 // In debug build, verify the string references before applying
1566 // the Runtime::LoadAppImageStartupCache() option.
1567 VerifyInternedStringReferences(space);
1568 }
1569
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001570 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001571 Runtime* const runtime = Runtime::Current();
1572 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001573 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001574 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001575 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001576 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001577 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001578 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001579 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001580 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001581 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001582 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001583 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001584 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001585 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001586
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001587 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001588 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001589 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001590
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001591 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001592 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001593 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001594 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1595 header.VisitPackedArtMethods([&](ArtMethod& method)
1596 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1597 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1598 if (klass != nullptr) {
1599 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1600 }
1601 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001602 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001603}
1604
Chris Wailesfbeef462018-10-19 14:16:35 -07001605void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001606 // Iterate over the string reference offsets stored in the image and intern
1607 // the strings they point to.
1608 ScopedTrace timing("AppImage:InternString");
1609
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001610 Runtime* const runtime = Runtime::Current();
1611 InternTable* const intern_table = runtime->GetInternTable();
1612
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001613 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1614 // for faster lookup.
1615 // TODO: Optimize with a bitmap or bloom filter
1616 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001617 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001618 REQUIRES_SHARED(Locks::mutator_lock_)
1619 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001620 const size_t non_boot_image_strings = intern_table->CountInterns(
1621 /*visit_boot_images=*/false,
1622 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001623 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001624 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1625 // Visit the smaller of the two sets to compute the intersection.
1626 if (interns.size() < non_boot_image_strings) {
1627 for (auto it = interns.begin(); it != interns.end(); ) {
1628 ObjPtr<mirror::String> string = it->Read();
1629 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1630 if (existing == nullptr) {
1631 existing = intern_table->LookupStrongLocked(string);
1632 }
1633 if (existing != nullptr) {
1634 intern_remap.Put(string.Ptr(), existing.Ptr());
1635 it = interns.erase(it);
1636 } else {
1637 ++it;
1638 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001639 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001640 } else {
1641 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1642 REQUIRES_SHARED(Locks::mutator_lock_)
1643 REQUIRES(Locks::intern_table_lock_) {
1644 auto it = interns.find(root);
1645 if (it != interns.end()) {
1646 ObjPtr<mirror::String> existing = root.Read();
1647 intern_remap.Put(it->Read(), existing.Ptr());
1648 it = interns.erase(it);
1649 }
1650 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1651 }
David Srbecky346fd962020-07-27 16:51:00 +01001652 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001653 if (kIsDebugBuild) {
1654 for (GcRoot<mirror::String>& root : interns) {
1655 ObjPtr<mirror::String> string = root.Read();
1656 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1657 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001658 }
1659 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001660 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001661 intern_table->AddImageStringsToTable(space, func);
1662 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001663 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001664 VisitInternedStringReferences(
1665 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001666 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1667 auto it = intern_remap.find(str.Ptr());
1668 if (it != intern_remap.end()) {
1669 return ObjPtr<mirror::String>(it->second);
1670 }
1671 return str;
1672 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001673 }
1674}
1675
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001676static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1677 const char* location,
1678 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001679 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001680 DCHECK(error_msg != nullptr);
1681 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001682 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001683 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001684 return std::unique_ptr<const DexFile>();
1685 }
1686 std::string inner_error_msg;
1687 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1688 if (dex_file == nullptr) {
1689 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1690 location,
1691 oat_file->GetLocation().c_str(),
1692 inner_error_msg.c_str());
1693 return std::unique_ptr<const DexFile>();
1694 }
1695
1696 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1697 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1698 location,
1699 dex_file->GetLocationChecksum(),
1700 oat_dex_file->GetDexFileLocationChecksum());
1701 return std::unique_ptr<const DexFile>();
1702 }
1703 return dex_file;
1704}
1705
1706bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1707 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1708 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001709 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001710 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001711 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001712 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001713 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001714 dex_caches_object->AsObjectArray<mirror::DexCache>();
1715 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001716 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001717 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1718 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1719 dex_file_location.c_str(),
1720 error_msg);
1721 if (dex_file == nullptr) {
1722 return false;
1723 }
1724 dex_cache->SetDexFile(dex_file.get());
1725 out_dex_files->push_back(std::move(dex_file));
1726 }
1727 return true;
1728}
1729
Andreas Gampe0793bec2016-12-01 11:37:33 -08001730// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1731// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001732class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001733 public:
1734 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1735 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001736 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001737 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1738 DCHECK(obj != nullptr);
1739 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1740 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1741 if (obj->IsClass()) {
1742 auto klass = obj->AsClass();
1743 for (ArtField& field : klass->GetIFields()) {
1744 CHECK_EQ(field.GetDeclaringClass(), klass);
1745 }
1746 for (ArtField& field : klass->GetSFields()) {
1747 CHECK_EQ(field.GetDeclaringClass(), klass);
1748 }
Orion Hodson5880c772020-07-28 20:12:08 +01001749 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001750 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001751 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001752 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001753 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001754 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001755 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001756 }
1757 if (klass->ShouldHaveImt()) {
1758 ImTable* imt = klass->GetImt(pointer_size);
1759 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001760 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001761 }
1762 }
1763 if (klass->ShouldHaveEmbeddedVTable()) {
1764 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001765 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001766 }
1767 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001768 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001769 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1770 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001771 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001772 }
1773 }
1774 }
1775 };
1776 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001777 }
1778
Andreas Gampe0793bec2016-12-01 11:37:33 -08001779 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001780 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001781 : spaces_(heap->GetBootImageSpaces()),
1782 pointer_size_(class_linker->GetImagePointerSize()) {
1783 space_begin_.reserve(spaces_.size());
1784 method_sections_.reserve(spaces_.size());
1785 runtime_method_sections_.reserve(spaces_.size());
1786 for (gc::space::ImageSpace* space : spaces_) {
1787 space_begin_.push_back(space->Begin());
1788 auto& header = space->GetImageHeader();
1789 method_sections_.push_back(&header.GetMethodsSection());
1790 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1791 }
1792 }
1793
Orion Hodson5880c772020-07-28 20:12:08 +01001794 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001795 REQUIRES_SHARED(Locks::mutator_lock_) {
1796 if (m->IsRuntimeMethod()) {
1797 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1798 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1799 } else if (m->IsCopied()) {
1800 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1801 } else if (expected_class != nullptr) {
1802 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1803 }
1804 if (!spaces_.empty()) {
1805 bool contains = false;
1806 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1807 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1808 contains = method_sections_[i]->Contains(offset) ||
1809 runtime_method_sections_[i]->Contains(offset);
1810 }
1811 CHECK(contains) << m << " not found";
1812 }
1813 }
1814
Orion Hodson5880c772020-07-28 20:12:08 +01001815 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1816 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001817 REQUIRES_SHARED(Locks::mutator_lock_) {
1818 CHECK(arr != nullptr);
1819 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1820 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1821 // expected_class == null means we are a dex cache.
1822 if (expected_class != nullptr) {
1823 CHECK(method != nullptr);
1824 }
1825 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001826 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001827 }
1828 }
1829 }
1830
Andreas Gampe0793bec2016-12-01 11:37:33 -08001831 const std::vector<gc::space::ImageSpace*>& spaces_;
1832 const PointerSize pointer_size_;
1833
1834 // Cached sections from the spaces.
1835 std::vector<const uint8_t*> space_begin_;
1836 std::vector<const ImageSection*> method_sections_;
1837 std::vector<const ImageSection*> runtime_method_sections_;
1838};
1839
Andreas Gampebe7af222017-07-25 09:57:28 -07001840static void VerifyAppImage(const ImageHeader& header,
1841 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001842 ClassTable* class_table,
1843 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001844 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001845 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1846 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1847 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1848 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1849 << mirror::Class::PrettyClass(klass);
1850 }
1851 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001852 {
1853 // Verify that all direct interfaces of classes in the class table are also resolved.
1854 std::vector<ObjPtr<mirror::Class>> classes;
1855 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1856 REQUIRES_SHARED(Locks::mutator_lock_) {
1857 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1858 classes.push_back(klass);
1859 }
1860 return true;
1861 };
1862 class_table->Visit(verify_direct_interfaces_in_table);
Andreas Gampebe7af222017-07-25 09:57:28 -07001863 for (ObjPtr<mirror::Class> klass : classes) {
1864 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +01001865 CHECK(klass->GetDirectInterface(i) != nullptr)
Andreas Gampebe7af222017-07-25 09:57:28 -07001866 << klass->PrettyDescriptor() << " iface #" << i;
1867 }
1868 }
1869 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001870}
1871
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001872bool ClassLinker::AddImageSpace(
1873 gc::space::ImageSpace* space,
1874 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001875 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1876 std::string* error_msg) {
1877 DCHECK(out_dex_files != nullptr);
1878 DCHECK(error_msg != nullptr);
1879 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001880 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001881 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001882 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001883 DCHECK(dex_caches_object != nullptr);
1884 Runtime* const runtime = Runtime::Current();
1885 gc::Heap* const heap = runtime->GetHeap();
1886 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001887 // Check that the image is what we are expecting.
1888 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1889 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1890 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1891 image_pointer_size_);
1892 return false;
1893 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001894 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1895 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1896 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1897 expected_image_roots,
1898 header.GetImageRoots()->GetLength());
1899 return false;
1900 }
1901 StackHandleScope<3> hs(self);
1902 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1903 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1904 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1905 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001906 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001907 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1908 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001909 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001910 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001911 *error_msg = StringPrintf("Expected %d class roots but got %d",
1912 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001913 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001914 return false;
1915 }
1916 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001917 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1918 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1919 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001920 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1921 return false;
1922 }
1923 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001924 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001925 if (oat_file->GetOatHeader().GetDexFileCount() !=
1926 static_cast<uint32_t>(dex_caches->GetLength())) {
1927 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1928 "image";
1929 return false;
1930 }
1931
Alex Lighta9bbc082019-11-14 14:51:41 -08001932 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001933 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001934 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1935 dex_file_location.c_str(),
1936 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001937 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001938 return false;
1939 }
1940
David Srbecky86d6cd52020-12-02 18:13:10 +00001941 {
David Srbecky33df0e32021-09-30 14:36:32 +00001942 // Native fields are all null. Initialize them.
David Srbecky86d6cd52020-12-02 18:13:10 +00001943 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky33df0e32021-09-30 14:36:32 +00001944 dex_cache->Initialize(dex_file.get(), class_loader.Get());
David Srbecky86d6cd52020-12-02 18:13:10 +00001945 }
1946 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001947 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001948 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001949 }
1950 out_dex_files->push_back(std::move(dex_file));
1951 }
1952
1953 if (app_image) {
1954 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001955 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001956 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1957 *error_msg = "Unexpected BootClassLoader in app image";
1958 return false;
1959 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001960 }
1961
Orion Hodson5880c772020-07-28 20:12:08 +01001962 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001964 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001965 }
1966 }
1967
1968 // Set entry point to interpreter if in InterpretOnly mode.
1969 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001970 // Set image methods' entry point to interpreter.
1971 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1972 if (!method.IsRuntimeMethod()) {
1973 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001974 if (!method.IsNative() && !method.IsResolutionMethod()) {
1975 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1976 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001977 }
1978 }
1979 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001980 }
1981
Nicolas Geoffray47171752020-08-31 15:03:20 +01001982 if (!runtime->IsAotCompiler()) {
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001983 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001984 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00001985 uint16_t hotness_threshold = runtime->GetJITOptions()->GetWarmupThreshold();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001986 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01001987 // In the image, the `data` pointer field of the ArtMethod contains the code
1988 // item offset. Change this to the actual pointer to the code item.
1989 if (method.HasCodeItem()) {
1990 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
1991 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
zhaoxuyang7156ea22022-01-10 13:58:11 +08001992 method.SetCodeItem(code_item, method.GetDexFile()->IsCompactDexFile());
Nicolas Geoffray61673dc2021-11-06 13:58:31 +00001993 // The hotness counter may have changed since we compiled the image, so
1994 // reset it with the runtime value.
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00001995 method.ResetCounter(hotness_threshold);
Nicolas Geoffray47171752020-08-31 15:03:20 +01001996 }
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001997 if (method.GetEntryPointFromQuickCompiledCode() == nterp_trampoline_) {
1998 if (can_use_nterp) {
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00001999 // Set image methods' entry point that point to the nterp trampoline to the
2000 // nterp entry point. This allows taking the fast path when doing a
2001 // nterp->nterp call.
Nicolas Geoffrayb1cf8372021-02-02 13:32:20 +00002002 DCHECK(!NeedsClinitCheckBeforeCall(&method) ||
2003 method.GetDeclaringClass()->IsVisiblyInitialized());
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00002004 method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
2005 } else {
2006 method.SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2007 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01002008 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002009 }, space->Begin(), image_pointer_size_);
2010 }
2011
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00002012 if (runtime->IsVerificationSoftFail()) {
2013 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2014 if (!method.IsNative() && method.IsInvokable()) {
2015 method.ClearSkipAccessChecks();
2016 }
2017 }, space->Begin(), image_pointer_size_);
2018 }
2019
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002020 ClassTable* class_table = nullptr;
2021 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002022 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002023 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002024 }
2025 // If we have a class table section, read it and use it for verification in
2026 // UpdateAppImageClassLoadersAndDexCaches.
2027 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002028 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002029 const bool added_class_table = class_table_section.Size() > 0u;
2030 if (added_class_table) {
2031 const uint64_t start_time2 = NanoTime();
2032 size_t read_count = 0;
2033 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2034 /*make copy*/false,
2035 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002036 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002037 }
2038 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002039 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002040
2041 {
2042 ScopedTrace trace("AppImage:UpdateClassLoaders");
2043 // Update class loader and resolved strings. If added_class_table is false, the resolved
2044 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002045 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002046 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002047 // Note: We probably don't need the read barrier unless we copy the app image objects into
2048 // the region space.
2049 ObjPtr<mirror::Class> klass(root.Read());
2050 // Do not update class loader for boot image classes where the app image
2051 // class loader is only the initiating loader but not the defining loader.
2052 // Avoid read barrier since we are comparing against null.
2053 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002054 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002055 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002056 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002057 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002058
Vladimir Marko305c38b2018-02-14 11:50:07 +00002059 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002060 // Every class in the app image has initially SubtypeCheckInfo in the
2061 // Uninitialized state.
2062 //
2063 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2064 // after class initialization is complete. The app image ClassStatus as-is
2065 // are almost all ClassStatus::Initialized, and being in the
2066 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2067 //
2068 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2069 //
2070 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002071 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002072 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2073 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002074 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002075 }
2076 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002077 }
2078 if (!oat_file->GetBssGcRoots().empty()) {
2079 // Insert oat file to class table for visiting .bss GC roots.
2080 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002081 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002082
Mathieu Chartier69731002016-03-02 16:08:31 -08002083 if (added_class_table) {
2084 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2085 class_table->AddClassSet(std::move(temp_set));
2086 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002087
Mathieu Chartier69731002016-03-02 16:08:31 -08002088 if (kIsDebugBuild && app_image) {
2089 // This verification needs to happen after the classes have been added to the class loader.
2090 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002091 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002092 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002093 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002094
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002095 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002096 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002097}
2098
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002099void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002100 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2101 // enabling tracing requires the mutator lock, there are no race conditions here.
2102 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002103 Thread* const self = Thread::Current();
2104 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002105 if (kUseReadBarrier) {
2106 // We do not track new roots for CC.
2107 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2108 kVisitRootFlagClearRootLog |
2109 kVisitRootFlagStartLoggingNewRoots |
2110 kVisitRootFlagStopLoggingNewRoots));
2111 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002112 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002113 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2114 // There is 3 GC cases to handle:
2115 // Non moving concurrent:
2116 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002117 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002118 //
2119 // Moving non-concurrent:
2120 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2121 // To prevent missing roots, this case needs to ensure that there is no
2122 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2123 // class which is in the class table.
2124 //
2125 // Moving concurrent:
2126 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2127 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002128 //
2129 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2130 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2131 // these objects.
2132 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002133 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002134 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002135 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002136 for (const ClassLoaderData& data : class_loaders_) {
2137 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2138 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2139 }
2140 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002141 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002142 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002143 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002144 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002145 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002146 // Concurrent moving GC marked new roots through the to-space invariant.
2147 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002148 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002149 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2150 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2151 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2152 if (old_ref != nullptr) {
2153 DCHECK(old_ref->IsClass());
2154 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2155 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2156 // Concurrent moving GC marked new roots through the to-space invariant.
2157 CHECK_EQ(new_ref, old_ref);
2158 }
2159 }
2160 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002161 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002162 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002163 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002164 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002165 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002166 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002167 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002168 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002169 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002170 }
2171 // We deliberately ignore the class roots in the image since we
2172 // handle image roots by using the MS/CMS rescanning of dirty cards.
2173}
2174
Brian Carlstroma663ea52011-08-19 23:33:41 -07002175// Keep in sync with InitCallback. Anything we visit, we need to
2176// reinit references to when reinitializing a ClassLinker from a
2177// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002178void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002179 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002180 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002181 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2182 // unloading if we are marking roots.
2183 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002184}
2185
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002186class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2187 public:
2188 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2189 : visitor_(visitor),
2190 done_(false) {}
2191
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002192 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002193 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002194 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002195 if (!done_ && class_table != nullptr) {
2196 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2197 if (!class_table->Visit(visitor)) {
2198 // If the visitor ClassTable returns false it means that we don't need to continue.
2199 done_ = true;
2200 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002201 }
2202 }
2203
2204 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002205 // Class visitor that limits the class visits from a ClassTable to the classes with
2206 // the provided defining class loader. This filter is used to avoid multiple visits
2207 // of the same class which can be recorded for multiple initiating class loaders.
2208 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2209 public:
2210 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2211 ClassVisitor* visitor)
2212 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2213
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002214 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002215 if (klass->GetClassLoader() != defining_class_loader_) {
2216 return true;
2217 }
2218 return (*visitor_)(klass);
2219 }
2220
Vladimir Marko0984e482019-03-27 16:41:41 +00002221 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002222 ClassVisitor* const visitor_;
2223 };
2224
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002225 ClassVisitor* const visitor_;
2226 // If done is true then we don't need to do any more visiting.
2227 bool done_;
2228};
2229
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002230void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002231 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002232 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2233 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002234 }
2235}
2236
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002237void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002238 Thread* const self = Thread::Current();
2239 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2240 // Not safe to have thread suspension when we are holding a lock.
2241 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002242 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002243 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002244 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002245 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002246 }
2247}
2248
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002249class GetClassesInToVector : public ClassVisitor {
2250 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002251 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002252 classes_.push_back(klass);
2253 return true;
2254 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002255 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002256};
2257
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002258class GetClassInToObjectArray : public ClassVisitor {
2259 public:
2260 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2261 : arr_(arr), index_(0) {}
2262
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002263 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002264 ++index_;
2265 if (index_ <= arr_->GetLength()) {
2266 arr_->Set(index_ - 1, klass);
2267 return true;
2268 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002269 return false;
2270 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002271
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002272 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002273 return index_ <= arr_->GetLength();
2274 }
2275
2276 private:
2277 mirror::ObjectArray<mirror::Class>* const arr_;
2278 int32_t index_;
2279};
2280
2281void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002282 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2283 // is avoiding duplicates.
2284 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002285 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002286 GetClassesInToVector accumulator;
2287 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002288 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002289 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002290 return;
2291 }
2292 }
2293 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002294 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002295 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002296 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002297 // We size the array assuming classes won't be added to the class table during the visit.
2298 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002299 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002300 size_t class_table_size;
2301 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002302 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002303 // Add 100 in case new classes get loaded when we are filling in the object array.
2304 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002305 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002306 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002307 classes.Assign(
2308 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002309 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002310 GetClassInToObjectArray accumulator(classes.Get());
2311 VisitClasses(&accumulator);
2312 if (accumulator.Succeeded()) {
2313 break;
2314 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002315 }
2316 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2317 // If the class table shrank during creation of the clases array we expect null elements. If
2318 // the class table grew then the loop repeats. If classes are created after the loop has
2319 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002320 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002321 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002322 return;
2323 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002324 }
2325 }
2326}
2327
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002328ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002329 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002330 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002331 // CHA unloading analysis is not needed. No negative consequences are expected because
2332 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002333 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002334 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002335 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002336 while (!running_visibly_initialized_callbacks_.empty()) {
2337 std::unique_ptr<VisiblyInitializedCallback> callback(
2338 std::addressof(running_visibly_initialized_callbacks_.front()));
2339 running_visibly_initialized_callbacks_.pop_front();
2340 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002341}
2342
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002343void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002344 Runtime* const runtime = Runtime::Current();
2345 JavaVMExt* const vm = runtime->GetJavaVM();
2346 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002347 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002348 if (runtime->GetJit() != nullptr) {
2349 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2350 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002351 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002352 code_cache->RemoveMethodsIn(self, *data.allocator);
2353 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002354 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002355 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002356 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002357 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002358 // Cleanup references to single implementation ArtMethods that will be deleted.
2359 if (cleanup_cha) {
2360 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2361 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2362 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002363 {
2364 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2365 auto end = critical_native_code_with_clinit_check_.end();
2366 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2367 if (data.allocator->ContainsUnsafe(it->first)) {
2368 it = critical_native_code_with_clinit_check_.erase(it);
2369 } else {
2370 ++it;
2371 }
2372 }
2373 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002374
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002375 delete data.allocator;
2376 delete data.class_table;
2377}
2378
Vladimir Markobcf17522018-06-01 13:14:32 +01002379ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2380 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002381 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002382 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2383 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002384}
2385
David Srbecky86d6cd52020-12-02 18:13:10 +00002386ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002387 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002388 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002389 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002390 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002391 self->AssertPendingOOMException();
2392 return nullptr;
2393 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002394 // Use InternWeak() so that the location String can be collected when the ClassLoader
2395 // with this DexCache is collected.
2396 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002397 if (location == nullptr) {
2398 self->AssertPendingOOMException();
2399 return nullptr;
2400 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002401 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002402 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002403}
2404
David Srbecky33df0e32021-09-30 14:36:32 +00002405ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(
2406 Thread* self, const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
2407 StackHandleScope<1> hs(self);
2408 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00002409 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002410 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002411 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky33df0e32021-09-30 14:36:32 +00002412 dex_cache->Initialize(&dex_file, h_class_loader.Get());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002413 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002414 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002415}
2416
Vladimir Marko70e2a762019-07-12 16:49:00 +01002417template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002418ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2419 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002420 uint32_t class_size,
2421 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002422 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002423 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002424 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002425 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2426 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002427 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002428 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002429 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002430 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002431 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002432}
2433
Vladimir Marko70e2a762019-07-12 16:49:00 +01002434template <bool kMovable>
2435ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2436 ObjPtr<mirror::Class> java_lang_Class,
2437 uint32_t class_size) {
2438 mirror::Class::InitializeClassVisitor visitor(class_size);
2439 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2440}
2441
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002442ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002443 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002444}
2445
Vladimir Marko70e2a762019-07-12 16:49:00 +01002446void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2447 ClassRoot primitive_root,
2448 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002449 // We make this class non-movable for the unlikely case where it were to be
2450 // moved by a sticky-bit (minor) collection when using the Generational
2451 // Concurrent Copying (CC) collector, potentially creating a stale reference
2452 // in the `klass_` field of one of its instances allocated in the Large-Object
2453 // Space (LOS) -- see the comment about the dirty card scanning logic in
2454 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002455 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2456 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2457 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2458 DCHECK(component_type->IsPrimitive());
2459 array_class->SetComponentType(component_type);
2460 SetClassRoot(array_root, array_class);
2461}
2462
2463void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2464 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2465 array_class->SetSuperClass(java_lang_Object);
2466 array_class->SetVTable(java_lang_Object->GetVTable());
2467 array_class->SetPrimitiveType(Primitive::kPrimNot);
2468 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2469 array_class->SetClassFlags(component_type->IsPrimitive()
2470 ? mirror::kClassFlagNoReferenceFields
2471 : mirror::kClassFlagObjectArray);
2472 array_class->SetClassLoader(component_type->GetClassLoader());
2473 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2474 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2475 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2476 array_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002477 DCHECK_EQ(array_class->NumMethods(), 0u);
2478
2479 // don't need to set new_class->SetObjectSize(..)
2480 // because Object::SizeOf delegates to Array::SizeOf
2481
2482 // All arrays have java/lang/Cloneable and java/io/Serializable as
2483 // interfaces. We need to set that up here, so that stuff like
2484 // "instanceof" works right.
2485
2486 // Use the single, global copies of "interfaces" and "iftable"
2487 // (remember not to free them for arrays).
2488 {
2489 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2490 CHECK(array_iftable != nullptr);
2491 array_class->SetIfTable(array_iftable);
2492 }
2493
2494 // Inherit access flags from the component type.
2495 int access_flags = component_type->GetAccessFlags();
2496 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2497 access_flags &= kAccJavaFlagsMask;
2498 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2499 // and remove "interface".
2500 access_flags |= kAccAbstract | kAccFinal;
2501 access_flags &= ~kAccInterface;
Vladimir Marko70e2a762019-07-12 16:49:00 +01002502
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002503 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002504
Vladimir Markobf121912019-06-04 13:49:05 +01002505 // Array classes are fully initialized either during single threaded startup,
2506 // or from a pre-fence visitor, so visibly initialized.
2507 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002508}
2509
2510void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2511 // Do not hold lock on the array class object, the initialization of
2512 // core array classes is done while the process is still single threaded.
2513 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2514 FinishArrayClassSetup(array_class);
2515
2516 std::string temp;
2517 const char* descriptor = array_class->GetDescriptor(&temp);
2518 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2519 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2520 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002521}
2522
Vladimir Markobcf17522018-06-01 13:14:32 +01002523ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002524 Thread* self,
2525 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002526 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002527 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002528}
2529
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002530ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2531 const char* descriptor,
2532 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002533 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002534 if (kIsDebugBuild) {
2535 StackHandleScope<1> hs(self);
2536 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2537 Thread::PoisonObjectPointersIfDebug();
2538 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002539
2540 // For temporary classes we must wait for them to be retired.
2541 if (init_done_ && klass->IsTemp()) {
2542 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002543 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002544 ThrowEarlierClassFailure(klass);
2545 return nullptr;
2546 }
2547 StackHandleScope<1> hs(self);
2548 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2549 ObjectLock<mirror::Class> lock(self, h_class);
2550 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002551 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002552 lock.WaitIgnoringInterrupts();
2553 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002554 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002555 ThrowEarlierClassFailure(h_class.Get());
2556 return nullptr;
2557 }
2558 CHECK(h_class->IsRetired());
2559 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002560 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002561 }
2562
Brian Carlstromaded5f72011-10-07 17:15:04 -07002563 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002564 size_t index = 0;
2565 // Maximum number of yield iterations until we start sleeping.
2566 static const size_t kNumYieldIterations = 1000;
2567 // How long each sleep is in us.
2568 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002569 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002570 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002571 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002572 {
2573 ObjectTryLock<mirror::Class> lock(self, h_class);
2574 // Can not use a monitor wait here since it may block when returning and deadlock if another
2575 // thread has locked klass.
2576 if (lock.Acquired()) {
2577 // Check for circular dependencies between classes, the lock is required for SetStatus.
2578 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2579 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002580 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002581 return nullptr;
2582 }
2583 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002585 {
2586 // Handle wrapper deals with klass moving.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002587 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002588 if (index < kNumYieldIterations) {
2589 sched_yield();
2590 } else {
2591 usleep(kSleepDurationUS);
2592 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002593 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002594 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002596
Vladimir Marko72ab6842017-01-20 19:32:50 +00002597 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002598 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002599 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002600 }
2601 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002602 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002603 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002604 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002605}
2606
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002607using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002608
2609// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002610ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002611 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002612 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002613 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002614 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002615 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002616 return ClassPathEntry(dex_file, dex_class_def);
2617 }
2618 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002619 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002620}
2621
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002622// Helper macro to make sure each class loader lookup call handles the case the
2623// class loader is not recognized, or the lookup threw an exception.
2624#define RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(call_, result_, thread_) \
2625do { \
2626 auto local_call = call_; \
2627 if (!local_call) { \
2628 return false; \
2629 } \
2630 auto local_result = result_; \
2631 if (local_result != nullptr) { \
2632 return true; \
2633 } \
2634 auto local_thread = thread_; \
2635 if (local_thread->IsExceptionPending()) { \
2636 /* Pending exception means there was an error other than */ \
2637 /* ClassNotFound that must be returned to the caller. */ \
2638 return false; \
2639 } \
2640} while (0)
2641
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002642bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2643 Thread* self,
2644 const char* descriptor,
2645 size_t hash,
2646 Handle<mirror::ClassLoader> class_loader,
2647 /*out*/ ObjPtr<mirror::Class>* result) {
2648 ArtField* field =
2649 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
Brad Stenning9c924e82021-10-11 19:09:00 -07002650 return FindClassInSharedLibrariesHelper(soa, self, descriptor, hash, class_loader, field, result);
2651}
2652
2653bool ClassLinker::FindClassInSharedLibrariesHelper(ScopedObjectAccessAlreadyRunnable& soa,
2654 Thread* self,
2655 const char* descriptor,
2656 size_t hash,
2657 Handle<mirror::ClassLoader> class_loader,
2658 ArtField* field,
2659 /*out*/ ObjPtr<mirror::Class>* result) {
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002660 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2661 if (raw_shared_libraries == nullptr) {
2662 return true;
2663 }
2664
2665 StackHandleScope<2> hs(self);
2666 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2667 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2668 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002669 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2670 temp_loader.Assign(loader);
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002671 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2672 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result),
2673 *result,
2674 self);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002675 }
2676 return true;
2677}
2678
Brad Stenning9c924e82021-10-11 19:09:00 -07002679bool ClassLinker::FindClassInSharedLibrariesAfter(ScopedObjectAccessAlreadyRunnable& soa,
2680 Thread* self,
2681 const char* descriptor,
2682 size_t hash,
2683 Handle<mirror::ClassLoader> class_loader,
2684 /*out*/ ObjPtr<mirror::Class>* result) {
2685 ArtField* field = jni::DecodeArtField(
2686 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
2687 return FindClassInSharedLibrariesHelper(soa, self, descriptor, hash, class_loader, field, result);
2688}
2689
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002690bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2691 Thread* self,
2692 const char* descriptor,
2693 size_t hash,
2694 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002695 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002696 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002697 if (IsBootClassLoader(soa, class_loader.Get())) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002698 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2699 FindClassInBootClassLoaderClassPath(self, descriptor, hash, result), *result, self);
Andreas Gampef865ea92015-04-13 22:14:19 -07002700 return true;
2701 }
2702
David Brazdil05909d82018-12-06 16:25:16 +00002703 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002704 // For regular path or dex class loader the search order is:
2705 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002706 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002707 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002708
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002709 // Create a handle as RegisterDexFile may allocate dex caches (and cause thread suspension).
Calin Juravlecdd49122017-07-05 20:09:53 -07002710 StackHandleScope<1> hs(self);
2711 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002712 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2713 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result),
2714 *result,
2715 self);
2716 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2717 FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result),
2718 *result,
2719 self);
2720 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2721 FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader, result),
2722 *result,
2723 self);
Brad Stenning9c924e82021-10-11 19:09:00 -07002724 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2725 FindClassInSharedLibrariesAfter(soa, self, descriptor, hash, class_loader, result),
2726 *result,
2727 self);
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002728 // We did not find a class, but the class loader chain was recognized, so we
2729 // return true.
2730 return true;
Andreas Gampef865ea92015-04-13 22:14:19 -07002731 }
2732
Calin Juravlecdd49122017-07-05 20:09:53 -07002733 if (IsDelegateLastClassLoader(soa, class_loader)) {
2734 // For delegate last, the search order is:
2735 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002736 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002737 // - class loader dex files
2738 // - parent
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002739 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2740 FindClassInBootClassLoaderClassPath(self, descriptor, hash, result), *result, self);
2741 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2742 FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result),
2743 *result,
2744 self);
2745 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2746 FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader, result),
2747 *result,
2748 self);
Brad Stenning9c924e82021-10-11 19:09:00 -07002749 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2750 FindClassInSharedLibrariesAfter(soa, self, descriptor, hash, class_loader, result),
2751 *result,
2752 self);
Calin Juravlecdd49122017-07-05 20:09:53 -07002753
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002754 // Create a handle as RegisterDexFile may allocate dex caches (and cause thread suspension).
Calin Juravlecdd49122017-07-05 20:09:53 -07002755 StackHandleScope<1> hs(self);
2756 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002757 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2758 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result),
2759 *result,
2760 self);
2761 // We did not find a class, but the class loader chain was recognized, so we
2762 // return true.
2763 return true;
Calin Juravlecdd49122017-07-05 20:09:53 -07002764 }
2765
2766 // Unsupported class loader.
2767 *result = nullptr;
2768 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002769}
2770
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002771#undef RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION
2772
Andreas Gampe501c3b02019-04-17 21:54:27 +00002773namespace {
2774
2775// Matches exceptions caught in DexFile.defineClass.
2776ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2777 ClassLinker* class_linker)
2778 REQUIRES_SHARED(Locks::mutator_lock_) {
2779 return
2780 // ClassNotFoundException.
2781 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2782 class_linker))
2783 ||
2784 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2785 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2786}
2787
2788// Clear exceptions caught in DexFile.defineClass.
2789ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2790 REQUIRES_SHARED(Locks::mutator_lock_) {
2791 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2792 self->ClearException();
2793 }
2794}
2795
2796} // namespace
2797
Calin Juravle415dc3d2017-06-28 11:03:12 -07002798// Finds the class in the boot class loader.
2799// If the class is found the method returns the resolved class. Otherwise it returns null.
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002800bool ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2801 const char* descriptor,
2802 size_t hash,
2803 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002804 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2805 if (pair.second != nullptr) {
2806 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2807 if (klass != nullptr) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002808 *result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002809 } else {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002810 *result = DefineClass(self,
2811 descriptor,
2812 hash,
2813 ScopedNullHandle<mirror::ClassLoader>(),
2814 *pair.first,
2815 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002816 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002817 if (*result == nullptr) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002818 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002819 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002820 }
2821 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002822 // The boot classloader is always a known lookup.
2823 return true;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002824}
Andreas Gampef865ea92015-04-13 22:14:19 -07002825
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002826bool ClassLinker::FindClassInBaseDexClassLoaderClassPath(
Calin Juravle415dc3d2017-06-28 11:03:12 -07002827 ScopedObjectAccessAlreadyRunnable& soa,
2828 const char* descriptor,
2829 size_t hash,
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002830 Handle<mirror::ClassLoader> class_loader,
2831 /*out*/ ObjPtr<mirror::Class>* result) {
David Brazdil05909d82018-12-06 16:25:16 +00002832 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2833 IsInMemoryDexClassLoader(soa, class_loader) ||
2834 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002835 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002836
Vladimir Marko68c07582021-04-19 16:01:15 +00002837 const DexFile* dex_file = nullptr;
2838 const dex::ClassDef* class_def = nullptr;
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002839 ObjPtr<mirror::Class> ret;
Vladimir Marko68c07582021-04-19 16:01:15 +00002840 auto find_class_def = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2841 const dex::ClassDef* cp_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2842 if (cp_class_def != nullptr) {
2843 dex_file = cp_dex_file;
2844 class_def = cp_class_def;
2845 return false; // Found a class definition, stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002846 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002847 return true; // Continue with the next DexFile.
2848 };
Vladimir Marko68c07582021-04-19 16:01:15 +00002849 VisitClassLoaderDexFiles(soa, class_loader, find_class_def);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002850
Vladimir Marko68c07582021-04-19 16:01:15 +00002851 if (class_def != nullptr) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002852 *result = DefineClass(soa.Self(), descriptor, hash, class_loader, *dex_file, *class_def);
2853 if (UNLIKELY(*result == nullptr)) {
Vladimir Marko68c07582021-04-19 16:01:15 +00002854 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2855 FilterDexFileCaughtExceptions(soa.Self(), this);
2856 } else {
2857 DCHECK(!soa.Self()->IsExceptionPending());
2858 }
2859 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002860 // A BaseDexClassLoader is always a known lookup.
2861 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002862}
2863
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002864ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2865 const char* descriptor,
2866 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002867 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002868 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002869 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002870 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002871 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002872 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2873 // for primitive classes that aren't backed by dex files.
2874 return FindPrimitiveClass(descriptor[0]);
2875 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002876 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002877 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002878 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002879 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002880 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002881 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002882 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002883 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002884 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002885 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002886 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002887 return DefineClass(self,
2888 descriptor,
2889 hash,
2890 ScopedNullHandle<mirror::ClassLoader>(),
2891 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002892 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002893 } else {
2894 // The boot class loader is searched ahead of the application class loader, failures are
2895 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2896 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002897 ObjPtr<mirror::Throwable> pre_allocated =
2898 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002899 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002900 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002901 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002902 }
2903 ObjPtr<mirror::Class> result_ptr;
2904 bool descriptor_equals;
2905 if (descriptor[0] == '[') {
2906 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2907 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2908 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2909 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002910 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002911 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002912 bool known_hierarchy =
2913 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2914 if (result_ptr != nullptr) {
2915 // The chain was understood and we found the class. We still need to add the class to
2916 // the class table to protect from racy programs that can try and redefine the path list
2917 // which would change the Class<?> returned for subsequent evaluation of const-class.
2918 DCHECK(known_hierarchy);
2919 DCHECK(result_ptr->DescriptorEquals(descriptor));
2920 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002921 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002922 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002923 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2924 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002925 //
2926 // If the chain was understood but we did not find the class, let the Java-side
2927 // rediscover all this and throw the exception with the right stack trace. Note that
2928 // the Java-side could still succeed for racy programs if another thread is actively
2929 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002930
Alex Light185a4612018-10-04 15:54:25 -07002931 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002932 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002933 // Oops, we can't call into java so we can't run actual class-loader code.
2934 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002935 ObjPtr<mirror::Throwable> pre_allocated =
2936 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2937 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002938 return nullptr;
2939 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002940
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002941 // Inlined DescriptorToDot(descriptor) with extra validation.
2942 //
2943 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2944 // the DescriptorEquals() check below and give a confusing error message. For example,
2945 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2946 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2947 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2948 size_t descriptor_length = strlen(descriptor);
2949 if (UNLIKELY(descriptor[0] != 'L') ||
2950 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2951 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2952 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2953 return nullptr;
2954 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002955
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002956 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2957 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002958 if (known_hierarchy &&
2959 fast_class_not_found_exceptions_ &&
2960 !Runtime::Current()->IsJavaDebuggable()) {
2961 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2962 // debuggable, optimize this path by throwing directly here without going back to Java
2963 // language. This reduces how many ClassNotFoundExceptions happen.
2964 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2965 "%s",
2966 class_name_string.c_str());
2967 } else {
2968 ScopedLocalRef<jobject> class_loader_object(
2969 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2970 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2971 {
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002972 ScopedThreadStateChange tsc(self, ThreadState::kNative);
Andreas Gampe87658f32019-04-18 18:39:02 +00002973 ScopedLocalRef<jobject> class_name_object(
2974 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2975 if (class_name_object.get() == nullptr) {
2976 DCHECK(self->IsExceptionPending()); // OOME.
2977 return nullptr;
2978 }
2979 CHECK(class_loader_object.get() != nullptr);
2980 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2981 WellKnownClasses::java_lang_ClassLoader_loadClass,
2982 class_name_object.get()));
2983 }
2984 if (result.get() == nullptr && !self->IsExceptionPending()) {
2985 // broken loader - throw NPE to be compatible with Dalvik
2986 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2987 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002988 return nullptr;
2989 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002990 result_ptr = soa.Decode<mirror::Class>(result.get());
2991 // Check the name of the returned class.
2992 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002993 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002994 } else {
2995 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002996 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002997 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002998
2999 if (self->IsExceptionPending()) {
3000 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3001 // However, to comply with the RI behavior, first check if another thread succeeded.
3002 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3003 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3004 self->ClearException();
3005 return EnsureResolved(self, descriptor, result_ptr);
3006 }
3007 return nullptr;
3008 }
3009
3010 // Try to insert the class to the class table, checking for mismatch.
3011 ObjPtr<mirror::Class> old;
3012 {
3013 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3014 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3015 old = class_table->Lookup(descriptor, hash);
3016 if (old == nullptr) {
3017 old = result_ptr; // For the comparison below, after releasing the lock.
3018 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003019 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003020 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003021 } // else throw below, after releasing the lock.
3022 }
3023 }
3024 if (UNLIKELY(old != result_ptr)) {
3025 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3026 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003027 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003028 const char* loader_class_name =
3029 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3030 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3031 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3032 << DescriptorToDot(descriptor) << "\").";
3033 return EnsureResolved(self, descriptor, old);
3034 }
3035 if (UNLIKELY(!descriptor_equals)) {
3036 std::string result_storage;
3037 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3038 std::string loader_storage;
3039 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3040 ThrowNoClassDefFoundError(
3041 "Initiating class loader of type %s returned class %s instead of %s.",
3042 DescriptorToDot(loader_class_name).c_str(),
3043 DescriptorToDot(result_name).c_str(),
3044 DescriptorToDot(descriptor).c_str());
3045 return nullptr;
3046 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003047 // Success.
3048 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003049}
3050
Alex Light270db1c2019-12-03 12:20:01 +00003051// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3052// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3053// like pausing class definition.
3054struct ScopedDefiningClass {
3055 public:
3056 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3057 : self_(self), returned_(false) {
3058 Locks::mutator_lock_->AssertSharedHeld(self_);
3059 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3060 self_->IncrDefineClassCount();
3061 }
3062 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3063 Locks::mutator_lock_->AssertSharedHeld(self_);
3064 CHECK(returned_);
3065 }
3066
3067 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3068 REQUIRES_SHARED(Locks::mutator_lock_) {
3069 CHECK(!returned_);
3070 self_->DecrDefineClassCount();
3071 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3072 Thread::PoisonObjectPointersIfDebug();
3073 returned_ = true;
3074 return h_klass.Get();
3075 }
3076
3077 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3078 REQUIRES_SHARED(Locks::mutator_lock_) {
3079 StackHandleScope<1> hs(self_);
3080 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3081 return Finish(h_klass);
3082 }
3083
3084 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3085 REQUIRES_SHARED(Locks::mutator_lock_) {
3086 ScopedNullHandle<mirror::Class> snh;
3087 return Finish(snh);
3088 }
3089
3090 private:
3091 Thread* self_;
3092 bool returned_;
3093};
3094
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003095ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3096 const char* descriptor,
3097 size_t hash,
3098 Handle<mirror::ClassLoader> class_loader,
3099 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003100 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003101 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003102 StackHandleScope<3> hs(self);
Eric Holk74584e62021-02-18 14:39:17 -08003103 metrics::AutoTimer timer{GetMetrics()->ClassLoadingTotalTime()};
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003104 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003105
Brian Carlstromaded5f72011-10-07 17:15:04 -07003106 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003107 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003108 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003109 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003110 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003111 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003112 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003113 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003114 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003115 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003116 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003117 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003118 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003119 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003120 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003121 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003122 }
3123
Calin Juravle33787682019-07-26 14:27:18 -07003124 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3125 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3126 // public class path then we prevent the definition of the class.
3127 //
3128 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3129 // classpath is not checked.
3130 if (class_loader == nullptr &&
3131 Runtime::Current()->IsAotCompiler() &&
3132 DenyAccessBasedOnPublicSdk(descriptor)) {
3133 ObjPtr<mirror::Throwable> pre_allocated =
3134 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3135 self->SetException(pre_allocated);
3136 return sdc.Finish(nullptr);
3137 }
3138
Alex Lighte9f61032018-09-24 16:04:51 -07003139 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3140 // code to be executed. We put it up here so we can avoid all the allocations associated with
3141 // creating the class. This can happen with (eg) jit threads.
3142 if (!self->CanLoadClasses()) {
3143 // Make sure we don't try to load anything, potentially causing an infinite loop.
3144 ObjPtr<mirror::Throwable> pre_allocated =
3145 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3146 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003147 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003148 }
3149
Andreas Gampefa4333d2017-02-14 11:10:34 -08003150 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003151 // Allocate a class with the status of not ready.
3152 // Interface object should get the right size here. Regular class will
3153 // figure out the right size later and be replaced with one of the right
3154 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003155 if (CanAllocClass()) {
3156 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3157 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003158 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003159 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003160 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003161 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003162 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003163 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003164 }
Alex Lightb0f11922017-01-23 14:25:17 -08003165 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3166 // nothing.
3167 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003168 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003169 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3170 // will only be called once.
3171 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3172 klass,
3173 class_loader,
3174 dex_file,
3175 dex_class_def,
3176 &new_dex_file,
3177 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003178 // Check to see if an exception happened during runtime callbacks. Return if so.
3179 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003180 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003181 }
Alex Lightb0f11922017-01-23 14:25:17 -08003182 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003183 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003184 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003185 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003186 }
3187 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003188 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003189
Jeff Hao848f70a2014-01-15 13:49:50 -08003190 // Mark the string class by setting its access flag.
3191 if (UNLIKELY(!init_done_)) {
3192 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3193 klass->SetStringClass();
3194 }
3195 }
3196
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003197 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003198 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003199 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003200 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003201
Mathieu Chartier590fee92013-09-13 13:46:47 -07003202 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003203 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003204 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003205 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3206 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003207 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003208 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003209
Mathieu Chartierc7853442015-03-27 14:35:38 -07003210 // Load the fields and other things after we are inserted in the table. This is so that we don't
3211 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3212 // other reason is that the field roots are only visited from the class table. So we need to be
3213 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003214 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003215 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003216 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003217 // An exception occured during load, set status to erroneous while holding klass' lock in case
3218 // notification is necessary.
3219 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003220 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003221 }
Alex Light270db1c2019-12-03 12:20:01 +00003222 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003223 }
3224
Brian Carlstromaded5f72011-10-07 17:15:04 -07003225 // Finish loading (if necessary) by finding parents
3226 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003227 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003228 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003229 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003230 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003231 }
Alex Light270db1c2019-12-03 12:20:01 +00003232 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003233 }
3234 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003235
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003236 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003237 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003238 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003239
Brian Carlstromaded5f72011-10-07 17:15:04 -07003240 // Link the class (if necessary)
3241 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003242 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003243 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003244
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003245 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003246 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003247 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003248 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003249 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003250 }
Alex Light270db1c2019-12-03 12:20:01 +00003251 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003252 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003253 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003254 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Markof9e82e52021-10-06 08:34:40 +01003255 CHECK(h_new_class->IsResolved()) << descriptor << " " << h_new_class->GetStatus();
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003256
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003257 // Instrumentation may have updated entrypoints for all methods of all
3258 // classes. However it could not update methods of this class while we
3259 // were loading it. Now the class is resolved, we can update entrypoints
3260 // as required by instrumentation.
3261 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3262 // We must be in the kRunnable state to prevent instrumentation from
3263 // suspending all threads to update entrypoints while we are doing it
3264 // for this class.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00003265 DCHECK_EQ(self->GetState(), ThreadState::kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003266 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003267 }
3268
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003269 /*
3270 * We send CLASS_PREPARE events to the debugger from here. The
3271 * definition of "preparation" is creating the static fields for a
3272 * class and initializing them to the standard default values, but not
3273 * executing any code (that comes later, during "initialization").
3274 *
3275 * We did the static preparation in LinkClass.
3276 *
3277 * The class has been prepared and resolved but possibly not yet verified
3278 * at this point.
3279 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003280 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003281
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003282 // Notify native debugger of the new class and its layout.
3283 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3284
Alex Light270db1c2019-12-03 12:20:01 +00003285 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003286}
3287
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003288uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003289 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003290 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003291 size_t num_8 = 0;
3292 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003293 size_t num_32 = 0;
3294 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003295 ClassAccessor accessor(dex_file, dex_class_def);
3296 // We allow duplicate definitions of the same field in a class_data_item
3297 // but ignore the repeated indexes here, b/21868015.
3298 uint32_t last_field_idx = dex::kDexNoIndex;
3299 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3300 uint32_t field_idx = field.GetIndex();
3301 // Ordering enforced by DexFileVerifier.
3302 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3303 if (UNLIKELY(field_idx == last_field_idx)) {
3304 continue;
3305 }
3306 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003307 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003308 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3309 char c = descriptor[0];
3310 switch (c) {
3311 case 'L':
3312 case '[':
3313 num_ref++;
3314 break;
3315 case 'J':
3316 case 'D':
3317 num_64++;
3318 break;
3319 case 'I':
3320 case 'F':
3321 num_32++;
3322 break;
3323 case 'S':
3324 case 'C':
3325 num_16++;
3326 break;
3327 case 'B':
3328 case 'Z':
3329 num_8++;
3330 break;
3331 default:
3332 LOG(FATAL) << "Unknown descriptor: " << c;
3333 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003334 }
3335 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003336 return mirror::Class::ComputeClassSize(false,
3337 0,
3338 num_8,
3339 num_16,
3340 num_32,
3341 num_64,
3342 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003343 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003344}
3345
Vladimir Marko86c87522020-05-11 16:55:55 +01003346void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003347 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003348 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003349 size_t num_direct_methods = klass->NumDirectMethods();
3350 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003351 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003352 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003353 if (UNLIKELY(klass->IsProxyClass())) {
3354 return;
3355 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003356 PointerSize pointer_size = image_pointer_size_;
3357 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3358 klass->GetDirectMethods(pointer_size).end(),
3359 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3360 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3361 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3362 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3363 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3364 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3365 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3366 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3367 lb->first->SetEntryPointFromJni(lb->second);
3368 lb = critical_native_code_with_clinit_check_.erase(lb);
3369 }
3370 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003371 Runtime* runtime = Runtime::Current();
Nicolas Geoffray854af032021-12-21 08:32:42 +00003372 if (runtime->IsAotCompiler()) {
3373 // We should not update entrypoints when running the transactional
3374 // interpreter.
3375 return;
Ian Rogers19846512012-02-24 11:42:47 -08003376 }
Alex Light64ad14d2014-08-19 14:23:13 -07003377
Nicolas Geoffrayc8a694d2022-01-17 17:12:38 +00003378 instrumentation::Instrumentation* instrumentation = runtime->GetInstrumentation();
Ian Rogers1c829822013-09-30 18:18:50 -07003379 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003380 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3381 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003382 if (!method->IsStatic()) {
3383 // Only update static methods.
3384 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003385 }
Nicolas Geoffray854af032021-12-21 08:32:42 +00003386 instrumentation->UpdateMethodsCode(method, instrumentation->GetCodeForInvoke(method));
Ian Rogers19846512012-02-24 11:42:47 -08003387 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003388 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003389}
3390
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003391// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3392// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003393inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3394 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003395 DCHECK(method != nullptr);
3396 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003397 method->SetEntryPointFromQuickCompiledCodePtrSize(
3398 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3399 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003400}
3401
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003402static void LinkCode(ClassLinker* class_linker,
3403 ArtMethod* method,
3404 const OatFile::OatClass* oat_class,
3405 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003406 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003407 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003408 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003409 // The following code only applies to a non-compiler runtime.
3410 return;
3411 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003412
Ian Rogers62d6c772013-02-27 08:32:07 -08003413 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003414 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray854af032021-12-21 08:32:42 +00003415 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
Jeff Hao16743632013-05-08 10:59:04 -07003416
Alex Light9139e002015-10-09 15:59:48 -07003417 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003418 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003419 return;
3420 }
Ian Rogers19846512012-02-24 11:42:47 -08003421
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003422 const void* quick_code = nullptr;
3423 if (oat_class != nullptr) {
3424 // Every kind of method should at least get an invoke stub from the oat_method.
3425 // non-abstract methods also get their code pointers.
3426 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3427 quick_code = oat_method.GetQuickCode();
3428 }
Nicolas Geoffray854af032021-12-21 08:32:42 +00003429 runtime->GetInstrumentation()->InitializeMethodsCode(method, quick_code);
jeffhao26c0a1a2012-01-17 16:28:33 -08003430
Ian Rogers62d6c772013-02-27 08:32:07 -08003431 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003432 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3433 // as the extra processing for @CriticalNative is not needed yet.
3434 method->SetEntryPointFromJni(
3435 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Brian Carlstrom92827a52011-10-10 15:50:01 -07003436 }
3437}
3438
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003439void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003440 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003441 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003442 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003443 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003444 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003445 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003446 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003447 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003448
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003449 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003450 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003451 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003452 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003453 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003454 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003455 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003456
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003457 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003458 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003459}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003460
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003461LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3462 LinearAlloc* allocator,
3463 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003464 if (length == 0) {
3465 return nullptr;
3466 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003467 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3468 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3469 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003470 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003471 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003472 CHECK(ret != nullptr);
3473 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3474 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003475}
3476
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003477LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3478 LinearAlloc* allocator,
3479 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003480 if (length == 0) {
3481 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003482 }
Vladimir Marko14632852015-08-17 12:07:23 +01003483 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3484 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003485 const size_t storage_size =
3486 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003487 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003488 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003489 CHECK(ret != nullptr);
3490 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003491 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003492 }
3493 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003494}
3495
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003496LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003497 if (class_loader == nullptr) {
3498 return Runtime::Current()->GetLinearAlloc();
3499 }
3500 LinearAlloc* allocator = class_loader->GetAllocator();
3501 DCHECK(allocator != nullptr);
3502 return allocator;
3503}
3504
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003505LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003506 if (class_loader == nullptr) {
3507 return Runtime::Current()->GetLinearAlloc();
3508 }
3509 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3510 LinearAlloc* allocator = class_loader->GetAllocator();
3511 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003512 RegisterClassLoader(class_loader);
3513 allocator = class_loader->GetAllocator();
3514 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003515 }
3516 return allocator;
3517}
3518
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003519void ClassLinker::LoadClass(Thread* self,
3520 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003521 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003522 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003523 ClassAccessor accessor(dex_file,
3524 dex_class_def,
3525 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003526 if (!accessor.HasClassData()) {
3527 return;
3528 }
3529 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003530 {
3531 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3532 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003533 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003534 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003535 // We allow duplicate definitions of the same field in a class_data_item
3536 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003537 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003538 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3539 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003540 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003541 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3542 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003543 accessor.NumInstanceFields());
3544 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003545 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003546 uint32_t last_static_field_idx = 0u;
3547 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003548
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003549 // Methods
3550 bool has_oat_class = false;
3551 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3552 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3553 : OatFile::OatClass::Invalid();
3554 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3555 klass->SetMethodsPtr(
3556 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3557 accessor.NumDirectMethods(),
3558 accessor.NumVirtualMethods());
3559 size_t class_def_method_index = 0;
3560 uint32_t last_dex_method_index = dex::kDexNoIndex;
3561 size_t last_class_def_method_index = 0;
3562
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003563 uint16_t hotness_threshold = runtime->GetJITOptions()->GetWarmupThreshold();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003564 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3565 // methods needs to decode all of the fields.
3566 accessor.VisitFieldsAndMethods([&](
3567 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3568 uint32_t field_idx = field.GetIndex();
3569 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3570 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3571 LoadField(field, klass, &sfields->At(num_sfields));
3572 ++num_sfields;
3573 last_static_field_idx = field_idx;
3574 }
3575 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3576 uint32_t field_idx = field.GetIndex();
3577 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3578 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3579 LoadField(field, klass, &ifields->At(num_ifields));
3580 ++num_ifields;
3581 last_instance_field_idx = field_idx;
3582 }
3583 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3584 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3585 image_pointer_size_);
3586 LoadMethod(dex_file, method, klass, art_method);
3587 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3588 uint32_t it_method_index = method.GetIndex();
3589 if (last_dex_method_index == it_method_index) {
3590 // duplicate case
3591 art_method->SetMethodIndex(last_class_def_method_index);
3592 } else {
3593 art_method->SetMethodIndex(class_def_method_index);
3594 last_dex_method_index = it_method_index;
3595 last_class_def_method_index = class_def_method_index;
3596 }
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003597 art_method->ResetCounter(hotness_threshold);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003598 ++class_def_method_index;
3599 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3600 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3601 class_def_method_index - accessor.NumDirectMethods(),
3602 image_pointer_size_);
Nicolas Geoffray58f916c2021-11-15 14:02:07 +00003603 art_method->ResetCounter(hotness_threshold);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003604 LoadMethod(dex_file, method, klass, art_method);
3605 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3606 ++class_def_method_index;
3607 });
3608
3609 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003610 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003611 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3612 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3613 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003614 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3615 if (sfields != nullptr) {
3616 sfields->SetSize(num_sfields);
3617 }
3618 if (ifields != nullptr) {
3619 ifields->SetSize(num_ifields);
3620 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003621 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003622 // Set the field arrays.
3623 klass->SetSFieldsPtr(sfields);
3624 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003625 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003626 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003627 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003628 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003629 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003630 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003631}
3632
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003633void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003634 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003635 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003636 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003637 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003638 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003639
David Brazdil85865692018-10-30 17:26:20 +00003640 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3641 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003642}
3643
Mathieu Chartier268764d2016-09-13 12:09:38 -07003644void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003645 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003646 Handle<mirror::Class> klass,
3647 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003648 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003649 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003650 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003651
Mathieu Chartier268764d2016-09-13 12:09:38 -07003652 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003653 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003654 dst->SetDeclaringClass(klass.Get());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003655
David Brazdil85865692018-10-30 17:26:20 +00003656 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3657 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003658
Ian Rogersdfb325e2013-10-30 01:00:44 -07003659 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003660 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003661 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3662 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003663 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003664 klass->SetFinalizable();
3665 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003666 std::string temp;
3667 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003668 // The Enum class declares a "final" finalize() method to prevent subclasses from
3669 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3670 // subclasses, so we exclude it here.
3671 // We also want to avoid setting the flag on Object, where we know that finalize() is
3672 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003673 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3674 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003675 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003676 }
3677 }
3678 }
3679 } else if (method_name[0] == '<') {
3680 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003681 bool is_init = (strcmp("<init>", method_name) == 0);
3682 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003683 if (UNLIKELY(!is_init && !is_clinit)) {
3684 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3685 } else {
3686 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3687 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003688 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003689 access_flags |= kAccConstructor;
3690 }
3691 }
3692 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003693 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3694 // Check if the native method is annotated with @FastNative or @CriticalNative.
3695 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3696 dex_file, dst->GetClassDef(), dex_method_idx);
Kevin Jeon8515f7f2022-01-12 00:15:26 +00003697 } else if ((access_flags & kAccAbstract) == 0u &&
3698 annotations::MethodIsNeverCompile(dex_file, dst->GetClassDef(), dex_method_idx)) {
Kevin Jeon55737562021-11-19 20:39:30 +00003699 access_flags |= kAccCompileDontBother;
3700 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003701 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003702 // Must be done after SetAccessFlags since IsAbstract depends on it.
3703 if (klass->IsInterface() && dst->IsAbstract()) {
3704 dst->CalculateAndSetImtIndex();
3705 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01003706 if (dst->HasCodeItem()) {
3707 DCHECK_NE(method.GetCodeItemOffset(), 0u);
3708 if (Runtime::Current()->IsAotCompiler()) {
3709 dst->SetDataPtrSize(reinterpret_cast32<void*>(method.GetCodeItemOffset()), image_pointer_size_);
3710 } else {
zhaoxuyang7156ea22022-01-10 13:58:11 +08003711 dst->SetCodeItem(dst->GetDexFile()->GetCodeItem(method.GetCodeItemOffset()),
3712 dst->GetDexFile()->IsCompactDexFile());
Nicolas Geoffray47171752020-08-31 15:03:20 +01003713 }
3714 } else {
3715 dst->SetDataPtrSize(nullptr, image_pointer_size_);
3716 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3717 }
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003718
3719 // Set optimization flags related to the shorty.
Jared Duke968c8132021-11-02 16:47:54 -07003720 uint32_t shorty_length;
3721 const char* shorty = dst->GetShorty(&shorty_length);
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003722 bool all_parameters_are_reference = true;
3723 bool all_parameters_are_reference_or_int = true;
3724 bool return_type_is_fp = (shorty[0] == 'F' || shorty[0] == 'D');
3725
Jared Duke968c8132021-11-02 16:47:54 -07003726 for (size_t i = 1; i < shorty_length; ++i) {
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003727 if (shorty[i] != 'L') {
3728 all_parameters_are_reference = false;
3729 if (shorty[i] == 'F' || shorty[i] == 'D' || shorty[i] == 'J') {
3730 all_parameters_are_reference_or_int = false;
3731 break;
3732 }
3733 }
3734 }
3735
3736 if (!dst->IsNative() && all_parameters_are_reference) {
3737 dst->SetNterpEntryPointFastPathFlag();
3738 }
3739
3740 if (!return_type_is_fp && all_parameters_are_reference_or_int) {
3741 dst->SetNterpInvokeFastPathFlag();
3742 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003743}
3744
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003745void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
David Srbecky33df0e32021-09-30 14:36:32 +00003746 ObjPtr<mirror::DexCache> dex_cache =
3747 AllocAndInitializeDexCache(self, *dex_file, /* class_loader= */ nullptr);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003748 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003749 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003750}
3751
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003752void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003753 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003754 CHECK(dex_file != nullptr);
3755 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3756 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003757 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003758 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003759}
3760
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003761void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003762 ObjPtr<mirror::DexCache> dex_cache,
3763 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003764 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003765 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003766 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003767 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003768 // For app images, the dex cache location may be a suffix of the dex file location since the
3769 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003770 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3771 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003772 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3773 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003774 // The following paths checks don't work on preopt when using boot dex files, where the dex
3775 // cache location is the one on device, and the dex_file's location is the one on host.
3776 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3777 CHECK_GE(dex_file_location.length(), dex_cache_length)
3778 << dex_cache_location << " " << dex_file.GetLocation();
3779 const std::string dex_file_suffix = dex_file_location.substr(
3780 dex_file_location.length() - dex_cache_length,
3781 dex_cache_length);
3782 // Example dex_cache location is SettingsProvider.apk and
3783 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3784 CHECK_EQ(dex_cache_location, dex_file_suffix);
3785 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003786 const OatFile* oat_file =
3787 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003788 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3789 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3790 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3791 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003792 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003793 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
David Srbecky6fbcc292021-02-23 01:05:32 +00003794 const DexCacheData& data = it->second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003795 if (self->IsJWeakCleared(data.weak_root)) {
3796 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003797 it = dex_caches_.erase(it);
3798 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003799 if (initialize_oat_file_data &&
David Srbecky6fbcc292021-02-23 01:05:32 +00003800 it->first->GetOatDexFile() != nullptr &&
3801 it->first->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003802 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003803 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003804 ++it;
3805 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003806 }
Vladimir Markob066d432018-01-03 13:14:37 +00003807 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003808 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003809 }
David Brazdila5c3a802019-03-08 14:59:41 +00003810 // Let hiddenapi assign a domain to the newly registered dex file.
3811 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3812
Vladimir Markocd556b02017-02-03 11:47:34 +00003813 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003814 DexCacheData data;
3815 data.weak_root = dex_cache_jweak;
Vladimir Markocd556b02017-02-03 11:47:34 +00003816 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky6fbcc292021-02-23 01:05:32 +00003817 AddNativeDebugInfoForDex(self, &dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003818 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003819 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3820 // path dex caches without an image.
3821 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003822 // Make sure that the dex cache holds the classloader live.
3823 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003824 if (class_loader != nullptr) {
3825 // Since we added a strong root to the class table, do the write barrier as required for
3826 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003827 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003828 }
David Srbecky6fbcc292021-02-23 01:05:32 +00003829 bool inserted = dex_caches_.emplace(&dex_file, std::move(data)).second;
3830 CHECK(inserted);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003831}
3832
Alex Light725da8f2020-02-19 14:46:33 -08003833ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3834 return data != nullptr
3835 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003836 : nullptr;
3837}
3838
Alex Light725da8f2020-02-19 14:46:33 -08003839bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003840 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003841 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003842 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003843 CHECK(data != nullptr);
David Srbecky6fbcc292021-02-23 01:05:32 +00003844 DCHECK_EQ(FindDexCacheDataLocked(*dex_cache->GetDexFile()), data);
Alex Light725da8f2020-02-19 14:46:33 -08003845 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003846}
3847
Alex Light07f06212017-06-01 14:01:43 -07003848void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3849 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003850 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003851 Thread* self = Thread::Current();
3852 StackHandleScope<2> hs(self);
3853 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3854 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3855 const DexFile* dex_file = dex_cache->GetDexFile();
3856 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3857 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003858 ReaderMutexLock mu(self, *Locks::dex_lock_);
3859 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3860 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003861 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3862 << "been registered on dex file " << dex_file->GetLocation();
3863 }
3864 ClassTable* table;
3865 {
3866 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3867 table = InsertClassTableForClassLoader(h_class_loader.Get());
3868 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003869 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3870 // a thread holding the dex lock and blocking on a condition variable regarding
3871 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003872 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003873 WriterMutexLock mu(self, *Locks::dex_lock_);
3874 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3875 table->InsertStrongRoot(h_dex_cache.Get());
3876 if (h_class_loader.Get() != nullptr) {
3877 // Since we added a strong root to the class table, do the write barrier as required for
3878 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003879 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003880 }
3881}
3882
Alex Lightde7f8782020-02-24 10:14:22 -08003883static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
3884 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08003885 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08003886 "Attempt to register dex file %s with multiple class loaders",
3887 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08003888}
3889
Vladimir Markocd556b02017-02-03 11:47:34 +00003890ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3891 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003892 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08003893 ObjPtr<mirror::DexCache> old_dex_cache;
3894 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003895 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003896 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003897 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
3898 old_dex_cache = DecodeDexCacheLocked(self, old_data);
3899 if (old_dex_cache != nullptr) {
3900 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
3901 return old_dex_cache;
3902 } else {
3903 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
3904 // be thrown when it's safe to do so to simplify this.
3905 registered_with_another_class_loader = true;
3906 }
3907 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003908 }
Alex Light725da8f2020-02-19 14:46:33 -08003909 // We need to have released the dex_lock_ to allocate safely.
3910 if (registered_with_another_class_loader) {
3911 ThrowDexFileAlreadyRegisteredError(self, dex_file);
3912 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003913 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003914 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003915 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3916 DCHECK(linear_alloc != nullptr);
3917 ClassTable* table;
3918 {
3919 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3920 table = InsertClassTableForClassLoader(class_loader);
3921 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003922 // Don't alloc while holding the lock, since allocation may need to
3923 // suspend all threads and another thread may need the dex_lock_ to
3924 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003925 StackHandleScope<3> hs(self);
3926 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00003927 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003928 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003929 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3930 // a thread holding the dex lock and blocking on a condition variable regarding
3931 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003932 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003933 WriterMutexLock 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);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003936 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
David Srbecky33df0e32021-09-30 14:36:32 +00003937 // Do Initialize while holding dex lock to make sure two threads don't call it
David Srbecky86d6cd52020-12-02 18:13:10 +00003938 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
3939 // DCHECK that the arrays are null.
David Srbecky33df0e32021-09-30 14:36:32 +00003940 h_dex_cache->Initialize(&dex_file, h_class_loader.Get());
Vladimir Markocd556b02017-02-03 11:47:34 +00003941 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003942 }
Alex Light725da8f2020-02-19 14:46:33 -08003943 if (old_dex_cache != nullptr) {
3944 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3945 // If this thread encountered OOME, ignore it.
3946 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
3947 self->ClearException();
3948 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
3949 // dex_lock_.
3950 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
3951 return old_dex_cache;
3952 } else {
3953 registered_with_another_class_loader = true;
3954 }
3955 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003956 }
Alex Light725da8f2020-02-19 14:46:33 -08003957 if (registered_with_another_class_loader) {
3958 ThrowDexFileAlreadyRegisteredError(self, dex_file);
3959 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00003960 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003961 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003962 self->AssertPendingOOMException();
3963 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003964 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003965 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003966 if (h_class_loader.Get() != nullptr) {
3967 // Since we added a strong root to the class table, do the write barrier as required for
3968 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003969 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003970 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01003971 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
Nicolas Geoffray4f6bb442021-06-02 18:05:51 +01003972 PaletteNotifyDexFileLoaded(dex_file.GetLocation().c_str());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003973 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003974}
3975
Vladimir Markocd556b02017-02-03 11:47:34 +00003976bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003977 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003978 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003979}
3980
Vladimir Markocd556b02017-02-03 11:47:34 +00003981ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3982 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003983 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
3984 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003985 if (dex_cache != nullptr) {
3986 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003987 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003988 // Failure, dump diagnostic and abort.
David Srbecky6fbcc292021-02-23 01:05:32 +00003989 for (const auto& entry : dex_caches_) {
3990 const DexCacheData& data = entry.second;
Alex Light725da8f2020-02-19 14:46:33 -08003991 if (DecodeDexCacheLocked(self, &data) != nullptr) {
David Srbecky6fbcc292021-02-23 01:05:32 +00003992 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << entry.first->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003993 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003994 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003995 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
David Srbecky6fbcc292021-02-23 01:05:32 +00003996 << " " << &dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003997 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003998}
3999
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004000ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const OatDexFile& oat_dex_file) {
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004001 ReaderMutexLock mu(self, *Locks::dex_lock_);
4002 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(oat_dex_file);
4003 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
4004 if (dex_cache != nullptr) {
4005 return dex_cache;
4006 }
4007 // Failure, dump diagnostic and abort.
4008 for (const auto& entry : dex_caches_) {
4009 const DexCacheData& data = entry.second;
4010 if (DecodeDexCacheLocked(self, &data) != nullptr) {
4011 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << entry.first->GetLocation();
4012 }
4013 }
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004014 LOG(FATAL) << "Failed to find DexCache for OatDexFile " << oat_dex_file.GetDexFileLocation()
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004015 << " " << &oat_dex_file;
4016 UNREACHABLE();
4017}
4018
Vladimir Markocd556b02017-02-03 11:47:34 +00004019ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4020 const DexFile* dex_file = dex_cache->GetDexFile();
4021 DCHECK(dex_file != nullptr);
4022 ReaderMutexLock mu(self, *Locks::dex_lock_);
David Srbecky6fbcc292021-02-23 01:05:32 +00004023 auto it = dex_caches_.find(dex_file);
4024 if (it != dex_caches_.end()) {
4025 const DexCacheData& data = it->second;
4026 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
4027 if (registered_dex_cache != nullptr) {
4028 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4029 return data.class_table;
Vladimir Markocd556b02017-02-03 11:47:34 +00004030 }
4031 }
4032 return nullptr;
4033}
4034
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004035const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004036 const OatDexFile& oat_dex_file) {
4037 auto it = std::find_if(dex_caches_.begin(), dex_caches_.end(), [&](const auto& entry) {
4038 return entry.first->GetOatDexFile() == &oat_dex_file;
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004039 });
4040 return it != dex_caches_.end() ? &it->second : nullptr;
4041}
4042
Alex Light725da8f2020-02-19 14:46:33 -08004043const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
David Srbecky6fbcc292021-02-23 01:05:32 +00004044 auto it = dex_caches_.find(&dex_file);
4045 return it != dex_caches_.end() ? &it->second : nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004046}
4047
Vladimir Marko70e2a762019-07-12 16:49:00 +01004048void ClassLinker::CreatePrimitiveClass(Thread* self,
4049 Primitive::Type type,
4050 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004051 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004052 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004053 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4054 // Do not hold lock on the primitive class object, the initialization of
4055 // primitive classes is done while the process is still single threaded.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004056 primitive_class->SetAccessFlagsDuringLinking(kAccPublic | kAccFinal | kAccAbstract);
Vladimir Marko70e2a762019-07-12 16:49:00 +01004057 primitive_class->SetPrimitiveType(type);
4058 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko70e2a762019-07-12 16:49:00 +01004059 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004060 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4061 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004062 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004063 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004064 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004065 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004066 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004067 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004068}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004069
Vladimir Marko02610552018-06-04 14:38:00 +01004070inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4071 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4072}
4073
Brian Carlstrombe977852011-07-19 14:54:54 -07004074// Create an array class (i.e. the class object for the array, not the
4075// array itself). "descriptor" looks like "[C" or "[[[[B" or
4076// "[Ljava/lang/String;".
4077//
4078// If "descriptor" refers to an array of primitives, look up the
4079// primitive type's internally-generated class object.
4080//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004081// "class_loader" is the class loader of the class that's referring to
4082// us. It's used to ensure that we're looking for the element type in
4083// the right context. It does NOT become the class loader for the
4084// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004085//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004086// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004087ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4088 const char* descriptor,
4089 size_t hash,
4090 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004091 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004092 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004093 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004094
4095 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4096 // code to be executed. We put it up here so we can avoid all the allocations associated with
4097 // creating the class. This can happen with (eg) jit threads.
4098 if (!self->CanLoadClasses()) {
4099 // Make sure we don't try to load anything, potentially causing an infinite loop.
4100 ObjPtr<mirror::Throwable> pre_allocated =
4101 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4102 self->SetException(pre_allocated);
4103 return nullptr;
4104 }
4105
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004106 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4107 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004108 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004109 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004110 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004111 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4112 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004113 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004114 DCHECK(self->IsExceptionPending());
4115 return nullptr;
4116 } else {
4117 self->ClearException();
4118 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004119 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004120 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4121 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4122 return nullptr;
4123 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004124 // See if the component type is already loaded. Array classes are
4125 // always associated with the class loader of their underlying
4126 // element type -- an array of Strings goes with the loader for
4127 // java/lang/String -- so we need to look for it there. (The
4128 // caller should have checked for the existence of the class
4129 // before calling here, but they did so with *their* class loader,
4130 // not the component type's loader.)
4131 //
4132 // If we find it, the caller adds "loader" to the class' initiating
4133 // loader list, which should prevent us from going through this again.
4134 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004135 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004136 // are the same, because our caller (FindClass) just did the
4137 // lookup. (Even if we get this wrong we still have correct behavior,
4138 // because we effectively do this lookup again when we add the new
4139 // class to the hash table --- necessary because of possible races with
4140 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004141 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004142 ObjPtr<mirror::Class> new_class =
4143 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004144 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004145 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004146 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004147 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004148 // Core array classes, i.e. Object[], Class[], String[] and primitive
4149 // arrays, have special initialization and they should be found above.
4150 DCHECK(!component_type->IsObjectClass() ||
4151 // Guard from false positives for errors before setting superclass.
4152 component_type->IsErroneousUnresolved());
4153 DCHECK(!component_type->IsStringClass());
4154 DCHECK(!component_type->IsClassClass());
4155 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004156
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004157 // Fill out the fields in the Class.
4158 //
4159 // It is possible to execute some methods against arrays, because
4160 // all arrays are subclasses of java_lang_Object_, so we need to set
4161 // up a vtable. We can just point at the one in java_lang_Object_.
4162 //
4163 // Array classes are simple enough that we don't need to do a full
4164 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004165 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4166 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4167 size_t usable_size)
4168 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004169 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004170 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4171 init_class(obj, usable_size);
4172 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4173 klass->SetComponentType(component_type.Get());
4174 // Do not hold lock for initialization, the fence issued after the visitor
4175 // returns ensures memory visibility together with the implicit consume
4176 // semantics (for all supported architectures) for any thread that loads
4177 // the array class reference from any memory locations afterwards.
4178 FinishArrayClassSetup(klass);
4179 };
4180 auto new_class = hs.NewHandle<mirror::Class>(
4181 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004182 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004183 self->AssertPendingOOMException();
4184 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004185 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004186
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004187 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004188 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004189 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4190 // duplicate events in case of races. Array classes don't really follow dedicated
4191 // load and prepare, anyways.
4192 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4193 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4194
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004195 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004196 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004197 }
4198 // Another thread must have loaded the class after we
4199 // started but before we finished. Abandon what we've
4200 // done.
4201 //
4202 // (Yes, this happens.)
4203
Vladimir Markobcf17522018-06-01 13:14:32 +01004204 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004205}
4206
Vladimir Marko9186b182018-11-06 14:55:54 +00004207ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4208 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004209 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004210 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4211 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4212 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4213 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4214 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4215 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4216 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4217 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4218 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004219 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004220 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004221 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004222 return GetClassRoot(class_root, this);
4223}
4224
4225ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4226 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4227 if (UNLIKELY(result == nullptr)) {
4228 std::string printable_type(PrintableChar(type));
4229 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4230 }
4231 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004232}
4233
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004234ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4235 ObjPtr<mirror::Class> klass,
4236 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004237 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004238 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004239 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004240 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004241 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004242 source += " from ";
4243 source += dex_cache->GetLocation()->ToModifiedUtf8();
4244 }
4245 LOG(INFO) << "Loaded class " << descriptor << source;
4246 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004247 {
4248 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004249 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004250 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004251 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004252 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004253 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004254 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004255 VerifyObject(klass);
4256 class_table->InsertWithHash(klass, hash);
4257 if (class_loader != nullptr) {
4258 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004259 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004260 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004261 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004262 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004263 }
4264 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004265 if (kIsDebugBuild) {
4266 // Test that copied methods correctly can find their holder.
4267 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4268 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4269 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004270 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004271 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004272}
4273
Vladimir Marko1998cd02017-01-13 13:02:58 +00004274void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004275 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4276 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4277 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4278 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004279 }
4280}
4281
Alex Lighte64300b2015-12-15 15:02:47 -08004282// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004283void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004284 LengthPrefixedArray<ArtMethod>* new_methods) {
4285 klass->SetMethodsPtrUnchecked(new_methods,
4286 klass->NumDirectMethods(),
4287 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004288 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004289 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004290}
4291
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004292ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4293 const char* descriptor,
4294 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004295 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4296}
4297
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004298ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4299 const char* descriptor,
4300 size_t hash,
4301 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004302 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4303 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4304 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004305 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004306 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004307 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004308 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004309 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004310 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004311}
4312
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004313class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4314 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004315 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004316
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004317 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004318 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004319 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004320 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004321 if (class_table != nullptr) {
4322 class_table->FreezeSnapshot();
4323 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004324 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004325};
4326
4327void ClassLinker::MoveClassTableToPreZygote() {
4328 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004329 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004330 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004331 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004332}
4333
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004334// Look up classes by hash and descriptor and put all matching ones in the result array.
4335class LookupClassesVisitor : public ClassLoaderVisitor {
4336 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004337 LookupClassesVisitor(const char* descriptor,
4338 size_t hash,
4339 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004340 : descriptor_(descriptor),
4341 hash_(hash),
4342 result_(result) {}
4343
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004344 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004345 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004346 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004347 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004348 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4349 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004350 result_->push_back(klass);
4351 }
4352 }
4353
4354 private:
4355 const char* const descriptor_;
4356 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004357 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004358};
4359
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004360void ClassLinker::LookupClasses(const char* descriptor,
4361 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004362 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004363 Thread* const self = Thread::Current();
4364 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004365 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004366 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004367 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004368 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004369 result.push_back(klass);
4370 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004371 LookupClassesVisitor visitor(descriptor, hash, &result);
4372 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004373}
4374
Alex Lightf1f10492015-10-07 16:08:36 -07004375bool ClassLinker::AttemptSupertypeVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004376 verifier::VerifierDeps* verifier_deps,
Alex Lightf1f10492015-10-07 16:08:36 -07004377 Handle<mirror::Class> klass,
4378 Handle<mirror::Class> supertype) {
4379 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004380 DCHECK(klass != nullptr);
4381 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004382
Alex Lightf1f10492015-10-07 16:08:36 -07004383 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004384 VerifyClass(self, verifier_deps, supertype);
Alex Lightf1f10492015-10-07 16:08:36 -07004385 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004386
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004387 if (supertype->IsVerified()
4388 || supertype->ShouldVerifyAtRuntime()
4389 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004390 // The supertype is either verified, or we soft failed at AOT time.
4391 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004392 return true;
4393 }
4394 // If we got this far then we have a hard failure.
4395 std::string error_msg =
4396 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004397 klass->PrettyDescriptor().c_str(),
4398 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004399 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004400 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004401 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004402 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004403 // Set during VerifyClass call (if at all).
4404 self->ClearException();
4405 }
4406 // Change into a verify error.
4407 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004408 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004409 self->GetException()->SetCause(cause.Get());
4410 }
4411 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4412 if (Runtime::Current()->IsAotCompiler()) {
4413 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4414 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004415 // Need to grab the lock to change status.
4416 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004417 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004418 return false;
4419}
4420
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004421verifier::FailureKind ClassLinker::VerifyClass(Thread* self,
4422 verifier::VerifierDeps* verifier_deps,
4423 Handle<mirror::Class> klass,
4424 verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004425 {
4426 // TODO: assert that the monitor on the Class is held
4427 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004428
Andreas Gampe884f3b82016-03-30 19:52:58 -07004429 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004430 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004431 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004432 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004433 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4434 // case we may see the same status again. b/62912904. This is why the check is
4435 // greater or equal.
4436 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004437 << "Class '" << klass->PrettyClass()
4438 << "' performed an illegal verification state transition from " << old_status
4439 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004440 old_status = klass->GetStatus();
4441 }
jeffhao98eacac2011-09-14 16:11:53 -07004442
Andreas Gampe884f3b82016-03-30 19:52:58 -07004443 // The class might already be erroneous, for example at compile time if we attempted to verify
4444 // this class as a parent to another.
4445 if (klass->IsErroneous()) {
4446 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004447 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004448 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004449
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004450 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004451 if (klass->IsVerified()) {
Nicolas Geoffray80789962021-04-30 16:50:39 +01004452 if (verifier_deps != nullptr &&
4453 verifier_deps->ContainsDexFile(klass->GetDexFile()) &&
4454 !verifier_deps->HasRecordedVerifiedStatus(klass->GetDexFile(), *klass->GetClassDef()) &&
4455 !Runtime::Current()->IsAotCompiler()) {
4456 // If the klass is verified, but `verifier_deps` did not record it, this
4457 // means we are running background verification of a secondary dex file.
4458 // Re-run the verifier to populate `verifier_deps`.
4459 // No need to run the verification when running on the AOT Compiler, as
4460 // the driver handles those multithreaded cases already.
4461 std::string error_msg;
4462 verifier::FailureKind failure =
4463 PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
4464 // We could have soft failures, so just check that we don't have a hard
4465 // failure.
4466 DCHECK_NE(failure, verifier::FailureKind::kHardFailure) << error_msg;
4467 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004468 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004469 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004470
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004471 if (klass->IsVerifiedNeedsAccessChecks()) {
4472 if (!Runtime::Current()->IsAotCompiler()) {
4473 // Mark the class as having a verification attempt to avoid re-running
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004474 // the verifier.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004475 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4476 }
4477 return verifier::FailureKind::kAccessChecksFailure;
4478 }
4479
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004480 // For AOT, don't attempt to re-verify if we have already found we should
4481 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004482 if (klass->ShouldVerifyAtRuntime()) {
4483 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004484 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004485 }
jeffhao98eacac2011-09-14 16:11:53 -07004486
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004487 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4488 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004489
4490 // Skip verification if disabled.
4491 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004492 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004493 UpdateClassAfterVerification(klass, image_pointer_size_, verifier::FailureKind::kNoFailure);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004494 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004495 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004496 }
4497
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004498 VLOG(class_linker) << "Beginning verification for class: "
4499 << klass->PrettyDescriptor()
4500 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4501
Ian Rogers9ffb0392012-09-10 11:56:50 -07004502 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004503 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004504 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4505 // If we have a superclass and we get a hard verification failure we can return immediately.
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004506 if (supertype != nullptr &&
4507 !AttemptSupertypeVerification(self, verifier_deps, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004508 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004509 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004510 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004511
Alex Lightf1f10492015-10-07 16:08:36 -07004512 // Verify all default super-interfaces.
4513 //
4514 // (1) Don't bother if the superclass has already had a soft verification failure.
4515 //
4516 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4517 // recursive initialization by themselves. This is because when an interface is initialized
4518 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4519 // but choose not to for an optimization. If the interfaces is being verified due to a class
4520 // initialization (which would need all the default interfaces to be verified) the class code
4521 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004522 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004523 && !klass->IsInterface()) { // See (2)
4524 int32_t iftable_count = klass->GetIfTableCount();
4525 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4526 // Loop through all interfaces this class has defined. It doesn't matter the order.
4527 for (int32_t i = 0; i < iftable_count; i++) {
4528 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004529 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004530 // We only care if we have default interfaces and can skip if we are already verified...
4531 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4532 continue;
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004533 } else if (UNLIKELY(!AttemptSupertypeVerification(self, verifier_deps, klass, iface))) {
Alex Lightf1f10492015-10-07 16:08:36 -07004534 // We had a hard failure while verifying this interface. Just return immediately.
4535 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004536 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004537 } else if (UNLIKELY(!iface->IsVerified())) {
4538 // We softly failed to verify the iface. Stop checking and clean up.
4539 // Put the iface into the supertype handle so we know what caused us to fail.
4540 supertype.Assign(iface.Get());
4541 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004542 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004543 }
4544 }
4545
Alex Lightf1f10492015-10-07 16:08:36 -07004546 // At this point if verification failed, then supertype is the "first" supertype that failed
4547 // verification (without a specific order). If verification succeeded, then supertype is either
4548 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004549 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004550 supertype.Get() == klass->GetSuperClass() ||
4551 !supertype->IsVerified());
4552
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004553 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004554 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004555 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004556 bool preverified = VerifyClassUsingOatFile(self, dex_file, klass, oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004557
4558 VLOG(class_linker) << "Class preverified status for class "
4559 << klass->PrettyDescriptor()
4560 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4561 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004562 << preverified
4563 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004564
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004565 // If the oat file says the class had an error, re-run the verifier. That way we will either:
4566 // 1) Be successful at runtime, or
4567 // 2) Get a precise error message.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004568 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004569
Ian Rogers62d6c772013-02-27 08:32:07 -08004570 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004571 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004572 if (!preverified) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004573 verifier_failure = PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004574 } else if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks) {
4575 verifier_failure = verifier::FailureKind::kAccessChecksFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004576 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004577
4578 // Verification is done, grab the lock again.
4579 ObjectLock<mirror::Class> lock(self, klass);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004580 self->AssertNoPendingException();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004581
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004582 if (verifier_failure == verifier::FailureKind::kHardFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004583 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004584 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4585 << " because: " << error_msg;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004586 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004587 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004588 return verifier_failure;
jeffhao5cfd6fb2011-09-27 13:54:29 -07004589 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004590
4591 // Make sure all classes referenced by catch blocks are resolved.
4592 ResolveClassExceptionHandlerTypes(klass);
4593
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004594 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004595 if (supertype != nullptr && supertype->ShouldVerifyAtRuntime()) {
4596 // Regardless of our own verification result, we need to verify the class
4597 // at runtime if the super class is not verified. This is required in case
4598 // we generate an app/boot image.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004599 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4600 } else if (verifier_failure == verifier::FailureKind::kNoFailure) {
4601 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4602 } else if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4603 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
4604 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4605 } else {
4606 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4607 }
4608 // Notify the compiler about the verification status, in case the class
4609 // was verified implicitly (eg super class of a compiled class). When the
4610 // compiler unloads dex file after compilation, we still want to keep
4611 // verification states.
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004612 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4613 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004614 } else {
4615 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004616 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004617
4618 UpdateClassAfterVerification(klass, image_pointer_size_, verifier_failure);
Nicolas Geoffray08025182016-10-25 17:20:18 +01004619 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004620}
4621
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004622verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004623 verifier::VerifierDeps* verifier_deps,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004624 Handle<mirror::Class> klass,
4625 verifier::HardFailLogMode log_level,
4626 std::string* error_msg) {
4627 Runtime* const runtime = Runtime::Current();
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004628 StackHandleScope<2> hs(self);
4629 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4630 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004631 return verifier::ClassVerifier::VerifyClass(self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004632 verifier_deps,
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004633 dex_cache->GetDexFile(),
4634 klass,
4635 dex_cache,
4636 class_loader,
4637 *klass->GetClassDef(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004638 runtime->GetCompilerCallbacks(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004639 log_level,
4640 Runtime::Current()->GetTargetSdkVersion(),
4641 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004642}
4643
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004644bool ClassLinker::VerifyClassUsingOatFile(Thread* self,
4645 const DexFile& dex_file,
4646 Handle<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004647 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004648 // If we're compiling, we can only verify the class using the oat file if
4649 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004650 // the compilation unit (app - dependencies). We will let the compiler callback
4651 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004652 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004653 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004654 // We are compiling an app (not the image).
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004655 if (!callbacks->CanUseOatStatusForVerification(klass.Get())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004656 return false;
4657 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004658 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004659
Andreas Gampeb40d3612018-06-26 15:49:42 -07004660 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004661 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004662 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004663 return false;
4664 }
4665
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004666 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004667 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004668 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004669 return true;
4670 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004671 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4672 // We return that the clas has already been verified, and the caller should
4673 // check the class status to ensure we run with access checks.
4674 return true;
4675 }
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004676
4677 // Check the class status with the vdex file.
4678 const OatFile* oat_file = oat_dex_file->GetOatFile();
4679 if (oat_file != nullptr) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004680 ClassStatus vdex_status = oat_file->GetVdexFile()->ComputeClassStatus(self, klass);
4681 if (vdex_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
Nicolas Geoffray327cfcf2021-10-12 14:13:25 +01004682 VLOG(verifier) << "Vdex verification success for " << klass->PrettyClass();
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004683 oat_file_class_status = vdex_status;
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004684 return true;
4685 }
4686 }
4687
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004688 // If we only verified a subset of the classes at compile time, we can end up with classes that
4689 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004690 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004691 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004692 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004693 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4694 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4695 << klass->PrettyClass() << " " << dex_file.GetLocation();
4696
Vladimir Marko72ab6842017-01-20 19:32:50 +00004697 if (mirror::Class::IsErroneous(oat_file_class_status)) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004698 // Compile time verification failed with a hard error. We'll re-run
4699 // verification, which might be successful at runtime.
jeffhao1ac29442012-03-26 11:37:32 -07004700 return false;
4701 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004702 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004703 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4704 // not loading the class.
4705 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4706 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004707 return false;
4708 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004709 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004710 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004711 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004712 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004713 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004714}
4715
Alex Light5a559862016-01-29 12:24:48 -08004716void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004717 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004718 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004719 }
4720}
4721
Alex Light5a559862016-01-29 12:24:48 -08004722void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004723 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004724 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004725 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004726 return; // native or abstract method
4727 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004728 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004729 return; // nothing to process
4730 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004731 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004732 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004733 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4734 CatchHandlerIterator iterator(handlers_ptr);
4735 for (; iterator.HasNext(); iterator.Next()) {
4736 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4737 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004738 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004739 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004740 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004741 DCHECK(Thread::Current()->IsExceptionPending());
4742 Thread::Current()->ClearException();
4743 }
4744 }
4745 }
4746 handlers_ptr = iterator.EndDataPointer();
4747 }
4748}
4749
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004750ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4751 jstring name,
4752 jobjectArray interfaces,
4753 jobject loader,
4754 jobjectArray methods,
4755 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004756 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004757
4758 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4759 // code to be executed. We put it up here so we can avoid all the allocations associated with
4760 // creating the class. This can happen with (eg) jit-threads.
4761 if (!self->CanLoadClasses()) {
4762 // Make sure we don't try to load anything, potentially causing an infinite loop.
4763 ObjPtr<mirror::Throwable> pre_allocated =
4764 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4765 self->SetException(pre_allocated);
4766 return nullptr;
4767 }
4768
Alex Light133987d2020-03-26 19:22:12 +00004769 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004770 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004771 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004772 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004773 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004774 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004775 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004776 DCHECK(temp_klass->GetClass() != nullptr);
4777 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004778 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4779 // the methods.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004780 temp_klass->SetAccessFlagsDuringLinking(kAccClassIsProxy | kAccPublic | kAccFinal);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004781 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4782 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4783 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004784 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004785 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004786 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004787 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004788 std::string storage;
4789 const char* descriptor = temp_klass->GetDescriptor(&storage);
4790 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004791
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004792 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004793 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004794
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004795 // Insert the class before loading the fields as the field roots
4796 // (ArtField::declaring_class_) are only visited from the class
4797 // table. There can't be any suspend points between inserting the
4798 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004799 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004800 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004801
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004802 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004803 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004804 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004805 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004806
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004807 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4808 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004809 ArtField& interfaces_sfield = sfields->At(0);
4810 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004811 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004812 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004813
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004814 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004815 ArtField& throws_sfield = sfields->At(1);
4816 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004817 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004818 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004819
Ian Rogers466bb252011-10-14 03:29:56 -07004820 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004821 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004822
Alex Light133987d2020-03-26 19:22:12 +00004823 // The array we get passed contains all methods, including private and static
4824 // ones that aren't proxied. We need to filter those out since only interface
4825 // methods (non-private & virtual) are actually proxied.
4826 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4827 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004828 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004829 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004830 // List of the actual virtual methods this class will have.
4831 std::vector<ArtMethod*> proxied_methods;
4832 std::vector<size_t> proxied_throws_idx;
4833 proxied_methods.reserve(h_methods->GetLength());
4834 proxied_throws_idx.reserve(h_methods->GetLength());
4835 // Filter out to only the non-private virtual methods.
4836 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4837 ArtMethod* m = mirror->GetArtMethod();
4838 if (!m->IsPrivate() && !m->IsStatic()) {
4839 proxied_methods.push_back(m);
4840 proxied_throws_idx.push_back(idx);
4841 }
4842 }
4843 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004844 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4845 // contains an array of all the classes each function is declared to throw.
4846 // This is used to wrap unexpected exceptions in a
4847 // UndeclaredThrowableException exception. This array is in the same order as
4848 // the methods array and like the methods array must be filtered to remove any
4849 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004850 const bool has_filtered_methods =
4851 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4852 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4853 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4854 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4855 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4856 (has_filtered_methods)
4857 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4858 self, original_proxied_throws->GetClass(), num_virtual_methods)
4859 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004860 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4861 self->AssertPendingOOMException();
4862 return nullptr;
4863 }
Alex Light133987d2020-03-26 19:22:12 +00004864 if (has_filtered_methods) {
4865 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
4866 DCHECK_LE(new_idx, orig_idx);
4867 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
4868 }
4869 }
Alex Lighte64300b2015-12-15 15:02:47 -08004870
4871 // Create the methods array.
4872 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4873 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004874 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4875 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004876 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004877 self->AssertPendingOOMException();
4878 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004879 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004880 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004881
4882 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004883 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004884
4885 // Create virtual method using specified prototypes.
4886 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004887 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004888 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004889 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004890 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004891 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4892 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004893 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004894
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004895 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004896 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004897 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004898 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004899 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004900
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004901 // At this point the class is loaded. Publish a ClassLoad event.
4902 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4903 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4904
4905 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004906 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004907 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004908 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004909 // Link the fields and virtual methods, creating vtable and iftables.
4910 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004911 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004912 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004913 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Markoa4d28dd2021-06-30 11:28:06 +01004914 if (!temp_klass->IsErroneous()) {
4915 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
4916 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004917 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004918 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004919 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004920 CHECK(temp_klass->IsRetired());
4921 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004922
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004923 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004924 interfaces_sfield.SetObject<false>(
4925 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004926 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004927 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4928 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004929 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00004930 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004931
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004932 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4933
Vladimir Marko305c38b2018-02-14 11:50:07 +00004934 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4935 // See also ClassLinker::EnsureInitialized().
4936 if (kBitstringSubtypeCheckEnabled) {
4937 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4938 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4939 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4940 }
4941
Vladimir Markobf121912019-06-04 13:49:05 +01004942 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004943 {
4944 // Lock on klass is released. Lock new class object.
4945 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Markobf121912019-06-04 13:49:05 +01004946 // Conservatively go through the ClassStatus::kInitialized state.
4947 callback = MarkClassInitialized(self, klass);
4948 }
4949 if (callback != nullptr) {
4950 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07004951 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004952
David Srbecky346fd962020-07-27 16:51:00 +01004953 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07004954 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004955 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004956 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4957
Ian Rogersc2b44472011-12-14 21:17:17 -08004958 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004959 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004960 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08004961 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004962
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004963 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004964 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004965 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004966 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004967 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004968
4969 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004970 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004971 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004972
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004973 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004974 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004975 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00004976 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004977 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004978 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004979}
4980
Mathieu Chartiere401d142015-04-22 13:56:20 -07004981void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4982 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004983 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4984 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004985
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004986 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4987 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004988 ArtMethod* proxy_constructor =
4989 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004990 DCHECK(proxy_constructor != nullptr)
4991 << "Could not find <init> method in java.lang.reflect.Proxy";
4992
Jeff Haodb8a6642014-08-14 17:18:52 -07004993 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4994 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004995 DCHECK(out != nullptr);
4996 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004997 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004998 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004999 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005000 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5001 kAccPublic |
5002 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005003 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005004
5005 // Set the original constructor method.
5006 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005007}
5008
Mathieu Chartiere401d142015-04-22 13:56:20 -07005009void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005010 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005011 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5012 CHECK_STREQ(np->GetName(), "<init>");
5013 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005014 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005015}
5016
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005017void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005018 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005019 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005020 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005021 DCHECK(out != nullptr);
5022 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005023
Alex Lighte9dd04f2016-03-16 16:09:45 -07005024 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005025 out->SetDeclaringClass(klass.Get());
Vladimir Markode0d0de2021-03-18 14:12:35 +00005026 // Clear the abstract and default flags to ensure that defaults aren't picked in
Alex Lighte9dd04f2016-03-16 16:09:45 -07005027 // preference to the invocation handler.
Vladimir Markode0d0de2021-03-18 14:12:35 +00005028 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005029 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005030 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5031 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005032 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5033
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005034 // Set the original interface method.
5035 out->SetDataPtrSize(prototype, image_pointer_size_);
5036
Ian Rogers466bb252011-10-14 03:29:56 -07005037 // At runtime the method looks like a reference and argument saving method, clone the code
5038 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005039 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005040}
Jesse Wilson95caa792011-10-12 18:14:17 -04005041
Mathieu Chartiere401d142015-04-22 13:56:20 -07005042void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005043 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005044 CHECK(!prototype->IsFinal());
5045 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005046 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005047
5048 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5049 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005050 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005051 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005052}
5053
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005054bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005055 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005056 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005057 return true;
5058 }
5059 if (!can_init_statics) {
5060 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005061 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005062 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005063 return false;
5064 }
5065 // Check if there are encoded static values needing initialization.
5066 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005067 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005068 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005069 if (dex_class_def->static_values_off_ != 0) {
5070 return false;
5071 }
5072 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005073 }
5074 // If we are a class we need to initialize all interfaces with default methods when we are
5075 // initialized. Check all of them.
5076 if (!klass->IsInterface()) {
5077 size_t num_interfaces = klass->GetIfTableCount();
5078 for (size_t i = 0; i < num_interfaces; i++) {
5079 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5080 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5081 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005082 return false;
5083 }
5084 }
5085 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005086 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005087 if (klass->IsInterface() || !klass->HasSuperClass()) {
5088 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005089 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005090 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005091 if (super_class->IsInitialized()) {
5092 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005093 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005094 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005095}
5096
Mathieu Chartier23369542020-03-04 08:24:11 -08005097bool ClassLinker::InitializeClass(Thread* self,
5098 Handle<mirror::Class> klass,
5099 bool can_init_statics,
5100 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005101 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5102
5103 // Are we already initialized and therefore done?
5104 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5105 // an initialized class will never change its state.
5106 if (klass->IsInitialized()) {
5107 return true;
5108 }
5109
5110 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005111 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005112 return false;
5113 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005114
Ian Rogers7b078e82014-09-10 14:44:24 -07005115 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005116 Runtime* const runtime = Runtime::Current();
5117 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005118 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005119 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005120 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005121
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005122 // Re-check under the lock in case another thread initialized ahead of us.
5123 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005124 return true;
5125 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005126
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005127 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005128 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005129 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005130 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005131 return false;
5132 }
5133
Vladimir Marko72ab6842017-01-20 19:32:50 +00005134 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5135 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005136
5137 if (!klass->IsVerified()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00005138 VerifyClass(self, /*verifier_deps= */ nullptr, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005139 if (!klass->IsVerified()) {
5140 // We failed to verify, expect either the klass to be erroneous or verification failed at
5141 // compile time.
5142 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005143 // The class is erroneous. This may be a verifier error, or another thread attempted
5144 // verification and/or initialization and failed. We can distinguish those cases by
5145 // whether an exception is already pending.
5146 if (self->IsExceptionPending()) {
5147 // Check that it's a VerifyError.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +01005148 DCHECK(IsVerifyError(self->GetException()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005149 } else {
5150 // Check that another thread attempted initialization.
5151 DCHECK_NE(0, klass->GetClinitThreadId());
5152 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5153 // Need to rethrow the previous failure now.
5154 ThrowEarlierClassFailure(klass.Get(), true);
5155 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005156 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005157 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005158 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005159 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005160 self->AssertNoPendingException();
5161 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005162 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005163 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005164 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005165 } else {
5166 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005167 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005168
5169 // A separate thread could have moved us all the way to initialized. A "simple" example
5170 // involves a subclass of the current class being initialized at the same time (which
5171 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005172 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005173 if (klass->IsInitialized()) {
5174 return true;
5175 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005176 }
5177
Vladimir Marko2c64a832018-01-04 11:31:56 +00005178 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005179 // initializing higher up the stack or another thread has beat us
5180 // to initializing and we need to wait. Either way, this
5181 // invocation of InitializeClass will not be responsible for
5182 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005183 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005184 // Could have got an exception during verification.
5185 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005186 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005187 return false;
5188 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005189 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005190 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005191 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005192 return true;
5193 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005194 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005195 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005196 }
5197
Jeff Haoe2e40342017-07-19 10:45:18 -07005198 // Try to get the oat class's status for this class if the oat file is present. The compiler
5199 // tries to validate superclass descriptors, and writes the result into the oat file.
5200 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5201 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5202 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005203 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005204 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5205 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5206 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005207 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005208 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005209 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005210 return false;
5211 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005212 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005213
Vladimir Marko2c64a832018-01-04 11:31:56 +00005214 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005215 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005216
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005217 // From here out other threads may observe that we're initializing and so changes of state
5218 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005219 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005220 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005221
Mathieu Chartier23369542020-03-04 08:24:11 -08005222 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005223 }
5224
Andreas Gampeaf864702019-07-23 14:05:35 -07005225 uint64_t t_sub = 0;
5226
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005227 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005228 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005229 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005230 if (!super_class->IsInitialized()) {
5231 CHECK(!super_class->IsInterface());
5232 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005233 StackHandleScope<1> hs(self);
5234 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005235 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005236 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005237 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005238 if (!super_initialized) {
5239 // The super class was verified ahead of entering initializing, we should only be here if
5240 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005241 // For the case of aot compiler, the super class might also be initializing but we don't
5242 // want to process circular dependencies in pre-compile.
5243 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005244 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005245 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005246 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005247 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005248 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005249 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005250 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005251 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005252 return false;
5253 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005254 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005255 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005256 }
5257
Alex Lighteb7c1442015-08-31 13:17:42 -07005258 if (!klass->IsInterface()) {
5259 // Initialize interfaces with default methods for the JLS.
5260 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005261 // Only setup the (expensive) handle scope if we actually need to.
5262 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005263 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005264 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5265 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005266 handle_scope_iface.Assign(klass->GetDirectInterface(i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005267 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005268 CHECK(handle_scope_iface->IsInterface());
5269 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5270 // We have already done this for this interface. Skip it.
5271 continue;
5272 }
5273 // We cannot just call initialize class directly because we need to ensure that ALL
5274 // interfaces with default methods are initialized. Non-default interface initialization
5275 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005276 // This is not very precise, misses all walking.
5277 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005278 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5279 handle_scope_iface,
5280 can_init_statics,
5281 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005282 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005283 if (!iface_initialized) {
5284 ObjectLock<mirror::Class> lock(self, klass);
5285 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005286 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005287 return false;
5288 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005289 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005290 }
5291 }
5292 }
5293
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005294 const size_t num_static_fields = klass->NumStaticFields();
5295 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005296 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005297 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005298 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005299 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005300 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005301
5302 // Eagerly fill in static fields so that the we don't have to do as many expensive
5303 // Class::FindStaticField in ResolveField.
5304 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005305 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005306 const uint32_t field_idx = field->GetDexFieldIndex();
David Srbecky5de5efe2021-02-15 21:23:00 +00005307 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005308 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005309 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005310 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5311 field,
5312 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5313 hiddenapi::AccessMethod::kNone));
David Srbecky5de5efe2021-02-15 21:23:00 +00005314 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005315 } else {
5316 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005317 }
5318 }
5319
Vladimir Markoe11dd502017-12-08 14:09:45 +00005320 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5321 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005322 this,
5323 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005324 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005325
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005326 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005327 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005328 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005329 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5330 if (!value_it.HasNext()) {
5331 break;
5332 }
5333 ArtField* art_field = ResolveField(field.GetIndex(),
5334 dex_cache,
5335 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005336 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005337 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005338 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005339 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005340 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005341 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005342 if (self->IsExceptionPending()) {
5343 break;
5344 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005345 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005346 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005347 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005348 }
5349 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005350
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005351
Mathieu Chartierda595be2016-08-10 13:57:39 -07005352 if (!self->IsExceptionPending()) {
5353 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5354 if (clinit != nullptr) {
5355 CHECK(can_init_statics);
5356 JValue result;
5357 clinit->Invoke(self, nullptr, 0, &result, "V");
5358 }
5359 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005360 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005361 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005362
Vladimir Markobf121912019-06-04 13:49:05 +01005363 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005364 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005365 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005366 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005367
5368 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005369 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005370 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005371 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005372 } else if (Runtime::Current()->IsTransactionAborted()) {
5373 // The exception thrown when the transaction aborted has been caught and cleared
5374 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005375 VLOG(compiler) << "Return from class initializer of "
5376 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005377 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005378 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005379 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005380 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005381 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005382 if (stats_enabled) {
5383 RuntimeStats* global_stats = runtime->GetStats();
5384 RuntimeStats* thread_stats = self->GetStats();
5385 ++global_stats->class_init_count;
5386 ++thread_stats->class_init_count;
5387 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5388 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5389 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005390 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005391 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005392 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005393 std::string temp;
5394 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005395 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005396 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005397 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005398 }
Vladimir Markobf121912019-06-04 13:49:05 +01005399 if (callback != nullptr) {
5400 callback->MakeVisible(self);
5401 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005402 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005403}
5404
Alex Lighteb7c1442015-08-31 13:17:42 -07005405// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5406// and perform the initialization only on those interfaces that contain default methods.
5407bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5408 Handle<mirror::Class> iface,
5409 bool can_init_statics,
5410 bool can_init_parents) {
5411 CHECK(iface->IsInterface());
5412 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005413 // Only create the (expensive) handle scope if we need it.
5414 if (UNLIKELY(num_direct_ifaces > 0)) {
5415 StackHandleScope<1> hs(self);
5416 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5417 // First we initialize all of iface's super-interfaces recursively.
5418 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005419 ObjPtr<mirror::Class> super_iface = iface->GetDirectInterface(i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005420 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005421 if (!super_iface->HasBeenRecursivelyInitialized()) {
5422 // Recursive step
5423 handle_super_iface.Assign(super_iface);
5424 if (!InitializeDefaultInterfaceRecursive(self,
5425 handle_super_iface,
5426 can_init_statics,
5427 can_init_parents)) {
5428 return false;
5429 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005430 }
5431 }
5432 }
5433
5434 bool result = true;
5435 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5436 // initialize if we don't have default methods.
5437 if (iface->HasDefaultMethods()) {
5438 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5439 }
5440
5441 // Mark that this interface has undergone recursive default interface initialization so we know we
5442 // can skip it on any later class initializations. We do this even if we are not a default
5443 // interface since we can still avoid the traversal. This is purely a performance optimization.
5444 if (result) {
5445 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005446 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5447 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5448 // initialization is a performance optimization (to avoid another idempotent visit
5449 // for other implementing classes/interfaces), and can be revisited later.
5450 ObjectTryLock<mirror::Class> lock(self, iface);
5451 if (lock.Acquired()) {
5452 iface->SetRecursivelyInitialized();
5453 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005454 }
5455 return result;
5456}
5457
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005458bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5459 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005460 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005461 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005462 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005463 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005464 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005465 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005466
5467 // When we wake up, repeat the test for init-in-progress. If
5468 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005469 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005470 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005471 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005472 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005473 return false;
5474 }
5475 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005476 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005477 continue;
5478 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005479 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005480 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005481 // Compile time initialization failed.
5482 return false;
5483 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005484 if (klass->IsErroneous()) {
5485 // The caller wants an exception, but it was thrown in a
5486 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005487 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005488 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005489 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005490 return false;
5491 }
5492 if (klass->IsInitialized()) {
5493 return true;
5494 }
David Sehr709b0702016-10-13 09:12:37 -07005495 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005496 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005497 }
Ian Rogers07140832014-09-30 15:43:59 -07005498 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005499}
5500
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005501static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5502 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005503 ArtMethod* method,
5504 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005505 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005506 DCHECK(Thread::Current()->IsExceptionPending());
5507 DCHECK(!m->IsProxyMethod());
5508 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005509 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5510 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005511 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005512 std::string return_type = dex_file->PrettyType(return_type_idx);
5513 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005514 ThrowWrappedLinkageError(klass.Get(),
5515 "While checking class %s method %s signature against %s %s: "
5516 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005517 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5518 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005519 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005520 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005521 return_type.c_str(), class_loader.c_str());
5522}
5523
5524static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5525 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005526 ArtMethod* method,
5527 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005528 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005529 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005530 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005531 DCHECK(Thread::Current()->IsExceptionPending());
5532 DCHECK(!m->IsProxyMethod());
5533 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005534 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5535 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005536 ThrowWrappedLinkageError(klass.Get(),
5537 "While checking class %s method %s signature against %s %s: "
5538 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005539 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5540 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005541 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005542 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005543 index, arg_type.c_str(), class_loader.c_str());
5544}
5545
5546static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5547 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005548 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005549 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005550 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005551 ThrowLinkageError(klass.Get(),
5552 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005553 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5554 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005555 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005556 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005557 error_msg.c_str());
5558}
5559
Ian Rogersb5fb2072014-12-02 17:22:02 -08005560static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005561 Handle<mirror::Class> klass,
5562 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005563 ArtMethod* method1,
5564 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005565 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005566 {
5567 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005568 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005569 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005570 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005571 return false;
5572 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005573 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005574 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005575 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005576 return false;
5577 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005578 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005579 ThrowSignatureMismatch(klass, super_klass, method1,
5580 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005581 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005582 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005583 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005584 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005585 return false;
5586 }
5587 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005588 const dex::TypeList* types1 = method1->GetParameterTypeList();
5589 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005590 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005591 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005592 ThrowSignatureMismatch(klass, super_klass, method1,
5593 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005594 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005595 return false;
5596 }
5597 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005598 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005599 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005600 ThrowSignatureMismatch(klass, super_klass, method1,
5601 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005602 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005603 return false;
5604 }
5605 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005606 }
5607 uint32_t num_types = types1->Size();
5608 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005609 ThrowSignatureMismatch(klass, super_klass, method1,
5610 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005611 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005612 return false;
5613 }
5614 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005615 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005616 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005617 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005618 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005619 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005620 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005621 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005622 return false;
5623 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005624 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005625 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005626 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005627 if (UNLIKELY(other_param_type == nullptr)) {
5628 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005629 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005630 return false;
5631 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005632 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005633 ThrowSignatureMismatch(klass, super_klass, method1,
5634 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5635 i,
David Sehr709b0702016-10-13 09:12:37 -07005636 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005637 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005638 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005639 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005640 return false;
5641 }
5642 }
5643 return true;
5644}
5645
5646
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005647bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005648 if (klass->IsInterface()) {
5649 return true;
5650 }
Ian Rogers151f2212014-05-06 11:27:27 -07005651 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005652 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005653 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005654 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005655 if (klass->HasSuperClass() &&
5656 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005657 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005658 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005659 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5660 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5661 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005662 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5663 klass,
5664 super_klass,
5665 m,
5666 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005667 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005668 return false;
5669 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005670 }
5671 }
5672 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005673 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005674 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5675 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5676 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005677 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005678 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5679 j, image_pointer_size_);
5680 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5681 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005682 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5683 klass,
5684 super_klass,
5685 m,
5686 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005687 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005688 return false;
5689 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005690 }
5691 }
5692 }
5693 }
5694 return true;
5695}
5696
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005697bool ClassLinker::EnsureInitialized(Thread* self,
5698 Handle<mirror::Class> c,
5699 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005700 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005701 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005702
Mathieu Chartier524507a2014-08-27 15:28:28 -07005703 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005704 // If we've seen an initialized but not visibly initialized class
5705 // many times, request visible initialization.
5706 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5707 // Thanks to the x86 memory model classes skip the initialized status.
5708 DCHECK(c->IsVisiblyInitialized());
5709 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5710 if (self->IncrementMakeVisiblyInitializedCounter()) {
5711 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5712 }
5713 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07005714 return true;
5715 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005716 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5717 //
5718 // Ensure the bitstring is initialized before any of the class initialization
5719 // logic occurs. Once a class initializer starts running, objects can
5720 // escape into the heap and use the subtype checking code.
5721 //
5722 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5723 // can be used as a source for the IsSubClass check, and that all ancestors
5724 // of the class are Assigned (can be used as a target for IsSubClass check)
5725 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005726 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005727 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005728 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005729 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5730 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005731 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005732 if (!success) {
5733 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005734 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Vladimir Markoac576912021-03-31 11:16:22 +01005735 } else {
5736 // There may or may not be an exception pending. If there is, clear it.
5737 // We propagate the exception only if we can initialize fields and parents.
5738 self->ClearException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005739 }
5740 } else {
5741 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005742 }
5743 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005744}
5745
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005746void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5747 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005748 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005749 for (ArtField& field : new_class->GetIFields()) {
5750 if (field.GetDeclaringClass() == temp_class) {
5751 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005752 }
5753 }
5754
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005755 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005756 for (ArtField& field : new_class->GetSFields()) {
5757 if (field.GetDeclaringClass() == temp_class) {
5758 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005759 }
5760 }
5761
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005762 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005763 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005764 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005765 if (method.GetDeclaringClass() == temp_class) {
5766 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005767 }
5768 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005769
5770 // Make sure the remembered set and mod-union tables know that we updated some of the native
5771 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005772 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005773}
5774
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005775void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005776 CHECK(class_loader->GetAllocator() == nullptr);
5777 CHECK(class_loader->GetClassTable() == nullptr);
5778 Thread* const self = Thread::Current();
5779 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005780 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005781 // Create and set the class table.
5782 data.class_table = new ClassTable;
5783 class_loader->SetClassTable(data.class_table);
5784 // Create and set the linear allocator.
5785 data.allocator = Runtime::Current()->CreateLinearAlloc();
5786 class_loader->SetAllocator(data.allocator);
5787 // Add to the list so that we know to free the data later.
5788 class_loaders_.push_back(data);
5789}
5790
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005791ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005792 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005793 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005794 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005795 ClassTable* class_table = class_loader->GetClassTable();
5796 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005797 RegisterClassLoader(class_loader);
5798 class_table = class_loader->GetClassTable();
5799 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005800 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005801 return class_table;
5802}
5803
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005804ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005805 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005806}
5807
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005808static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005809 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005810 while (klass->HasSuperClass()) {
5811 klass = klass->GetSuperClass();
5812 if (klass->ShouldHaveImt()) {
5813 return klass->GetImt(pointer_size);
5814 }
5815 }
5816 return nullptr;
5817}
5818
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005819bool ClassLinker::LinkClass(Thread* self,
5820 const char* descriptor,
5821 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005822 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005823 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005824 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005825
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005826 if (!LinkSuperClass(klass)) {
5827 return false;
5828 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005829 ArtMethod* imt_data[ImTable::kSize];
5830 // If there are any new conflicts compared to super class.
5831 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005832 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005833 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005834 return false;
5835 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005836 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005837 return false;
5838 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005839 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005840 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005841 return false;
5842 }
5843 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005844 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005845
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005846 ImTable* imt = nullptr;
5847 if (klass->ShouldHaveImt()) {
5848 // If there are any new conflicts compared to the super class we can not make a copy. There
5849 // can be cases where both will have a conflict method at the same slot without having the same
5850 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5851 // will possibly create a table that is incorrect for either of the classes.
5852 // Same IMT with new_conflict does not happen very often.
5853 if (!new_conflict) {
5854 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5855 if (super_imt != nullptr) {
5856 bool imt_equals = true;
5857 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5858 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5859 }
5860 if (imt_equals) {
5861 imt = super_imt;
5862 }
5863 }
5864 }
5865 if (imt == nullptr) {
5866 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5867 imt = reinterpret_cast<ImTable*>(
5868 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5869 if (imt == nullptr) {
5870 return false;
5871 }
5872 imt->Populate(imt_data, image_pointer_size_);
5873 }
5874 }
5875
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005876 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5877 // We don't need to retire this class as it has no embedded tables or it was created the
5878 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005879 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005880
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005881 if (klass->ShouldHaveEmbeddedVTable()) {
5882 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005883 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005884 if (klass->ShouldHaveImt()) {
5885 klass->SetImt(imt, image_pointer_size_);
5886 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005887
5888 // Update CHA info based on whether we override methods.
5889 // Have to do this before setting the class as resolved which allows
5890 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005891 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005892 cha_->UpdateAfterLoadingOf(klass);
5893 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005894
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005895 // This will notify waiters on klass that saw the not yet resolved
5896 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005897 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005898 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005899 } else {
5900 CHECK(!klass->IsResolved());
5901 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005902 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01005903 Handle<mirror::Class> h_new_class =
5904 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005905 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5906 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5907 // may not see any references to the target space and clean the card for a class if another
5908 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005909 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005910 klass->SetSFieldsPtrUnchecked(nullptr);
5911 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005912 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005913 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005914 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005915 return false;
5916 }
5917
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005918 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5919 ObjectLock<mirror::Class> lock(self, h_new_class);
5920 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005921
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005922 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005923 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005924 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005925 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005926 const ObjPtr<mirror::Class> existing =
5927 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005928 if (class_loader != nullptr) {
5929 // We updated the class in the class table, perform the write barrier so that the GC knows
5930 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005931 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005932 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005933 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005934 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005935 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5936 }
5937 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005938
Mingyao Yang063fc772016-08-02 11:02:54 -07005939 // Update CHA info based on whether we override methods.
5940 // Have to do this before setting the class as resolved which allows
5941 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005942 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005943 cha_->UpdateAfterLoadingOf(h_new_class);
5944 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005945
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005946 // This will notify waiters on temp class that saw the not yet resolved class in the
5947 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005948 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005949
Vladimir Marko2c64a832018-01-04 11:31:56 +00005950 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005951 // This will notify waiters on new_class that saw the not yet resolved
5952 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005953 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005954 // Return the new class.
5955 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005956 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005957 return true;
5958}
5959
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005960bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005961 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005962 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005963 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5964 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005965 // Check that a class does not inherit from itself directly.
5966 //
5967 // TODO: This is a cheap check to detect the straightforward case
5968 // of a class extending itself (b/28685551), but we should do a
5969 // proper cycle detection on loaded classes, to detect all cases
5970 // of class circularity errors (b/28830038).
5971 if (super_class_idx == class_def.class_idx_) {
5972 ThrowClassCircularityError(klass.Get(),
5973 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005974 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005975 return false;
5976 }
5977
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005978 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005979 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005980 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005981 return false;
5982 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005983 // Verify
5984 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005985 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005986 super_class->PrettyDescriptor().c_str(),
5987 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005988 return false;
5989 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005990 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005991 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005992 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005993 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005994 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005995 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005996 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005997 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005998 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005999 DCHECK(Thread::Current()->IsExceptionPending());
6000 return false;
6001 }
6002 // Verify
6003 if (!klass->CanAccess(interface)) {
6004 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006005 ThrowIllegalAccessError(klass.Get(),
6006 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006007 interface->PrettyDescriptor().c_str(),
6008 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006009 return false;
6010 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006011 }
6012 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006013 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006014 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006015 return true;
6016}
6017
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006018bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006019 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006020 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006021 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6022 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006023 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006024 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006025 return false;
6026 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006027 return true;
6028 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006029 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006030 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006031 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006032 return false;
6033 }
6034 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006035 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006036 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6037 return false;
6038 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006039 if (super->IsFinal()) {
6040 ThrowVerifyError(klass.Get(),
6041 "Superclass %s of %s is declared final",
6042 super->PrettyDescriptor().c_str(),
6043 klass->PrettyDescriptor().c_str());
6044 return false;
6045 }
6046 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006047 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006048 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006049 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006050 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006051 return false;
6052 }
6053 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006054 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006055 super->PrettyDescriptor().c_str(),
6056 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006057 return false;
6058 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006059
Brian Carlstromf3632832014-05-20 15:36:53 -07006060 // Inherit kAccClassIsFinalizable from the superclass in case this
6061 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006062 if (super->IsFinalizable()) {
6063 klass->SetFinalizable();
6064 }
6065
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006066 // Inherit class loader flag form super class.
6067 if (super->IsClassLoaderClass()) {
6068 klass->SetClassLoaderClass();
6069 }
6070
Elliott Hughes2da50362011-10-10 16:57:08 -07006071 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006072 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006073 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006074 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006075 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006076 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006077 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006078 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006079 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006080 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006081 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006082 return false;
6083 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006084
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006085 if (kIsDebugBuild) {
6086 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006087 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006088 CHECK(super->IsResolved());
6089 super = super->GetSuperClass();
6090 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006091 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006092 return true;
6093}
6094
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006095// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6096// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6097// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006098class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006099 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006100 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006101 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006102 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006103 name_view_() {
David Sehr709b0702016-10-13 09:12:37 -07006104 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006105 }
6106
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006107 ALWAYS_INLINE std::string_view GetNameView() {
6108 if (name_view_.empty()) {
6109 name_view_ = dex_file_->StringViewByIdx(mid_->name_idx_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006110 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006111 return name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006112 }
6113
Mathieu Chartiere401d142015-04-22 13:56:20 -07006114 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006115 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006116 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006117 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006118 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006119 if (dex_file_ == other_dex_file) {
6120 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6121 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006122 return GetNameView() == other_dex_file->StringViewByIdx(other_mid.name_idx_) &&
6123 dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006124 }
6125
6126 private:
6127 // Dex file for the method to compare against.
6128 const DexFile* const dex_file_;
6129 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006130 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006131 // Lazily computed name from the dex file's strings.
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006132 std::string_view name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006133};
6134
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006135ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006136 ArtMethod* conflict_method,
6137 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006138 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006139 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006140 Runtime* const runtime = Runtime::Current();
6141 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006142
6143 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006144 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006145 ? runtime->CreateImtConflictMethod(linear_alloc)
6146 : conflict_method;
6147
6148 // Allocate a new table. Note that we will leak this table at the next conflict,
6149 // but that's a tradeoff compared to making the table fixed size.
6150 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006151 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6152 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006153 if (data == nullptr) {
6154 LOG(ERROR) << "Failed to allocate conflict table";
6155 return conflict_method;
6156 }
6157 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6158 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006159 method,
6160 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006161
6162 // Do a fence to ensure threads see the data in the table before it is assigned
6163 // to the conflict method.
6164 // Note that there is a race in the presence of multiple threads and we may leak
6165 // memory from the LinearAlloc, but that's a tradeoff compared to using
6166 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006167 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006168 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006169 return new_conflict_method;
6170}
6171
Vladimir Marko921094a2017-01-12 18:37:06 +00006172bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6173 Handle<mirror::Class> klass,
6174 Handle<mirror::IfTable> iftable) {
6175 DCHECK(!klass->IsInterface());
Vladimir Markobed84ef2022-01-21 13:57:14 +00006176 DCHECK(klass->HasSuperClass());
6177 const size_t ifcount = iftable->Count();
Vladimir Marko921094a2017-01-12 18:37:06 +00006178 for (size_t i = 0; i < ifcount; ++i) {
6179 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6180 if (num_methods > 0) {
Vladimir Marko19366b82022-01-18 10:41:28 +00006181 ObjPtr<mirror::PointerArray> method_array = AllocPointerArray(self, num_methods);
Vladimir Marko921094a2017-01-12 18:37:06 +00006182 if (UNLIKELY(method_array == nullptr)) {
6183 self->AssertPendingOOMException();
6184 return false;
6185 }
6186 iftable->SetMethodArray(i, method_array);
6187 }
6188 }
6189 return true;
6190}
6191
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006192void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6193 ArtMethod* imt_conflict_method,
6194 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006195 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006196 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006197 // Place method in imt if entry is empty, place conflict otherwise.
6198 if (*imt_ref == unimplemented_method) {
6199 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006200 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006201 // If we are not a conflict and we have the same signature and name as the imt
6202 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006203 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6204 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006205 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006206 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006207 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006208 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006209 *imt_ref = current_method;
6210 } else {
Alex Light9139e002015-10-09 15:59:48 -07006211 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006212 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006213 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006214 } else {
6215 // Place the default conflict method. Note that there may be an existing conflict
6216 // method in the IMT, but it could be one tailored to the super class, with a
6217 // specific ImtConflictTable.
6218 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006219 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006220 }
6221}
6222
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006223void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006224 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6225 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006226 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006227 Runtime* const runtime = Runtime::Current();
6228 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6229 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006230 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006231 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006232 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006233 FillIMTFromIfTable(klass->GetIfTable(),
6234 unimplemented_method,
6235 conflict_method,
6236 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006237 /*create_conflict_tables=*/true,
6238 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006239 &new_conflict,
6240 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006241 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006242 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6243 // we can just use the same pointer.
6244 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006245 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006246 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6247 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6248 bool same = true;
6249 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6250 ArtMethod* method = imt_data[i];
6251 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6252 if (method != super_method) {
6253 bool is_conflict_table = method->IsRuntimeMethod() &&
6254 method != unimplemented_method &&
6255 method != conflict_method;
6256 // Verify conflict contents.
6257 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6258 super_method != unimplemented_method &&
6259 super_method != conflict_method;
6260 if (!is_conflict_table || !super_conflict_table) {
6261 same = false;
6262 } else {
6263 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6264 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6265 same = same && table1->Equals(table2, image_pointer_size_);
6266 }
6267 }
6268 }
6269 if (same) {
6270 imt = super_imt;
6271 }
6272 }
6273 if (imt == nullptr) {
6274 imt = klass->GetImt(image_pointer_size_);
6275 DCHECK(imt != nullptr);
6276 imt->Populate(imt_data, image_pointer_size_);
6277 } else {
6278 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006279 }
6280}
6281
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006282ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6283 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006284 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006285 void* data = linear_alloc->Alloc(Thread::Current(),
6286 ImtConflictTable::ComputeSize(count,
6287 image_pointer_size));
6288 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6289}
6290
6291ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6292 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6293}
6294
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006295void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006296 ArtMethod* unimplemented_method,
6297 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006298 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006299 bool create_conflict_tables,
6300 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006301 /*out*/bool* new_conflict,
6302 /*out*/ArtMethod** imt) {
6303 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006304 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006305 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006306 const size_t num_virtuals = interface->NumVirtualMethods();
6307 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6308 // Virtual methods can be larger than the if table methods if there are default methods.
6309 DCHECK_GE(num_virtuals, method_array_count);
6310 if (kIsDebugBuild) {
6311 if (klass->IsInterface()) {
6312 DCHECK_EQ(method_array_count, 0u);
6313 } else {
6314 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6315 }
6316 }
6317 if (method_array_count == 0) {
6318 continue;
6319 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006320 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006321 for (size_t j = 0; j < method_array_count; ++j) {
6322 ArtMethod* implementation_method =
6323 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6324 if (ignore_copied_methods && implementation_method->IsCopied()) {
6325 continue;
6326 }
6327 DCHECK(implementation_method != nullptr);
6328 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6329 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6330 // or interface methods in the IMT here they will not create extra conflicts since we compare
6331 // names and signatures in SetIMTRef.
6332 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006333 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006334
6335 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6336 // the same implementation method, keep track of this to avoid creating a conflict table in
6337 // this case.
6338
6339 // Conflict table size for each IMT slot.
6340 ++conflict_counts[imt_index];
6341
6342 SetIMTRef(unimplemented_method,
6343 imt_conflict_method,
6344 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006345 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006346 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006347 }
6348 }
6349
6350 if (create_conflict_tables) {
6351 // Create the conflict tables.
6352 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006353 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006354 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006355 if (imt[i] == imt_conflict_method) {
6356 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6357 if (new_table != nullptr) {
6358 ArtMethod* new_conflict_method =
6359 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6360 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6361 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006362 } else {
6363 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006364 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006365 }
6366 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006367 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006368 }
6369 }
6370
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006371 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006372 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006373 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6374 // Virtual methods can be larger than the if table methods if there are default methods.
6375 if (method_array_count == 0) {
6376 continue;
6377 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006378 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006379 for (size_t j = 0; j < method_array_count; ++j) {
6380 ArtMethod* implementation_method =
6381 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6382 if (ignore_copied_methods && implementation_method->IsCopied()) {
6383 continue;
6384 }
6385 DCHECK(implementation_method != nullptr);
6386 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006387 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006388 if (!imt[imt_index]->IsRuntimeMethod() ||
6389 imt[imt_index] == unimplemented_method ||
6390 imt[imt_index] == imt_conflict_method) {
6391 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006392 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006393 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6394 const size_t num_entries = table->NumEntries(image_pointer_size_);
6395 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6396 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006397 }
6398 }
6399 }
6400}
6401
Vladimir Marko78f62d82022-01-10 16:25:19 +00006402namespace {
6403
Alex Lighteb7c1442015-08-31 13:17:42 -07006404// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6405// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006406static bool NotSubinterfaceOfAny(
Vladimir Marko78f62d82022-01-10 16:25:19 +00006407 const ScopedArenaHashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006408 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006409 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006410 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006411 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006412 for (ObjPtr<mirror::Class> c : classes) {
6413 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006414 return false;
6415 }
6416 }
6417 return true;
6418}
6419
Vladimir Marko78f62d82022-01-10 16:25:19 +00006420// We record new interfaces by the index of the direct interface and the index in the
6421// direct interface's `IfTable`, or `dex::kDexNoIndex` if it's the direct interface itself.
6422struct NewInterfaceReference {
6423 uint32_t direct_interface_index;
6424 uint32_t direct_interface_iftable_index;
6425};
6426
6427class ProxyInterfacesAccessor {
6428 public:
6429 explicit ProxyInterfacesAccessor(Handle<mirror::ObjectArray<mirror::Class>> interfaces)
6430 REQUIRES_SHARED(Locks::mutator_lock_)
6431 : interfaces_(interfaces) {}
6432
6433 size_t GetLength() REQUIRES_SHARED(Locks::mutator_lock_) {
6434 return interfaces_->GetLength();
6435 }
6436
6437 ObjPtr<mirror::Class> GetInterface(size_t index) REQUIRES_SHARED(Locks::mutator_lock_) {
6438 DCHECK_LT(index, GetLength());
6439 return interfaces_->GetWithoutChecks(index);
6440 }
6441
6442 private:
6443 Handle<mirror::ObjectArray<mirror::Class>> interfaces_;
6444};
6445
6446class NonProxyInterfacesAccessor {
6447 public:
6448 NonProxyInterfacesAccessor(ClassLinker* class_linker, Handle<mirror::Class> klass)
6449 REQUIRES_SHARED(Locks::mutator_lock_)
6450 : interfaces_(klass->GetInterfaceTypeList()),
6451 class_linker_(class_linker),
6452 klass_(klass) {
6453 DCHECK(!klass->IsProxyClass());
6454 }
6455
6456 size_t GetLength() REQUIRES_SHARED(Locks::mutator_lock_) {
6457 return (interfaces_ != nullptr) ? interfaces_->Size() : 0u;
6458 }
6459
6460 ObjPtr<mirror::Class> GetInterface(size_t index) REQUIRES_SHARED(Locks::mutator_lock_) {
6461 DCHECK_LT(index, GetLength());
6462 dex::TypeIndex type_index = interfaces_->GetTypeItem(index).type_idx_;
6463 return class_linker_->LookupResolvedType(type_index, klass_.Get());
6464 }
6465
6466 private:
6467 const dex::TypeList* interfaces_;
6468 ClassLinker* class_linker_;
6469 Handle<mirror::Class> klass_;
6470};
6471
6472// Finds new interfaces to add to the interface table in addition to superclass interfaces.
Alex Lighteb7c1442015-08-31 13:17:42 -07006473//
Vladimir Marko78f62d82022-01-10 16:25:19 +00006474// Interfaces in the interface table must satisfy the following constraint:
6475// all I, J: Interface | I <: J implies J precedes I
6476// (note A <: B means that A is a subtype of B). We order this backwards so that we do not need
6477// to reorder superclass interfaces when new interfaces are added in subclass's interface tables.
Alex Lighteb7c1442015-08-31 13:17:42 -07006478//
Vladimir Marko78f62d82022-01-10 16:25:19 +00006479// This function returns a list of references for all interfaces in the transitive
6480// closure of the direct interfaces that are not in the superclass interfaces.
6481// The entries in the list are ordered to satisfy the interface table ordering
6482// constraint and therefore the interface table formed by appending them to the
6483// superclass interface table shall also satisfy that constraint.
6484template <typename InterfaceAccessor>
6485ALWAYS_INLINE
6486static ArrayRef<const NewInterfaceReference> FindNewIfTableInterfaces(
6487 ObjPtr<mirror::IfTable> super_iftable,
6488 size_t super_ifcount,
6489 ScopedArenaAllocator* allocator,
6490 InterfaceAccessor&& interfaces,
6491 ArrayRef<NewInterfaceReference> initial_storage,
6492 /*out*/ScopedArenaVector<NewInterfaceReference>* supplemental_storage)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006493 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00006494 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006495
Vladimir Marko782fb712020-12-23 12:47:31 +00006496 // This is the set of all classes already in the iftable. Used to make checking
6497 // if a class has already been added quicker.
6498 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
6499 mirror::Class* buffer[kBufferSize];
Vladimir Marko78f62d82022-01-10 16:25:19 +00006500 ScopedArenaHashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize, allocator->Adapter());
Alex Lighteb7c1442015-08-31 13:17:42 -07006501 // The first super_ifcount elements are from the superclass. We note that they are already added.
6502 for (size_t i = 0; i < super_ifcount; i++) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00006503 ObjPtr<mirror::Class> iface = super_iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006504 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006505 classes_in_iftable.Put(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07006506 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006507
6508 ArrayRef<NewInterfaceReference> current_storage = initial_storage;
6509 DCHECK_NE(current_storage.size(), 0u);
6510 size_t num_new_interfaces = 0u;
6511 auto insert_reference = [&](uint32_t direct_interface_index,
6512 uint32_t direct_interface_iface_index) {
6513 if (UNLIKELY(num_new_interfaces == current_storage.size())) {
6514 bool copy = current_storage.data() != supplemental_storage->data();
6515 supplemental_storage->resize(2u * num_new_interfaces);
6516 if (copy) {
6517 std::copy_n(current_storage.data(), num_new_interfaces, supplemental_storage->data());
6518 }
6519 current_storage = ArrayRef<NewInterfaceReference>(*supplemental_storage);
6520 }
6521 current_storage[num_new_interfaces] = {direct_interface_index, direct_interface_iface_index};
6522 ++num_new_interfaces;
6523 };
6524
6525 for (size_t i = 0, num_interfaces = interfaces.GetLength(); i != num_interfaces; ++i) {
6526 ObjPtr<mirror::Class> interface = interfaces.GetInterface(i);
Vladimir Marko782fb712020-12-23 12:47:31 +00006527
Alex Lighteb7c1442015-08-31 13:17:42 -07006528 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6529 // At this point in the loop current-iface-list has the invariant that:
6530 // for every pair of interfaces I,J within it:
6531 // if index_of(I) < index_of(J) then I is not a subtype of J
6532
6533 // If we have already seen this element then all of its super-interfaces must already be in the
6534 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00006535 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006536 // We haven't seen this interface so add all of its super-interfaces onto the
6537 // current-iface-list, skipping those already on it.
6538 int32_t ifcount = interface->GetIfTableCount();
6539 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006540 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006541 if (classes_in_iftable.find(super_interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006542 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006543 classes_in_iftable.Put(super_interface.Ptr());
6544 insert_reference(i, j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006545 }
6546 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006547 // Add this interface reference after all of its super-interfaces.
Alex Lighteb7c1442015-08-31 13:17:42 -07006548 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
Vladimir Marko78f62d82022-01-10 16:25:19 +00006549 classes_in_iftable.Put(interface.Ptr());
6550 insert_reference(i, dex::kDexNoIndex);
Alex Lighteb7c1442015-08-31 13:17:42 -07006551 } else if (kIsDebugBuild) {
6552 // Check all super-interfaces are already in the list.
6553 int32_t ifcount = interface->GetIfTableCount();
6554 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006555 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006556 DCHECK(classes_in_iftable.find(super_interface.Ptr()) != classes_in_iftable.end())
David Sehr709b0702016-10-13 09:12:37 -07006557 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6558 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006559 }
6560 }
6561 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00006562 return ArrayRef<const NewInterfaceReference>(current_storage.data(), num_new_interfaces);
6563}
6564
6565template <typename InterfaceAccessor>
6566static ObjPtr<mirror::IfTable> SetupInterfaceLookupTable(
6567 Thread* self,
6568 Handle<mirror::Class> klass,
6569 ScopedArenaAllocator* allocator,
6570 InterfaceAccessor&& interfaces)
6571 REQUIRES_SHARED(Locks::mutator_lock_) {
6572 DCHECK(klass->HasSuperClass());
6573 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
6574 const size_t super_ifcount = super_iftable->Count();
6575 const size_t num_interfaces = interfaces.GetLength();
6576
6577 // If there are no new interfaces, we can recycle parent's interface table if the class
6578 // inherits no interfaces from the superclass (this is always the case for interfaces as
6579 // their superclass `java.lang.Object` does not implement any interface), or there are no
6580 // new virtuals, or all interfaces inherited from the superclass are just marker interfaces.
6581 auto is_marker_iface = [=](size_t index) REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
6582 return super_iftable->GetMethodArrayCount(index) == 0;
6583 };
6584 auto can_reuse_super_iftable = [=]() REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE{
6585 if (super_ifcount == 0u) {
6586 return true;
6587 }
6588 DCHECK(!klass->IsInterface());
6589 return klass->NumDeclaredVirtualMethods() == 0u ||
6590 std::all_of(CountIter(0), CountIter(super_ifcount), is_marker_iface);
6591 };
6592 if (num_interfaces == 0 && can_reuse_super_iftable()) {
6593 return super_iftable;
6594 }
6595
6596 // Check that every class being implemented is an interface.
6597 for (size_t i = 0; i != num_interfaces; ++i) {
6598 ObjPtr<mirror::Class> interface = interfaces.GetInterface(i);
6599 DCHECK(interface != nullptr);
6600 if (UNLIKELY(!interface->IsInterface())) {
6601 ThrowIncompatibleClassChangeError(klass.Get(),
6602 "Class %s implements non-interface class %s",
6603 klass->PrettyDescriptor().c_str(),
6604 interface->PrettyDescriptor().c_str());
6605 return nullptr;
6606 }
6607 }
6608
6609 static constexpr size_t kMaxStackReferences = 16;
6610 NewInterfaceReference initial_storage[kMaxStackReferences];
6611 ScopedArenaVector<NewInterfaceReference> supplemental_storage(allocator->Adapter());
6612 ArrayRef<const NewInterfaceReference> new_interface_references =
6613 FindNewIfTableInterfaces(
6614 super_iftable,
6615 super_ifcount,
6616 allocator,
6617 interfaces,
6618 ArrayRef<NewInterfaceReference>(initial_storage),
6619 &supplemental_storage);
6620
6621 // If all declared interfaces were already present in superclass interface table, we can
6622 // re-check if other conditions of reusing the superclass interface table are satisfied.
6623 if (UNLIKELY(num_interfaces != 0u && new_interface_references.empty())) {
6624 DCHECK(!klass->IsInterface());
6625 if (can_reuse_super_iftable()) {
6626 return super_iftable;
6627 }
6628 }
6629
6630 // Create the interface table.
6631 size_t ifcount = super_ifcount + new_interface_references.size();
6632 ObjPtr<mirror::IfTable> iftable = AllocIfTable(self, ifcount, super_iftable->GetClass());
6633 if (UNLIKELY(iftable == nullptr)) {
6634 self->AssertPendingOOMException();
6635 return nullptr;
6636 }
6637 // Fill in table with superclass's iftable.
6638 if (super_ifcount != 0) {
6639 // Reload `super_iftable` as it may have been clobbered by the allocation.
6640 super_iftable = klass->GetSuperClass()->GetIfTable();
6641 for (size_t i = 0; i < super_ifcount; i++) {
6642 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
6643 iftable->SetInterface(i, super_interface);
6644 }
6645 }
6646 // Fill in the table with additional interfaces.
6647 size_t current_index = super_ifcount;
6648 for (NewInterfaceReference ref : new_interface_references) {
6649 ObjPtr<mirror::Class> direct_interface = interfaces.GetInterface(ref.direct_interface_index);
6650 ObjPtr<mirror::Class> new_interface = (ref.direct_interface_iftable_index != dex::kDexNoIndex)
6651 ? direct_interface->GetIfTable()->GetInterface(ref.direct_interface_iftable_index)
6652 : direct_interface;
6653 iftable->SetInterface(current_index, new_interface);
6654 ++current_index;
6655 }
6656 DCHECK_EQ(current_index, ifcount);
6657
Alex Lighteb7c1442015-08-31 13:17:42 -07006658 if (kIsDebugBuild) {
6659 // Check that the iftable is ordered correctly.
Vladimir Marko78f62d82022-01-10 16:25:19 +00006660 for (size_t i = 0; i < ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006661 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Vladimir Marko78f62d82022-01-10 16:25:19 +00006662 for (size_t j = i + 1; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006663 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006664 // !(if_a <: if_b)
6665 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006666 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6667 << ") extends "
6668 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006669 << "interface list.";
6670 }
6671 }
6672 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006673
Vladimir Marko78f62d82022-01-10 16:25:19 +00006674 return iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006675}
6676
Alex Light1f3925d2016-09-07 12:04:20 -07006677// Check that all vtable entries are present in this class's virtuals or are the same as a
6678// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006679void CheckClassOwnsVTableEntries(Thread* self,
6680 Handle<mirror::Class> klass,
6681 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006682 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07006683 StackHandleScope<2> hs(self);
6684 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006685 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07006686 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006687 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08006688 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6689 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6690 CHECK(m != nullptr);
6691
Alex Lighta41a30782017-03-29 11:33:19 -07006692 if (m->GetMethodIndexDuringLinking() != i) {
6693 LOG(WARNING) << m->PrettyMethod()
6694 << " has an unexpected method index for its spot in the vtable for class"
6695 << klass->PrettyClass();
6696 }
Alex Lighte64300b2015-12-15 15:02:47 -08006697 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6698 auto is_same_method = [m] (const ArtMethod& meth) {
6699 return &meth == m;
6700 };
Alex Light3f980532017-03-17 15:10:32 -07006701 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6702 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
6703 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
6704 << klass->PrettyClass() << " or any of its superclasses!";
6705 }
Alex Lighte64300b2015-12-15 15:02:47 -08006706 }
6707}
6708
Alex Light1f3925d2016-09-07 12:04:20 -07006709// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
6710// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08006711template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006712void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07006713 REQUIRES_SHARED(Locks::mutator_lock_) {
6714 StackHandleScope<1> hs(self);
6715 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6716 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006717
6718 // Observations:
6719 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
6720 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
6721 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
6722 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
6723 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
6724 // * The single-pass algorithm will trade memory for speed, but that is OK.
6725
6726 CHECK_GT(num_entries, 0);
6727
6728 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
6729 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
6730 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
6731 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
6732 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
6733 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
6734 << m2->PrettyMethod() << " (0x" << std::hex
6735 << reinterpret_cast<uintptr_t>(m2) << ")";
6736 };
6737 struct BaseHashType {
6738 static size_t HashCombine(size_t seed, size_t val) {
6739 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
6740 }
6741 };
6742
6743 // Check assuming all entries come from the same dex file.
6744 {
6745 // Find the first interesting method and its dex file.
6746 int32_t start = 0;
6747 for (; start < num_entries; ++start) {
6748 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
6749 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
6750 // maybe).
6751 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6752 vtable_entry->GetAccessFlags())) {
6753 continue;
6754 }
6755 break;
6756 }
6757 if (start == num_entries) {
6758 return;
6759 }
6760 const DexFile* dex_file =
6761 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
6762 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
6763
6764 // Helper function to avoid logging if we have to run the cross-file checks.
6765 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
6766 // Use a map to store seen entries, as the storage space is too large for a bitvector.
6767 using PairType = std::pair<uint32_t, uint16_t>;
6768 struct PairHash : BaseHashType {
6769 size_t operator()(const PairType& key) const {
6770 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
6771 }
6772 };
Vladimir Marko782fb712020-12-23 12:47:31 +00006773 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006774 seen.reserve(2 * num_entries);
6775 bool need_slow_path = false;
6776 bool found_dup = false;
6777 for (int i = start; i < num_entries; ++i) {
6778 // Can use Unchecked here as the start loop already ensured that the arrays are correct
6779 // wrt/ kPointerSize.
6780 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
6781 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6782 vtable_entry->GetAccessFlags())) {
6783 continue;
6784 }
6785 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
6786 if (dex_file != m->GetDexFile()) {
6787 need_slow_path = true;
6788 break;
6789 }
6790 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
6791 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
6792 auto it = seen.find(pair);
6793 if (it != seen.end()) {
6794 found_dup = true;
6795 if (log_warn) {
6796 log_fn(it->second, i);
6797 }
6798 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00006799 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006800 }
6801 }
6802 return std::make_pair(need_slow_path, found_dup);
6803 };
6804 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
6805 if (!result.first) {
6806 if (result.second) {
6807 check_fn(/* log_warn= */ true);
6808 }
6809 return;
6810 }
6811 }
6812
6813 // Need to check across dex files.
6814 struct Entry {
6815 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00006816 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006817 const char* name = nullptr;
6818 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006819
Vladimir Marko782fb712020-12-23 12:47:31 +00006820 Entry() = default;
6821 Entry(const Entry& other) = default;
6822 Entry& operator=(const Entry& other) = default;
6823
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006824 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00006825 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
6826 // This call writes `name_len` and it is therefore necessary that the
6827 // initializer for `name_len` comes before it, otherwise the value
6828 // from the call would be overwritten by that initializer.
6829 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006830 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00006831 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
6832 if (name[name_len] != 0) {
6833 name_len += strlen(name + name_len);
6834 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006835 }
6836
6837 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00006838 return name_len == other.name_len &&
6839 memcmp(name, other.name, name_len) == 0 &&
6840 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006841 }
6842 };
6843 struct EntryHash {
6844 size_t operator()(const Entry& key) const {
6845 return key.cached_hash;
6846 }
6847 };
Vladimir Marko782fb712020-12-23 12:47:31 +00006848 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006849 for (int32_t i = 0; i < num_entries; ++i) {
6850 // Can use Unchecked here as the first loop already ensured that the arrays are correct
6851 // wrt/ kPointerSize.
6852 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
6853 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
6854 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07006855 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
6856 vtable_entry->GetAccessFlags())) {
6857 continue;
6858 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006859 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
6860 const DexFile* dex_file = m->GetDexFile();
6861 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
6862
6863 Entry e(dex_file, mid);
6864
6865 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
6866 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
6867 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
6868 sig_hash);
6869
6870 auto it = map.find(e);
6871 if (it != map.end()) {
6872 log_fn(it->second, i);
6873 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00006874 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07006875 }
6876 }
6877}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006878
6879void CheckVTableHasNoDuplicates(Thread* self,
6880 Handle<mirror::Class> klass,
6881 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08006882 REQUIRES_SHARED(Locks::mutator_lock_) {
6883 switch (pointer_size) {
6884 case PointerSize::k64:
6885 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
6886 break;
6887 case PointerSize::k32:
6888 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
6889 break;
6890 }
6891}
Alex Light1f3925d2016-09-07 12:04:20 -07006892
Orion Hodson5880c772020-07-28 20:12:08 +01006893static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07006894 REQUIRES_SHARED(Locks::mutator_lock_) {
6895 CheckClassOwnsVTableEntries(self, klass, pointer_size);
6896 CheckVTableHasNoDuplicates(self, klass, pointer_size);
6897}
6898
Andreas Gampe9f3928f2019-02-04 11:19:31 -08006899} // namespace
6900
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006901void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6902 ArtMethod* unimplemented_method,
6903 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006904 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006905 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07006906 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006907 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006908 if (super_class->ShouldHaveImt()) {
6909 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6910 for (size_t i = 0; i < ImTable::kSize; ++i) {
6911 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07006912 }
6913 } else {
6914 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006915 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08006916 if (if_table->Count() != 0) {
Vladimir Marko19366b82022-01-18 10:41:28 +00006917 // Ignore copied methods, we will handle these later.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006918 FillIMTFromIfTable(if_table,
6919 unimplemented_method,
6920 imt_conflict_method,
6921 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006922 /*create_conflict_tables=*/false,
6923 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006924 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006925 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07006926 }
6927 }
6928}
6929
Vladimir Markob91402f2021-12-21 15:55:06 +00006930template <PointerSize kPointerSize>
Vladimir Markobc893672021-11-10 15:25:46 +00006931class ClassLinker::LinkMethodsHelper {
Vladimir Marko921094a2017-01-12 18:37:06 +00006932 public:
Vladimir Markobc893672021-11-10 15:25:46 +00006933 LinkMethodsHelper(ClassLinker* class_linker,
6934 Handle<mirror::Class> klass,
6935 Thread* self,
6936 Runtime* runtime)
Vladimir Marko921094a2017-01-12 18:37:06 +00006937 : class_linker_(class_linker),
6938 klass_(klass),
Vladimir Marko921094a2017-01-12 18:37:06 +00006939 self_(self),
Vladimir Marko78f62d82022-01-10 16:25:19 +00006940 runtime_(runtime),
Vladimir Marko921094a2017-01-12 18:37:06 +00006941 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
6942 allocator_(&stack_),
Vladimir Marko19366b82022-01-18 10:41:28 +00006943 copied_method_records_(copied_method_records_initial_buffer_,
6944 kCopiedMethodRecordInitialBufferSize,
6945 allocator_.Adapter()),
6946 num_new_copied_methods_(0u) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006947 }
6948
Vladimir Marko78f62d82022-01-10 16:25:19 +00006949 // Links the virtual and interface methods for the given class.
Vladimir Markobc893672021-11-10 15:25:46 +00006950 //
6951 // Arguments:
6952 // * self - The current thread.
6953 // * klass - class, whose vtable will be filled in.
Vladimir Marko78f62d82022-01-10 16:25:19 +00006954 // * interfaces - implemented interfaces for a proxy class, otherwise null.
6955 // * out_new_conflict - whether there is a new conflict compared to the superclass.
6956 // * out_imt - interface method table to fill.
6957 bool LinkMethods(
Vladimir Markobc893672021-11-10 15:25:46 +00006958 Thread* self,
6959 Handle<mirror::Class> klass,
Vladimir Marko78f62d82022-01-10 16:25:19 +00006960 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Vladimir Markobc893672021-11-10 15:25:46 +00006961 bool* out_new_conflict,
6962 ArtMethod** out_imt)
6963 REQUIRES_SHARED(Locks::mutator_lock_);
6964
6965 private:
Vladimir Marko8670e042021-12-21 17:55:48 +00006966 // Assign vtable indexes to declared virtual methods for a non-interface class other
6967 // than `java.lang.Object`. Returns the number of vtable entries on success, 0 on failure.
Vladimir Marko19366b82022-01-18 10:41:28 +00006968 // This function also assigns vtable indexes for interface methods in new interfaces
6969 // and records data for copied methods which shall be referenced by the vtable.
Vladimir Markobed84ef2022-01-21 13:57:14 +00006970 size_t AssignVTableIndexes(ObjPtr<mirror::Class> klass,
Vladimir Marko8670e042021-12-21 17:55:48 +00006971 ObjPtr<mirror::Class> super_class,
Vladimir Marko19366b82022-01-18 10:41:28 +00006972 size_t num_virtual_methods,
6973 ObjPtr<mirror::IfTable> iftable)
6974 REQUIRES_SHARED(Locks::mutator_lock_);
6975
6976 bool FindCopiedMethodsForInterface(ObjPtr<mirror::Class> klass,
6977 size_t num_virtual_methods,
6978 ObjPtr<mirror::IfTable> iftable)
Vladimir Marko8670e042021-12-21 17:55:48 +00006979 REQUIRES_SHARED(Locks::mutator_lock_);
6980
Vladimir Marko78f62d82022-01-10 16:25:19 +00006981 bool LinkJavaLangObjectMethods(Thread* self, Handle<mirror::Class> klass)
Vladimir Markob91402f2021-12-21 15:55:06 +00006982 REQUIRES_SHARED(Locks::mutator_lock_) COLD_ATTR;
6983
Vladimir Marko19366b82022-01-18 10:41:28 +00006984 void ReallocMethods(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_);
6985 void FinalizeIfTable(ObjPtr<mirror::IfTable> iftable,
6986 ObjPtr<mirror::PointerArray> vtable,
6987 bool* out_new_conflict,
6988 ArtMethod** out_imt)
Vladimir Marko78f62d82022-01-10 16:25:19 +00006989 REQUIRES_SHARED(Locks::mutator_lock_);
6990
Vladimir Marko921094a2017-01-12 18:37:06 +00006991 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
6992 LengthPrefixedArray<ArtMethod>* methods) {
Vladimir Marko19366b82022-01-18 10:41:28 +00006993 if (kIsDebugBuild && old_methods != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006994 CHECK(methods != nullptr);
6995 // Put some random garbage in old methods to help find stale pointers.
Vladimir Marko19366b82022-01-18 10:41:28 +00006996 if (methods != old_methods) {
Vladimir Marko921094a2017-01-12 18:37:06 +00006997 // Need to make sure the GC is not running since it could be scanning the methods we are
6998 // about to overwrite.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00006999 ScopedThreadStateChange tsc(self_, ThreadState::kSuspended);
Vladimir Marko921094a2017-01-12 18:37:06 +00007000 gc::ScopedGCCriticalSection gcs(self_,
7001 gc::kGcCauseClassLinker,
7002 gc::kCollectorTypeClassLinker);
7003 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
Vladimir Markob91402f2021-12-21 15:55:06 +00007004 kMethodSize,
7005 kMethodAlignment);
Vladimir Marko921094a2017-01-12 18:37:06 +00007006 memset(old_methods, 0xFEu, old_size);
7007 }
7008 }
7009 }
7010
Vladimir Marko19366b82022-01-18 10:41:28 +00007011 NO_INLINE
7012 void LogNewVirtuals(LengthPrefixedArray<ArtMethod>* methods) const
7013 REQUIRES_SHARED(Locks::mutator_lock_) {
7014 ObjPtr<mirror::Class> klass = klass_.Get();
7015 size_t num_new_copied_methods = num_new_copied_methods_;
7016 size_t old_method_count = methods->size() - num_new_copied_methods;
7017 size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
7018 size_t num_miranda_methods = 0u;
7019 size_t num_overriding_default_methods = 0u;
7020 size_t num_default_methods = 0u;
7021 size_t num_overriding_default_conflict_methods = 0u;
7022 size_t num_default_conflict_methods = 0u;
7023 for (size_t i = 0; i != num_new_copied_methods; ++i) {
7024 ArtMethod& m = methods->At(old_method_count + i, kMethodSize, kMethodAlignment);
7025 if (m.IsDefault()) {
7026 if (m.GetMethodIndexDuringLinking() < super_vtable_length) {
7027 ++num_overriding_default_methods;
7028 } else {
7029 ++num_default_methods;
7030 }
7031 } else if (m.IsDefaultConflicting()) {
7032 if (m.GetMethodIndexDuringLinking() < super_vtable_length) {
7033 ++num_overriding_default_conflict_methods;
7034 } else {
7035 ++num_default_conflict_methods;
7036 }
7037 } else {
7038 DCHECK(m.IsMiranda());
7039 ++num_miranda_methods;
7040 }
Vladimir Marko5cfb7bb2022-01-28 11:12:17 +00007041 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007042 VLOG(class_linker) << klass->PrettyClass() << ": miranda_methods=" << num_miranda_methods
7043 << " default_methods=" << num_default_methods
7044 << " overriding_default_methods=" << num_overriding_default_methods
7045 << " default_conflict_methods=" << num_default_conflict_methods
Vladimir Marko921094a2017-01-12 18:37:06 +00007046 << " overriding_default_conflict_methods="
Vladimir Marko19366b82022-01-18 10:41:28 +00007047 << num_overriding_default_conflict_methods;
Vladimir Marko921094a2017-01-12 18:37:06 +00007048 }
7049
Vladimir Marko8670e042021-12-21 17:55:48 +00007050 class MethodIndexEmptyFn {
7051 public:
7052 void MakeEmpty(uint32_t& item) const {
7053 item = dex::kDexNoIndex;
7054 }
7055 bool IsEmpty(const uint32_t& item) const {
7056 return item == dex::kDexNoIndex;
7057 }
7058 };
7059
Vladimir Marko7ddae992022-01-18 14:27:20 +00007060 class VTableIndexCheckerDebug {
7061 protected:
7062 explicit VTableIndexCheckerDebug(size_t vtable_length)
7063 : vtable_length_(vtable_length) {}
Vladimir Marko8670e042021-12-21 17:55:48 +00007064
Vladimir Marko7ddae992022-01-18 14:27:20 +00007065 void CheckIndex(uint32_t index) const {
7066 CHECK_LT(index, vtable_length_);
Vladimir Marko8670e042021-12-21 17:55:48 +00007067 }
7068
7069 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007070 uint32_t vtable_length_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007071 };
7072
Vladimir Marko7ddae992022-01-18 14:27:20 +00007073 class VTableIndexCheckerRelease {
7074 protected:
7075 explicit VTableIndexCheckerRelease(size_t vtable_length ATTRIBUTE_UNUSED) {}
7076 void CheckIndex(uint32_t index ATTRIBUTE_UNUSED) const {}
7077 };
Vladimir Marko8670e042021-12-21 17:55:48 +00007078
Vladimir Marko7ddae992022-01-18 14:27:20 +00007079 using VTableIndexChecker =
7080 std::conditional_t<kIsDebugBuild, VTableIndexCheckerDebug, VTableIndexCheckerRelease>;
7081
7082 class VTableAccessor : private VTableIndexChecker {
7083 public:
7084 VTableAccessor(uint8_t* raw_vtable, size_t vtable_length)
7085 REQUIRES_SHARED(Locks::mutator_lock_)
7086 : VTableIndexChecker(vtable_length),
7087 raw_vtable_(raw_vtable) {}
Vladimir Marko8670e042021-12-21 17:55:48 +00007088
7089 ArtMethod* GetVTableEntry(uint32_t index) const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko7ddae992022-01-18 14:27:20 +00007090 this->CheckIndex(index);
7091 uint8_t* entry = raw_vtable_ + static_cast<size_t>(kPointerSize) * index;
7092 if (kPointerSize == PointerSize::k64) {
7093 return reinterpret_cast64<ArtMethod*>(*reinterpret_cast<uint64_t*>(entry));
7094 } else {
7095 return reinterpret_cast32<ArtMethod*>(*reinterpret_cast<uint32_t*>(entry));
7096 }
Vladimir Marko8670e042021-12-21 17:55:48 +00007097 }
7098
7099 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007100 uint8_t* raw_vtable_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007101 };
7102
Vladimir Marko8670e042021-12-21 17:55:48 +00007103 class VTableSignatureHash {
7104 public:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007105 explicit VTableSignatureHash(VTableAccessor accessor)
Vladimir Marko8670e042021-12-21 17:55:48 +00007106 REQUIRES_SHARED(Locks::mutator_lock_)
7107 : accessor_(accessor) {}
7108
7109 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7110 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7111 return ComputeMethodHash(method);
7112 }
7113
7114 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7115 size_t operator()(uint32_t index) const NO_THREAD_SAFETY_ANALYSIS {
7116 return ComputeMethodHash(accessor_.GetVTableEntry(index));
7117 }
7118
7119 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007120 VTableAccessor accessor_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007121 };
7122
Vladimir Marko8670e042021-12-21 17:55:48 +00007123 class VTableSignatureEqual {
7124 public:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007125 explicit VTableSignatureEqual(VTableAccessor accessor)
Vladimir Marko8670e042021-12-21 17:55:48 +00007126 REQUIRES_SHARED(Locks::mutator_lock_)
7127 : accessor_(accessor) {}
7128
7129 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7130 bool operator()(uint32_t lhs_index, ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
Vladimir Markobed84ef2022-01-21 13:57:14 +00007131 return MethodSignatureEquals(accessor_.GetVTableEntry(lhs_index), rhs);
Vladimir Marko8670e042021-12-21 17:55:48 +00007132 }
7133
7134 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7135 bool operator()(uint32_t lhs_index, uint32_t rhs_index) const NO_THREAD_SAFETY_ANALYSIS {
7136 return (*this)(lhs_index, accessor_.GetVTableEntry(rhs_index));
7137 }
7138
7139 private:
Vladimir Marko7ddae992022-01-18 14:27:20 +00007140 VTableAccessor accessor_;
Vladimir Marko8670e042021-12-21 17:55:48 +00007141 };
7142
Vladimir Marko7ddae992022-01-18 14:27:20 +00007143 using VTableSignatureSet =
7144 ScopedArenaHashSet<uint32_t, MethodIndexEmptyFn, VTableSignatureHash, VTableSignatureEqual>;
Vladimir Marko8670e042021-12-21 17:55:48 +00007145
Vladimir Marko19366b82022-01-18 10:41:28 +00007146 class DeclaredVirtualSignatureHash {
7147 public:
7148 explicit DeclaredVirtualSignatureHash(ObjPtr<mirror::Class> klass)
7149 REQUIRES_SHARED(Locks::mutator_lock_)
7150 : klass_(klass) {}
7151
7152 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7153 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7154 return ComputeMethodHash(method);
7155 }
7156
7157 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7158 size_t operator()(uint32_t index) const NO_THREAD_SAFETY_ANALYSIS {
7159 DCHECK_LT(index, klass_->NumDeclaredVirtualMethods());
7160 ArtMethod* method = klass_->GetVirtualMethodDuringLinking(index, kPointerSize);
7161 return ComputeMethodHash(method->GetInterfaceMethodIfProxy(kPointerSize));
7162 }
7163
7164 private:
7165 ObjPtr<mirror::Class> klass_;
7166 };
7167
7168 class DeclaredVirtualSignatureEqual {
7169 public:
7170 explicit DeclaredVirtualSignatureEqual(ObjPtr<mirror::Class> klass)
7171 REQUIRES_SHARED(Locks::mutator_lock_)
7172 : klass_(klass) {}
7173
7174 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7175 bool operator()(uint32_t lhs_index, ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
7176 DCHECK_LT(lhs_index, klass_->NumDeclaredVirtualMethods());
7177 ArtMethod* lhs = klass_->GetVirtualMethodDuringLinking(lhs_index, kPointerSize);
7178 return MethodSignatureEquals(lhs->GetInterfaceMethodIfProxy(kPointerSize), rhs);
7179 }
7180
7181 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7182 bool operator()(uint32_t lhs_index, uint32_t rhs_index) const NO_THREAD_SAFETY_ANALYSIS {
7183 DCHECK_LT(lhs_index, klass_->NumDeclaredVirtualMethods());
7184 DCHECK_LT(rhs_index, klass_->NumDeclaredVirtualMethods());
7185 return lhs_index == rhs_index;
7186 }
7187
7188 private:
7189 ObjPtr<mirror::Class> klass_;
7190 };
7191
7192 using DeclaredVirtualSignatureSet = ScopedArenaHashSet<uint32_t,
7193 MethodIndexEmptyFn,
7194 DeclaredVirtualSignatureHash,
7195 DeclaredVirtualSignatureEqual>;
7196
7197 // Helper class to keep records for determining the correct copied method to create.
7198 class CopiedMethodRecord {
7199 public:
7200 enum class State : uint32_t {
7201 // Note: The `*Single` values are used when we know that there is only one interface
7202 // method with the given signature that's not masked; that method is the main method.
7203 // We use this knowledge for faster masking check, otherwise we need to search for
7204 // a masking method through methods of all interfaces that could potentially mask it.
7205 kAbstractSingle,
7206 kDefaultSingle,
7207 kAbstract,
7208 kDefault,
7209 kDefaultConflict,
7210 kUseSuperMethod,
7211 };
7212
7213 CopiedMethodRecord()
7214 : main_method_(nullptr),
7215 method_index_(0u),
7216 state_(State::kAbstractSingle) {}
7217
7218 CopiedMethodRecord(ArtMethod* main_method, size_t vtable_index)
7219 : main_method_(main_method),
7220 method_index_(vtable_index),
7221 state_(State::kAbstractSingle) {}
7222
7223 // Set main method. The new main method must be more specific implementation.
7224 void SetMainMethod(ArtMethod* main_method) {
7225 DCHECK(main_method_ != nullptr);
7226 main_method_ = main_method;
7227 }
7228
7229 // The main method is the first encountered default method if any,
7230 // otherwise the first encountered abstract method.
7231 ArtMethod* GetMainMethod() const {
7232 return main_method_;
7233 }
7234
7235 void SetMethodIndex(size_t method_index) {
7236 DCHECK_NE(method_index, dex::kDexNoIndex);
7237 method_index_ = method_index;
7238 }
7239
7240 size_t GetMethodIndex() const {
7241 DCHECK_NE(method_index_, dex::kDexNoIndex);
7242 return method_index_;
7243 }
7244
7245 void SetState(State state) {
7246 state_ = state;
7247 }
7248
7249 State GetState() const {
7250 return state_;
7251 }
7252
7253 ALWAYS_INLINE
7254 void UpdateStateForInterface(ObjPtr<mirror::Class> iface,
7255 ArtMethod* interface_method,
7256 ObjPtr<mirror::IfTable> iftable,
7257 size_t ifcount,
7258 size_t index)
7259 REQUIRES_SHARED(Locks::mutator_lock_) {
7260 DCHECK_EQ(ifcount, iftable->Count());
7261 DCHECK_LT(index, ifcount);
7262 DCHECK(iface == interface_method->GetDeclaringClass());
7263 DCHECK(iface == iftable->GetInterface(index));
7264 DCHECK(interface_method->IsDefault());
7265 if (GetState() != State::kDefaultConflict) {
7266 DCHECK(GetState() == State::kDefault);
7267 // We do not record all overriding methods, so we need to walk over all
7268 // interfaces that could mask the `interface_method`.
7269 if (ContainsOverridingMethodOf(iftable, index + 1, ifcount, iface, interface_method)) {
7270 return; // Found an overriding method that masks `interface_method`.
7271 }
7272 // We have a new default method that's not masked by any other method.
7273 SetState(State::kDefaultConflict);
7274 }
7275 }
7276
7277 ALWAYS_INLINE
7278 void UpdateState(ObjPtr<mirror::Class> iface,
7279 ArtMethod* interface_method,
7280 size_t vtable_index,
7281 ObjPtr<mirror::IfTable> iftable,
7282 size_t ifcount,
7283 size_t index)
7284 REQUIRES_SHARED(Locks::mutator_lock_) {
7285 DCHECK_EQ(ifcount, iftable->Count());
7286 DCHECK_LT(index, ifcount);
7287 if (kIsDebugBuild) {
7288 if (interface_method->IsCopied()) {
7289 // Called from `FinalizeState()` for a default method from superclass.
7290 // The `index` points to the last interface inherited from the superclass
7291 // as we need to search only the new interfaces for masking methods.
7292 DCHECK(interface_method->IsDefault());
7293 } else {
7294 DCHECK(iface == interface_method->GetDeclaringClass());
7295 DCHECK(iface == iftable->GetInterface(index));
7296 }
7297 }
7298 DCHECK_EQ(vtable_index, method_index_);
7299 auto slow_is_masked = [=]() REQUIRES_SHARED(Locks::mutator_lock_) {
7300 return ContainsImplementingMethod(iftable, index + 1, ifcount, iface, vtable_index);
7301 };
7302 UpdateStateImpl(iface, interface_method, slow_is_masked);
7303 }
7304
7305 ALWAYS_INLINE
7306 void FinalizeState(ArtMethod* super_method,
7307 size_t vtable_index,
7308 ObjPtr<mirror::IfTable> iftable,
7309 size_t ifcount,
7310 ObjPtr<mirror::IfTable> super_iftable,
7311 size_t super_ifcount)
7312 REQUIRES_SHARED(Locks::mutator_lock_) {
7313 DCHECK(super_method->IsCopied());
7314 DCHECK_EQ(vtable_index, method_index_);
7315 DCHECK_EQ(vtable_index, super_method->GetMethodIndex());
7316 DCHECK_NE(super_ifcount, 0u);
7317 if (super_method->IsDefault()) {
7318 if (UNLIKELY(super_method->IsDefaultConflicting())) {
7319 // Some of the default methods that contributed to the conflict in the superclass
7320 // may be masked by new interfaces. Walk over all the interfaces and update state
7321 // as long as the current state is not `kDefaultConflict`.
7322 size_t i = super_ifcount;
7323 while (GetState() != State::kDefaultConflict && i != 0u) {
7324 --i;
7325 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
7326 DCHECK(iface == super_iftable->GetInterface(i));
7327 auto [found, index] =
7328 MethodArrayContains(super_iftable->GetMethodArrayOrNull(i), super_method);
7329 if (found) {
7330 ArtMethod* interface_method = iface->GetVirtualMethod(index, kPointerSize);
7331 auto slow_is_masked = [=]() REQUIRES_SHARED(Locks::mutator_lock_) {
7332 // Note: The `iftable` has method arrays in range [super_ifcount, ifcount) filled
7333 // with vtable indexes but the range [0, super_ifcount) is empty, so we need to
7334 // use the `super_iftable` filled with implementation methods for that range.
7335 return ContainsImplementingMethod(
7336 super_iftable, i + 1u, super_ifcount, iface, super_method) ||
7337 ContainsImplementingMethod(
7338 iftable, super_ifcount, ifcount, iface, vtable_index);
7339 };
7340 UpdateStateImpl(iface, interface_method, slow_is_masked);
7341 }
7342 }
7343 if (GetState() == State::kDefaultConflict) {
7344 SetState(State::kUseSuperMethod);
7345 }
7346 } else {
7347 // There was exactly one default method in superclass interfaces that was
7348 // not masked by subinterfaces. Use `UpdateState()` to process it and pass
7349 // `super_ifcount - 1` as index for checking if it's been masked by new interfaces.
7350 ObjPtr<mirror::Class> iface = super_method->GetDeclaringClass();
7351 UpdateState(
7352 iface, super_method, vtable_index, iftable, ifcount, /*index=*/ super_ifcount - 1u);
7353 if (GetMainMethod() == super_method) {
7354 DCHECK(GetState() == State::kDefault) << enum_cast<uint32_t>(GetState());
7355 SetState(State::kUseSuperMethod);
7356 }
7357 }
7358 } else {
7359 DCHECK(super_method->IsMiranda());
7360 // Any default methods with this signature in superclass interfaces have been
7361 // masked by subinterfaces. Check if we can reuse the miranda method.
7362 if (GetState() == State::kAbstractSingle || GetState() == State::kAbstract) {
7363 SetState(State::kUseSuperMethod);
7364 }
7365 }
7366 }
7367
7368 private:
7369 template <typename Predicate>
7370 ALWAYS_INLINE
7371 void UpdateStateImpl(ObjPtr<mirror::Class> iface,
7372 ArtMethod* interface_method,
7373 Predicate&& slow_is_masked)
7374 REQUIRES_SHARED(Locks::mutator_lock_) {
7375 bool have_default = false;
7376 switch (GetState()) {
7377 case State::kDefaultSingle:
7378 have_default = true;
7379 FALLTHROUGH_INTENDED;
7380 case State::kAbstractSingle:
7381 if (GetMainMethod()->GetDeclaringClass()->Implements(iface)) {
7382 return; // The main method masks the `interface_method`.
7383 }
7384 if (!interface_method->IsDefault()) {
7385 SetState(have_default ? State::kDefault : State::kAbstract);
7386 return;
7387 }
7388 break;
7389 case State::kDefault:
7390 have_default = true;
7391 FALLTHROUGH_INTENDED;
7392 case State::kAbstract:
7393 if (!interface_method->IsDefault()) {
7394 return; // Keep the same state. We do not need to check for masking.
7395 }
7396 // We do not record all overriding methods, so we need to walk over all
7397 // interfaces that could mask the `interface_method`. The provided
7398 // predicate `slow_is_masked()` does that.
7399 if (slow_is_masked()) {
7400 return; // Found an overriding method that masks `interface_method`.
7401 }
7402 break;
7403 case State::kDefaultConflict:
7404 return; // The state cannot change anymore.
7405 default:
7406 LOG(FATAL) << "Unexpected state: " << enum_cast<uint32_t>(GetState());
7407 UNREACHABLE();
7408 }
7409 // We have a new default method that's not masked by any other method.
7410 DCHECK(interface_method->IsDefault());
7411 if (have_default) {
7412 SetState(State::kDefaultConflict);
7413 } else {
7414 SetMainMethod(interface_method);
7415 SetState(State::kDefault);
7416 }
7417 }
7418
7419 // Determine if the given `iftable` contains in the given range a subinterface of `iface`
7420 // that declares a method with the same name and signature as 'interface_method'.
7421 //
7422 // Arguments
7423 // - iftable: The iftable we are searching for an overriding method.
7424 // - begin: The start of the range to search.
7425 // - end: The end of the range to search.
7426 // - iface: The interface we are checking to see if anything overrides.
7427 // - interface_method:
7428 // The interface method providing a name and signature we're searching for.
7429 //
7430 // Returns whether an overriding method was found in any subinterface of `iface`.
7431 static bool ContainsOverridingMethodOf(ObjPtr<mirror::IfTable> iftable,
7432 size_t begin,
7433 size_t end,
7434 ObjPtr<mirror::Class> iface,
7435 ArtMethod* interface_method)
7436 REQUIRES_SHARED(Locks::mutator_lock_) {
7437 for (size_t i = begin; i != end; ++i) {
7438 ObjPtr<mirror::Class> current_iface = iftable->GetInterface(i);
7439 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(kPointerSize)) {
7440 if (MethodSignatureEquals(&current_method, interface_method)) {
7441 // Check if the i'th interface is a subtype of this one.
7442 if (current_iface->Implements(iface)) {
7443 return true;
7444 }
7445 break;
7446 }
7447 }
7448 }
7449 return false;
7450 }
7451
7452 // Determine if the given `iftable` contains in the given range a subinterface of `iface`
7453 // that declares a method implemented by 'target'. This is an optimized version of
7454 // `ContainsOverridingMethodOf()` that searches implementation method arrays instead
7455 // of comparing signatures for declared interface methods.
7456 //
7457 // Arguments
7458 // - iftable: The iftable we are searching for an overriding method.
7459 // - begin: The start of the range to search.
7460 // - end: The end of the range to search.
7461 // - iface: The interface we are checking to see if anything overrides.
7462 // - target: The implementation method we're searching for.
7463 // Note that the new `iftable` is filled with vtable indexes for new interfaces,
7464 // so this needs to be the vtable index if we're searching that range.
7465 //
7466 // Returns whether the `target` was found in a method array for any subinterface of `iface`.
7467 template <typename TargetType>
7468 static bool ContainsImplementingMethod(ObjPtr<mirror::IfTable> iftable,
7469 size_t begin,
7470 size_t end,
7471 ObjPtr<mirror::Class> iface,
7472 TargetType target)
7473 REQUIRES_SHARED(Locks::mutator_lock_) {
7474 for (size_t i = begin; i != end; ++i) {
7475 if (MethodArrayContains(iftable->GetMethodArrayOrNull(i), target).first &&
7476 iftable->GetInterface(i)->Implements(iface)) {
7477 return true;
7478 }
7479 }
7480 return false;
7481 }
7482
7483 template <typename TargetType>
7484 static std::pair<bool, size_t> MethodArrayContains(ObjPtr<mirror::PointerArray> method_array,
7485 TargetType target)
7486 REQUIRES_SHARED(Locks::mutator_lock_) {
7487 size_t num_methods = (method_array != nullptr) ? method_array->GetLength() : 0u;
7488 for (size_t j = 0; j != num_methods; ++j) {
7489 if (method_array->GetElementPtrSize<TargetType, kPointerSize>(j) == target) {
7490 return {true, j};
7491 }
7492 }
7493 return {false, 0};
7494 }
7495
7496 ArtMethod* main_method_;
7497 uint32_t method_index_;
7498 State state_;
7499 };
7500
7501 class CopiedMethodRecordEmptyFn {
7502 public:
7503 void MakeEmpty(CopiedMethodRecord& item) const {
7504 item = CopiedMethodRecord();
7505 }
7506 bool IsEmpty(const CopiedMethodRecord& item) const {
7507 return item.GetMainMethod() == nullptr;
7508 }
7509 };
7510
7511 class CopiedMethodRecordHash {
7512 public:
7513 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7514 size_t operator()(ArtMethod* method) const NO_THREAD_SAFETY_ANALYSIS {
7515 DCHECK(method != nullptr);
7516 return ComputeMethodHash(method);
7517 }
7518
7519 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7520 size_t operator()(const CopiedMethodRecord& record) const NO_THREAD_SAFETY_ANALYSIS {
7521 return (*this)(record.GetMainMethod());
7522 }
7523 };
7524
7525 class CopiedMethodRecordEqual {
7526 public:
7527 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7528 bool operator()(const CopiedMethodRecord& lhs_record,
7529 ArtMethod* rhs) const NO_THREAD_SAFETY_ANALYSIS {
7530 ArtMethod* lhs = lhs_record.GetMainMethod();
7531 DCHECK(lhs != nullptr);
7532 DCHECK(rhs != nullptr);
7533 return MethodSignatureEquals(lhs, rhs);
7534 }
7535
7536 // NO_THREAD_SAFETY_ANALYSIS: This is called from unannotated `HashSet<>` functions.
7537 bool operator()(const CopiedMethodRecord& lhs_record,
7538 const CopiedMethodRecord& rhs_record) const NO_THREAD_SAFETY_ANALYSIS {
7539 return (*this)(lhs_record, rhs_record.GetMainMethod());
7540 }
7541 };
7542
7543 using CopiedMethodRecordSet = ScopedArenaHashSet<CopiedMethodRecord,
7544 CopiedMethodRecordEmptyFn,
7545 CopiedMethodRecordHash,
7546 CopiedMethodRecordEqual>;
7547
Vladimir Markob91402f2021-12-21 15:55:06 +00007548 static constexpr size_t kMethodAlignment = ArtMethod::Alignment(kPointerSize);
7549 static constexpr size_t kMethodSize = ArtMethod::Size(kPointerSize);
7550
Vladimir Marko921094a2017-01-12 18:37:06 +00007551 ClassLinker* class_linker_;
7552 Handle<mirror::Class> klass_;
Vladimir Marko921094a2017-01-12 18:37:06 +00007553 Thread* const self_;
Vladimir Marko78f62d82022-01-10 16:25:19 +00007554 Runtime* const runtime_;
Vladimir Marko921094a2017-01-12 18:37:06 +00007555
7556 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7557 // the virtual methods array.
7558 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7559 // during cross compilation.
7560 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7561 ArenaStack stack_;
7562 ScopedArenaAllocator allocator_;
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 Marko19366b82022-01-18 10:41:28 +00007721void ClassLinker::LinkMethodsHelper<kPointerSize>::FinalizeIfTable(
7722 ObjPtr<mirror::IfTable> iftable,
7723 ObjPtr<mirror::PointerArray> vtable,
7724 bool* out_new_conflict,
7725 ArtMethod** out_imt) {
7726 ObjPtr<mirror::IfTable> super_iftable = klass_->GetSuperClass()->GetIfTable();
7727 size_t ifcount = iftable->Count();
7728 size_t super_ifcount = super_iftable->Count();
Vladimir Marko921094a2017-01-12 18:37:06 +00007729
Vladimir Marko19366b82022-01-18 10:41:28 +00007730 ArtMethod* const unimplemented_method = runtime_->GetImtUnimplementedMethod();
7731 ArtMethod* const imt_conflict_method = runtime_->GetImtConflictMethod();
Vladimir Marko921094a2017-01-12 18:37:06 +00007732
Vladimir Marko19366b82022-01-18 10:41:28 +00007733 // For interfaces inherited from superclass, the new method arrays are empty,
7734 // so use vtable indexes from implementation methods from the superclass method array.
7735 for (size_t i = 0; i != super_ifcount; ++i) {
7736 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
7737 if (method_array == nullptr) {
7738 continue;
7739 }
7740 size_t num_methods = method_array->GetLength();
7741 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
7742 ObjPtr<mirror::PointerArray> super_method_array = super_iftable->GetMethodArrayOrNull(i);
7743 for (size_t j = 0; j != num_methods; ++j) {
7744 ArtMethod* super_implementation =
7745 super_method_array->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7746 size_t vtable_index = super_implementation->GetMethodIndex();
7747 ArtMethod* implementation =
7748 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(vtable_index);
7749 method_array->SetElementPtrSize(j, implementation, kPointerSize);
7750 // Place method in imt if entry is empty, place conflict otherwise.
7751 ArtMethod** imt_ptr = &out_imt[iface->GetVirtualMethod(j, kPointerSize)->GetImtIndex()];
7752 class_linker_->SetIMTRef(unimplemented_method,
7753 imt_conflict_method,
7754 implementation,
7755 /*out*/out_new_conflict,
7756 /*out*/imt_ptr);
Vladimir Marko921094a2017-01-12 18:37:06 +00007757 }
7758 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007759
Vladimir Marko19366b82022-01-18 10:41:28 +00007760 // New interface method arrays contain vtable indexes. Translate them to methods.
7761 for (size_t i = super_ifcount; i != ifcount; ++i) {
7762 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
7763 if (method_array == nullptr) {
7764 continue;
Vladimir Marko921094a2017-01-12 18:37:06 +00007765 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007766 size_t num_methods = method_array->GetLength();
7767 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
7768 for (size_t j = 0; j != num_methods; ++j) {
7769 size_t vtable_index = method_array->GetElementPtrSize<size_t, kPointerSize>(j);
7770 ArtMethod* implementation =
7771 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(vtable_index);
7772 method_array->SetElementPtrSize(j, implementation, kPointerSize);
7773 // Place method in imt if entry is empty, place conflict otherwise.
7774 ArtMethod** imt_ptr = &out_imt[iface->GetVirtualMethod(j, kPointerSize)->GetImtIndex()];
7775 class_linker_->SetIMTRef(unimplemented_method,
7776 imt_conflict_method,
7777 implementation,
7778 /*out*/out_new_conflict,
7779 /*out*/imt_ptr);
Vladimir Marko921094a2017-01-12 18:37:06 +00007780 }
7781 }
7782}
7783
Vladimir Marko19366b82022-01-18 10:41:28 +00007784NO_INLINE
7785static void ThrowIllegalAccessErrorForImplementingMethod(ObjPtr<mirror::Class> klass,
7786 ArtMethod* vtable_method,
7787 ArtMethod* interface_method)
7788 REQUIRES_SHARED(Locks::mutator_lock_) {
7789 DCHECK(!vtable_method->IsAbstract());
7790 DCHECK(!vtable_method->IsPublic());
7791 ThrowIllegalAccessError(
7792 klass,
7793 "Method '%s' implementing interface method '%s' is not public",
7794 vtable_method->PrettyMethod().c_str(),
7795 interface_method->PrettyMethod().c_str());
Vladimir Marko921094a2017-01-12 18:37:06 +00007796}
7797
Vladimir Markob91402f2021-12-21 15:55:06 +00007798template <PointerSize kPointerSize>
Vladimir Markobed84ef2022-01-21 13:57:14 +00007799size_t ClassLinker::LinkMethodsHelper<kPointerSize>::AssignVTableIndexes(
Vladimir Marko19366b82022-01-18 10:41:28 +00007800 ObjPtr<mirror::Class> klass,
7801 ObjPtr<mirror::Class> super_class,
7802 size_t num_virtual_methods,
7803 ObjPtr<mirror::IfTable> iftable) {
Vladimir Marko8670e042021-12-21 17:55:48 +00007804 DCHECK(!klass->IsInterface());
7805 DCHECK(klass->HasSuperClass());
7806 DCHECK(klass->GetSuperClass() == super_class);
Vladimir Marko8670e042021-12-21 17:55:48 +00007807
7808 // There should be no thread suspension unless we want to throw an exception.
Vladimir Marko7ddae992022-01-18 14:27:20 +00007809 // (We are using `ObjPtr<>` and raw vtable pointers that are invalidated by thread suspension.)
Vladimir Marko8670e042021-12-21 17:55:48 +00007810 std::optional<ScopedAssertNoThreadSuspension> sants(__FUNCTION__);
7811
7812 // Prepare a hash table with virtual methods from the superclass.
7813 // For the unlikely cases that there are multiple methods with the same signature
7814 // but different vtable indexes, keep an array with indexes of the previous
7815 // methods with the same signature (walked as singly-linked lists).
Vladimir Marko7ddae992022-01-18 14:27:20 +00007816 uint8_t* raw_super_vtable;
7817 size_t super_vtable_length;
7818 if (super_class->ShouldHaveEmbeddedVTable()) {
7819 raw_super_vtable = reinterpret_cast<uint8_t*>(super_class.Ptr()) +
7820 mirror::Class::EmbeddedVTableOffset(kPointerSize).Uint32Value();
7821 super_vtable_length = super_class->GetEmbeddedVTableLength();
7822 } else {
7823 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTableDuringLinking();
7824 DCHECK(super_vtable != nullptr);
7825 raw_super_vtable = reinterpret_cast<uint8_t*>(super_vtable.Ptr()) +
7826 mirror::Array::DataOffset(static_cast<size_t>(kPointerSize)).Uint32Value();
7827 super_vtable_length = super_vtable->GetLength();
7828 }
7829 VTableAccessor super_vtable_accessor(raw_super_vtable, super_vtable_length);
Vladimir Marko8670e042021-12-21 17:55:48 +00007830 static constexpr double kMinLoadFactor = 0.3;
7831 static constexpr double kMaxLoadFactor = 0.5;
Vladimir Marko19366b82022-01-18 10:41:28 +00007832 static constexpr size_t kMaxStackBuferSize = 256;
7833 const size_t super_vtable_buffer_size = super_vtable_length * 3;
7834 const size_t declared_virtuals_buffer_size = num_virtual_methods * 3;
7835 const size_t total_buffer_size = super_vtable_buffer_size + declared_virtuals_buffer_size;
7836 uint32_t* super_vtable_buffer_ptr = (total_buffer_size <= kMaxStackBuferSize)
7837 ? reinterpret_cast<uint32_t*>(alloca(total_buffer_size * sizeof(uint32_t)))
7838 : allocator_.AllocArray<uint32_t>(total_buffer_size);
7839 uint32_t* declared_virtuals_buffer_ptr = super_vtable_buffer_ptr + super_vtable_buffer_size;
Vladimir Marko7ddae992022-01-18 14:27:20 +00007840 VTableSignatureSet super_vtable_signatures(
Vladimir Marko8670e042021-12-21 17:55:48 +00007841 kMinLoadFactor,
7842 kMaxLoadFactor,
Vladimir Marko7ddae992022-01-18 14:27:20 +00007843 VTableSignatureHash(super_vtable_accessor),
7844 VTableSignatureEqual(super_vtable_accessor),
Vladimir Marko19366b82022-01-18 10:41:28 +00007845 super_vtable_buffer_ptr,
7846 super_vtable_buffer_size,
Vladimir Marko8670e042021-12-21 17:55:48 +00007847 allocator_.Adapter());
Vladimir Markobed84ef2022-01-21 13:57:14 +00007848 ArrayRef<uint32_t> same_signature_vtable_lists;
Vladimir Marko8670e042021-12-21 17:55:48 +00007849 // Insert the first `mirror::Object::kVTableLength` indexes with pre-calculated hashes.
7850 DCHECK_GE(super_vtable_length, mirror::Object::kVTableLength);
7851 for (uint32_t i = 0; i != mirror::Object::kVTableLength; ++i) {
7852 size_t hash = class_linker_->object_virtual_method_hashes_[i];
Vladimir Marko163ebe22022-01-07 12:35:36 +00007853 // There are no duplicate signatures in `java.lang.Object`, so use `HashSet<>::PutWithHash()`.
7854 // This avoids equality comparison for the three `java.lang.Object.wait()` overloads.
7855 super_vtable_signatures.PutWithHash(i, hash);
Vladimir Marko8670e042021-12-21 17:55:48 +00007856 }
7857 // Insert the remaining indexes, check for duplicate signatures.
7858 if (super_vtable_length > mirror::Object::kVTableLength) {
7859 for (size_t i = mirror::Object::kVTableLength; i < super_vtable_length; ++i) {
7860 // Use `super_vtable_accessor` for getting the method for hash calculation.
7861 // Letting `HashSet<>::insert()` use the internal accessor copy in the hash
7862 // function prevents the compiler from optimizing this properly because the
7863 // compiler cannot prove that the accessor copy is immutable.
7864 size_t hash = ComputeMethodHash(super_vtable_accessor.GetVTableEntry(i));
7865 auto [it, inserted] = super_vtable_signatures.InsertWithHash(i, hash);
7866 if (UNLIKELY(!inserted)) {
Vladimir Markobed84ef2022-01-21 13:57:14 +00007867 if (same_signature_vtable_lists.empty()) {
7868 same_signature_vtable_lists = ArrayRef<uint32_t>(
7869 allocator_.AllocArray<uint32_t>(super_vtable_length), super_vtable_length);
7870 std::fill_n(same_signature_vtable_lists.data(), super_vtable_length, dex::kDexNoIndex);
Vladimir Marko8670e042021-12-21 17:55:48 +00007871 }
7872 DCHECK_LT(*it, i);
Vladimir Markobed84ef2022-01-21 13:57:14 +00007873 same_signature_vtable_lists[i] = *it;
Vladimir Marko8670e042021-12-21 17:55:48 +00007874 *it = i;
7875 }
7876 }
7877 }
7878
7879 // For each declared virtual method, look for a superclass virtual method
7880 // to override and assign a new vtable index if no method was overridden.
Vladimir Marko19366b82022-01-18 10:41:28 +00007881 DeclaredVirtualSignatureSet declared_virtual_signatures(
7882 kMinLoadFactor,
7883 kMaxLoadFactor,
7884 DeclaredVirtualSignatureHash(klass),
7885 DeclaredVirtualSignatureEqual(klass),
7886 declared_virtuals_buffer_ptr,
7887 declared_virtuals_buffer_size,
7888 allocator_.Adapter());
Vladimir Marko8670e042021-12-21 17:55:48 +00007889 const bool is_proxy_class = klass->IsProxyClass();
7890 size_t vtable_length = super_vtable_length;
Vladimir Marko19366b82022-01-18 10:41:28 +00007891 for (size_t i = 0; i != num_virtual_methods; ++i) {
Vladimir Marko8670e042021-12-21 17:55:48 +00007892 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
Vladimir Marko19366b82022-01-18 10:41:28 +00007893 DCHECK(!virtual_method->IsStatic()) << virtual_method->PrettyMethod();
Vladimir Marko8670e042021-12-21 17:55:48 +00007894 ArtMethod* signature_method = UNLIKELY(is_proxy_class)
7895 ? virtual_method->GetInterfaceMethodForProxyUnchecked(kPointerSize)
7896 : virtual_method;
7897 size_t hash = ComputeMethodHash(signature_method);
Vladimir Marko19366b82022-01-18 10:41:28 +00007898 declared_virtual_signatures.PutWithHash(i, hash);
Vladimir Marko8670e042021-12-21 17:55:48 +00007899 auto it = super_vtable_signatures.FindWithHash(signature_method, hash);
7900 if (it != super_vtable_signatures.end()) {
7901 size_t super_index = *it;
7902 DCHECK_LT(super_index, super_vtable_length);
7903 ArtMethod* super_method = super_vtable_accessor.GetVTableEntry(super_index);
7904 // Historical note: Before Android 4.1, an inaccessible package-private
7905 // superclass method would have been incorrectly overridden.
7906 bool overrides = klass->CanAccessMember(super_method->GetDeclaringClass(),
7907 super_method->GetAccessFlags());
Vladimir Markobed84ef2022-01-21 13:57:14 +00007908 if (UNLIKELY(!same_signature_vtable_lists.empty())) {
Vladimir Marko8670e042021-12-21 17:55:48 +00007909 // We override only the first accessible virtual method from superclass.
7910 // TODO: Override all methods that need to be overridden according to JLS. b/211854716
7911 size_t current_index = super_index;
Vladimir Markobed84ef2022-01-21 13:57:14 +00007912 while (same_signature_vtable_lists[current_index] != dex::kDexNoIndex) {
7913 DCHECK_LT(same_signature_vtable_lists[current_index], current_index);
7914 current_index = same_signature_vtable_lists[current_index];
Vladimir Marko8670e042021-12-21 17:55:48 +00007915 ArtMethod* current_method = super_vtable_accessor.GetVTableEntry(current_index);
7916 if (klass->CanAccessMember(current_method->GetDeclaringClass(),
7917 current_method->GetAccessFlags())) {
7918 overrides = true;
7919 super_index = current_index;
7920 super_method = current_method;
7921 }
7922 }
7923 }
7924 if (overrides) {
7925 if (super_method->IsFinal()) {
7926 sants.reset();
7927 ThrowLinkageError(klass, "Method %s overrides final method in class %s",
7928 virtual_method->PrettyMethod().c_str(),
7929 super_method->GetDeclaringClassDescriptor());
7930 return 0u;
7931 }
7932 virtual_method->SetMethodIndex(super_index);
7933 continue;
7934 }
7935 }
7936 // The method does not override any method from superclass, so it needs a new vtable index.
7937 virtual_method->SetMethodIndex(vtable_length);
7938 ++vtable_length;
7939 }
Vladimir Marko19366b82022-01-18 10:41:28 +00007940
7941 // Assign vtable indexes for interface methods in new interfaces and store them
7942 // in implementation method arrays. These shall be replaced by actual method
7943 // pointers later. We do not need to do this for superclass interfaces as we can
7944 // get these vtable indexes from implementation methods in superclass iftable.
7945 // Record data for copied methods which shall be referenced by the vtable.
7946 const size_t ifcount = iftable->Count();
7947 ObjPtr<mirror::IfTable> super_iftable = super_class->GetIfTable();
7948 const size_t super_ifcount = super_iftable->Count();
7949 for (size_t i = ifcount; i != super_ifcount; ) {
7950 --i;
7951 DCHECK_LT(i, ifcount);
7952 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
7953 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArrayOrNull(i);
7954 size_t num_methods = (method_array != nullptr) ? method_array->GetLength() : 0u;
7955 for (size_t j = 0; j != num_methods; ++j) {
7956 ArtMethod* interface_method = iface->GetVirtualMethod(j, kPointerSize);
7957 size_t hash = ComputeMethodHash(interface_method);
7958 ArtMethod* vtable_method = nullptr;
7959 bool found = false;
7960 auto it1 = declared_virtual_signatures.FindWithHash(interface_method, hash);
7961 if (it1 != declared_virtual_signatures.end()) {
7962 vtable_method = klass->GetVirtualMethodDuringLinking(*it1, kPointerSize);
7963 found = true;
7964 } else {
7965 auto it2 = super_vtable_signatures.FindWithHash(interface_method, hash);
7966 if (it2 != super_vtable_signatures.end()) {
7967 // FIXME: If there are multiple vtable methods with the same signature, the one
7968 // with the highest vtable index is not nessarily the one in most-derived class.
7969 // However, we're preserving old behavior for now. b/211854716
7970 vtable_method = super_vtable_accessor.GetVTableEntry(*it2);
7971 found = true;
7972 }
7973 }
7974 uint32_t vtable_index = vtable_length;
7975 if (found) {
7976 DCHECK(vtable_method != nullptr);
7977 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
7978 sants.reset();
7979 ThrowIllegalAccessErrorForImplementingMethod(klass, vtable_method, interface_method);
7980 return 0u;
7981 }
7982 vtable_index = vtable_method->GetMethodIndexDuringLinking();
7983 if (!vtable_method->IsOverridableByDefaultMethod()) {
7984 method_array->SetElementPtrSize(j, vtable_index, kPointerSize);
7985 continue;
7986 }
7987 }
7988
7989 auto [it, inserted] = copied_method_records_.InsertWithHash(
7990 CopiedMethodRecord(interface_method, vtable_index), hash);
7991 if (found) {
7992 DCHECK_EQ(vtable_index, it->GetMethodIndex());
7993 } else if (inserted) {
7994 DCHECK_EQ(vtable_index, it->GetMethodIndex());
7995 DCHECK_EQ(vtable_index, vtable_length);
7996 ++vtable_length;
7997 } else {
7998 vtable_index = it->GetMethodIndex();
7999 }
8000 method_array->SetElementPtrSize(j, it->GetMethodIndex(), kPointerSize);
8001 if (inserted) {
8002 it->SetState(interface_method->IsAbstract() ? CopiedMethodRecord::State::kAbstractSingle
8003 : CopiedMethodRecord::State::kDefaultSingle);
8004 } else {
8005 it->UpdateState(iface, interface_method, vtable_index, iftable, ifcount, i);
8006 }
8007 }
8008 }
8009 // Finalize copied method records and check if we can reuse some methods from superclass vtable.
8010 size_t num_new_copied_methods = copied_method_records_.size();
8011 for (CopiedMethodRecord& record : copied_method_records_) {
8012 uint32_t vtable_index = record.GetMethodIndex();
8013 if (vtable_index < super_vtable_length) {
8014 ArtMethod* super_method = super_vtable_accessor.GetVTableEntry(record.GetMethodIndex());
8015 DCHECK(super_method->IsOverridableByDefaultMethod());
8016 record.FinalizeState(
8017 super_method, vtable_index, iftable, ifcount, super_iftable, super_ifcount);
8018 if (record.GetState() == CopiedMethodRecord::State::kUseSuperMethod) {
8019 --num_new_copied_methods;
8020 }
8021 }
8022 }
8023 num_new_copied_methods_ = num_new_copied_methods;
8024
Vladimir Marko8670e042021-12-21 17:55:48 +00008025 if (UNLIKELY(!IsUint<16>(vtable_length))) {
8026 sants.reset();
8027 ThrowClassFormatError(klass, "Too many methods defined on class: %zd", vtable_length);
8028 return 0u;
8029 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008030
Vladimir Marko8670e042021-12-21 17:55:48 +00008031 return vtable_length;
8032}
8033
8034template <PointerSize kPointerSize>
Vladimir Marko19366b82022-01-18 10:41:28 +00008035bool ClassLinker::LinkMethodsHelper<kPointerSize>::FindCopiedMethodsForInterface(
8036 ObjPtr<mirror::Class> klass,
8037 size_t num_virtual_methods,
8038 ObjPtr<mirror::IfTable> iftable) {
8039 DCHECK(klass->IsInterface());
8040 DCHECK(klass->HasSuperClass());
8041 DCHECK(klass->GetSuperClass()->IsObjectClass());
8042 DCHECK_EQ(klass->GetSuperClass()->GetIfTableCount(), 0);
8043
8044 // There should be no thread suspension unless we want to throw an exception.
8045 // (We are using `ObjPtr<>`s that are invalidated by thread suspension.)
8046 std::optional<ScopedAssertNoThreadSuspension> sants(__FUNCTION__);
8047
8048 // Prepare a `HashSet<>` with the declared virtual methods. These mask any methods
8049 // from superinterfaces, so we can filter out matching superinterface methods.
8050 static constexpr double kMinLoadFactor = 0.3;
8051 static constexpr double kMaxLoadFactor = 0.5;
8052 static constexpr size_t kMaxStackBuferSize = 256;
8053 const size_t declared_virtuals_buffer_size = num_virtual_methods * 3;
8054 uint32_t* declared_virtuals_buffer_ptr = (declared_virtuals_buffer_size <= kMaxStackBuferSize)
8055 ? reinterpret_cast<uint32_t*>(alloca(declared_virtuals_buffer_size * sizeof(uint32_t)))
8056 : allocator_.AllocArray<uint32_t>(declared_virtuals_buffer_size);
8057 DeclaredVirtualSignatureSet declared_virtual_signatures(
8058 kMinLoadFactor,
8059 kMaxLoadFactor,
8060 DeclaredVirtualSignatureHash(klass),
8061 DeclaredVirtualSignatureEqual(klass),
8062 declared_virtuals_buffer_ptr,
8063 declared_virtuals_buffer_size,
8064 allocator_.Adapter());
8065 for (size_t i = 0; i != num_virtual_methods; ++i) {
8066 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
8067 DCHECK(!virtual_method->IsStatic()) << virtual_method->PrettyMethod();
8068 size_t hash = ComputeMethodHash(virtual_method);
8069 declared_virtual_signatures.PutWithHash(i, hash);
8070 }
8071
8072 // We do not create miranda methods for interface classes, so we do not need to track
8073 // non-default (abstract) interface methods. The downside is that we cannot use the
8074 // optimized code paths with `CopiedMethodRecord::State::kDefaultSingle` and since
8075 // we do not fill method arrays for interfaces, the method search actually has to
8076 // compare signatures instead of searching for the implementing method.
8077 const size_t ifcount = iftable->Count();
8078 size_t new_method_index = num_virtual_methods;
8079 for (size_t i = ifcount; i != 0u; ) {
8080 --i;
8081 DCHECK_LT(i, ifcount);
8082 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
8083 if (!iface->HasDefaultMethods()) {
8084 continue; // No default methods to process.
8085 }
8086 size_t num_methods = iface->NumDeclaredVirtualMethods();
8087 for (size_t j = 0; j != num_methods; ++j) {
8088 ArtMethod* interface_method = iface->GetVirtualMethod(j, kPointerSize);
8089 if (!interface_method->IsDefault()) {
8090 continue; // Do not process this non-default method.
8091 }
8092 size_t hash = ComputeMethodHash(interface_method);
8093 auto it1 = declared_virtual_signatures.FindWithHash(interface_method, hash);
8094 if (it1 != declared_virtual_signatures.end()) {
8095 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(*it1, kPointerSize);
8096 if (!virtual_method->IsAbstract() && !virtual_method->IsPublic()) {
8097 sants.reset();
8098 ThrowIllegalAccessErrorForImplementingMethod(klass, virtual_method, interface_method);
8099 return false;
8100 }
8101 continue; // This default method is masked by a method declared in this interface.
8102 }
8103
8104 CopiedMethodRecord new_record(interface_method, new_method_index);
8105 auto it = copied_method_records_.FindWithHash(new_record, hash);
8106 if (it == copied_method_records_.end()) {
8107 // Pretend that there is another default method and try to update the state.
8108 // If the `interface_method` is not masked, the state shall change to
8109 // `kDefaultConflict`; if it is masked, the state remains `kDefault`.
8110 new_record.SetState(CopiedMethodRecord::State::kDefault);
8111 new_record.UpdateStateForInterface(iface, interface_method, iftable, ifcount, i);
8112 if (new_record.GetState() == CopiedMethodRecord::State::kDefaultConflict) {
8113 // Insert the new record with the state `kDefault`.
8114 new_record.SetState(CopiedMethodRecord::State::kDefault);
8115 copied_method_records_.PutWithHash(new_record, hash);
8116 DCHECK_EQ(new_method_index, new_record.GetMethodIndex());
8117 ++new_method_index;
8118 }
8119 } else {
8120 it->UpdateStateForInterface(iface, interface_method, iftable, ifcount, i);
8121 }
8122 }
8123 }
8124
8125 // Prune records without conflict. (Method indexes are updated in `ReallocMethods()`.)
8126 // We do not copy normal default methods to subinterfaces, instead we find the
8127 // default method with `Class::FindVirtualMethodForInterfaceSuper()` when needed.
8128 size_t num_new_copied_methods = copied_method_records_.size();
8129 for (CopiedMethodRecord& record : copied_method_records_) {
8130 if (record.GetState() != CopiedMethodRecord::State::kDefaultConflict) {
8131 DCHECK(record.GetState() == CopiedMethodRecord::State::kDefault);
8132 record.SetState(CopiedMethodRecord::State::kUseSuperMethod);
8133 --num_new_copied_methods;
8134 }
8135 }
8136 num_new_copied_methods_ = num_new_copied_methods;
8137
8138 return true;
8139}
8140
8141
8142template <PointerSize kPointerSize>
Vladimir Markob91402f2021-12-21 15:55:06 +00008143FLATTEN
Vladimir Marko78f62d82022-01-10 16:25:19 +00008144bool ClassLinker::LinkMethodsHelper<kPointerSize>::LinkMethods(
Vladimir Markobc893672021-11-10 15:25:46 +00008145 Thread* self,
Vladimir Marko78f62d82022-01-10 16:25:19 +00008146 Handle<mirror::Class> klass,
8147 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
8148 bool* out_new_conflict,
8149 ArtMethod** out_imt) {
Vladimir Markobc893672021-11-10 15:25:46 +00008150 const size_t num_virtual_methods = klass->NumVirtualMethods();
8151 if (klass->IsInterface()) {
8152 // No vtable.
8153 if (!IsUint<16>(num_virtual_methods)) {
8154 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
8155 return false;
8156 }
8157 bool has_defaults = false;
8158 // Assign each method an IMT index and set the default flag.
8159 for (size_t i = 0; i < num_virtual_methods; ++i) {
Vladimir Markob91402f2021-12-21 15:55:06 +00008160 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
Vladimir Markobc893672021-11-10 15:25:46 +00008161 m->SetMethodIndex(i);
8162 if (!m->IsAbstract()) {
8163 // If the dex file does not support default methods, throw ClassFormatError.
8164 // This check is necessary to protect from odd cases, such as native default
8165 // methods, that the dex file verifier permits for old dex file versions. b/157170505
8166 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
8167 // currently running CTS tests for default methods with dex file version 035 which
8168 // does not support default methods. So, we limit this to native methods. b/157718952
8169 if (m->IsNative()) {
8170 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
8171 ThrowClassFormatError(klass.Get(),
8172 "Dex file does not support default method '%s'",
8173 m->PrettyMethod().c_str());
8174 return false;
8175 }
Vladimir Markofd0aec42022-01-27 14:27:24 +00008176 if (!m->IsPublic()) {
8177 // The verifier should have caught the non-public method for dex version 37.
8178 // Just warn and skip it since this is from before default-methods so we don't
8179 // really need to care that it has code.
8180 LOG(WARNING) << "Default interface method " << m->PrettyMethod() << " is not public! "
8181 << "This will be a fatal error in subsequent versions of android. "
8182 << "Continuing anyway.";
8183 }
Vladimir Markobc893672021-11-10 15:25:46 +00008184 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
8185 has_defaults = true;
8186 }
8187 }
8188 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
8189 // during initialization. This is a performance optimization. We could simply traverse the
8190 // virtual_methods_ array again during initialization.
8191 if (has_defaults) {
8192 klass->SetHasDefaultMethods();
8193 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008194 ObjPtr<mirror::IfTable> iftable = SetupInterfaceLookupTable(
8195 self, klass, &allocator_, NonProxyInterfacesAccessor(class_linker_, klass));
8196 if (UNLIKELY(iftable == nullptr)) {
8197 self->AssertPendingException();
8198 return false;
8199 }
Vladimir Marko19366b82022-01-18 10:41:28 +00008200 size_t ifcount = iftable->Count();
8201 bool have_super_with_defaults = false;
8202 for (size_t i = 0; i != ifcount; ++i) {
8203 if (iftable->GetInterface(i)->HasDefaultMethods()) {
8204 have_super_with_defaults = true;
8205 break;
8206 }
8207 }
8208 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8209 if (have_super_with_defaults) {
8210 if (!FindCopiedMethodsForInterface(klass.Get(), num_virtual_methods, iftable)) {
8211 self->AssertPendingException();
8212 return false;
8213 }
8214 if (num_new_copied_methods_ != 0u) {
8215 // Re-check the number of methods.
8216 size_t final_num_virtual_methods = num_virtual_methods + num_new_copied_methods_;
8217 if (!IsUint<16>(final_num_virtual_methods)) {
8218 ThrowClassFormatError(
8219 klass.Get(), "Too many methods on interface: %zu", final_num_virtual_methods);
8220 return false;
8221 }
8222 ReallocMethods(klass.Get());
8223 }
8224 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008225 klass->SetIfTable(iftable);
Vladimir Marko19366b82022-01-18 10:41:28 +00008226 if (kIsDebugBuild) {
8227 // May cause thread suspension, so do this after we're done with `ObjPtr<> iftable`.
8228 ClobberOldMethods(old_methods, klass->GetMethodsPtr());
8229 }
8230 return true;
Vladimir Markob91402f2021-12-21 15:55:06 +00008231 } else if (LIKELY(klass->HasSuperClass())) {
Vladimir Marko78f62d82022-01-10 16:25:19 +00008232 // Copy IMT from superclass. It shall be updated later if needed.
8233 class_linker_->FillImtFromSuperClass(klass,
8234 runtime_->GetImtUnimplementedMethod(),
8235 runtime_->GetImtConflictMethod(),
8236 out_new_conflict,
8237 out_imt);
8238
8239 // We set up the interface lookup table now because we need it to determine if we need
8240 // to update any vtable entries with new default method implementations.
Vladimir Markobc893672021-11-10 15:25:46 +00008241 StackHandleScope<3> hs(self);
Vladimir Marko78f62d82022-01-10 16:25:19 +00008242 Handle<mirror::IfTable> iftable = hs.NewHandle(UNLIKELY(klass->IsProxyClass())
8243 ? SetupInterfaceLookupTable(self, klass, &allocator_, ProxyInterfacesAccessor(interfaces))
8244 : SetupInterfaceLookupTable(
8245 self, klass, &allocator_, NonProxyInterfacesAccessor(class_linker_, klass)));
8246 if (UNLIKELY(iftable == nullptr)) {
8247 self->AssertPendingException();
8248 return false;
8249 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008250
8251 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
Vladimir Markobc893672021-11-10 15:25:46 +00008252 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Vladimir Marko8670e042021-12-21 17:55:48 +00008253
8254 // If there are no new virtual methods and no new interfaces, we can simply reuse
8255 // the vtable from superclass. We may need to make a copy if it's embedded.
Vladimir Markobed84ef2022-01-21 13:57:14 +00008256 if (num_virtual_methods == 0 &&
8257 static_cast<size_t>(super_class->GetIfTableCount()) == iftable->Count()) {
Vladimir Marko8670e042021-12-21 17:55:48 +00008258 if (super_class->ShouldHaveEmbeddedVTable()) {
8259 ObjPtr<mirror::PointerArray> vtable =
8260 class_linker_->AllocPointerArray(self, super_vtable_length);
8261 if (UNLIKELY(vtable == nullptr)) {
8262 self->AssertPendingOOMException();
Vladimir Markobc893672021-11-10 15:25:46 +00008263 return false;
8264 }
Vladimir Marko8670e042021-12-21 17:55:48 +00008265 for (size_t i = 0; i < super_vtable_length; i++) {
8266 vtable->SetElementPtrSize(
8267 i, super_class->GetEmbeddedVTableEntry(i, kPointerSize), kPointerSize);
8268 }
8269 klass->SetVTable(vtable);
8270 } else {
8271 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
8272 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
8273 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
8274 klass->SetVTable(super_vtable);
8275 }
Vladimir Marko78f62d82022-01-10 16:25:19 +00008276 // The interface table from superclass has also been reused by `SetupInterfaceLookupTable()`.
8277 DCHECK(iftable.Get() == super_class->GetIfTable()) << klass->PrettyDescriptor();
Vladimir Markobed84ef2022-01-21 13:57:14 +00008278 klass->SetIfTable(iftable.Get());
Vladimir Marko8670e042021-12-21 17:55:48 +00008279 return true;
8280 }
8281
Vladimir Markobed84ef2022-01-21 13:57:14 +00008282 // Allocate method arrays, so that we can link interface methods without thread suspension,
8283 // otherwise GC could miss visiting newly allocated copied methods.
8284 // TODO: Do not allocate copied methods during linking, store only records about what
8285 // we need to allocate and allocate it at the end. Start with superclass iftable and
8286 // perform copy-on-write when needed to facilitate maximum memory sharing.
8287 if (!class_linker_->AllocateIfTableMethodArrays(self, klass, iftable)) {
8288 return false;
8289 }
8290
Vladimir Marko7ddae992022-01-18 14:27:20 +00008291 size_t final_vtable_size =
Vladimir Marko19366b82022-01-18 10:41:28 +00008292 AssignVTableIndexes(klass.Get(), super_class.Get(), num_virtual_methods, iftable.Get());
Vladimir Marko8670e042021-12-21 17:55:48 +00008293 if (final_vtable_size == 0u) {
8294 self->AssertPendingException();
8295 return false;
8296 }
8297 DCHECK(IsUint<16>(final_vtable_size));
8298
8299 // Allocate the new vtable.
8300 Handle<mirror::PointerArray> vtable =
8301 hs.NewHandle(class_linker_->AllocPointerArray(self, final_vtable_size));
8302 if (UNLIKELY(vtable == nullptr)) {
8303 self->AssertPendingOOMException();
8304 return false;
8305 }
8306
Vladimir Marko19366b82022-01-18 10:41:28 +00008307 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8308 if (num_new_copied_methods_ != 0u) {
8309 ReallocMethods(klass.Get());
8310 }
8311
Vladimir Marko8670e042021-12-21 17:55:48 +00008312 // Store new virtual methods in the new vtable.
8313 for (ArtMethod& virtual_method : klass->GetVirtualMethodsSliceUnchecked(kPointerSize)) {
8314 int32_t vtable_index = virtual_method.GetMethodIndexDuringLinking();
8315 vtable->SetElementPtrSize(vtable_index, &virtual_method, kPointerSize);
8316 }
8317
8318 // For non-overridden vtable slots, copy a method from `super_class`.
8319 for (size_t j = 0; j != super_vtable_length; ++j) {
Vladimir Marko19366b82022-01-18 10:41:28 +00008320 if (vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j) == nullptr) {
8321 ArtMethod* super_method = super_class->GetVTableEntry(j, kPointerSize);
8322 vtable->SetElementPtrSize(j, super_method, kPointerSize);
Vladimir Markobc893672021-11-10 15:25:46 +00008323 }
8324 }
Vladimir Marko8670e042021-12-21 17:55:48 +00008325
Vladimir Marko19366b82022-01-18 10:41:28 +00008326 // Update the `iftable` with finalized virtual methods.
8327 FinalizeIfTable(iftable.Get(), vtable.Get(), out_new_conflict, out_imt);
8328
Vladimir Markobc893672021-11-10 15:25:46 +00008329 klass->SetVTable(vtable.Get());
Vladimir Marko19366b82022-01-18 10:41:28 +00008330 klass->SetIfTable(iftable.Get());
8331 if (kIsDebugBuild) {
8332 CheckVTable(self, klass, kPointerSize);
8333 ClobberOldMethods(old_methods, klass->GetMethodsPtr());
8334 }
8335 return true;
Vladimir Markobc893672021-11-10 15:25:46 +00008336 } else {
Vladimir Marko78f62d82022-01-10 16:25:19 +00008337 return LinkJavaLangObjectMethods(self, klass);
Vladimir Markobc893672021-11-10 15:25:46 +00008338 }
Vladimir Markobc893672021-11-10 15:25:46 +00008339}
8340
Vladimir Markob91402f2021-12-21 15:55:06 +00008341template <PointerSize kPointerSize>
Vladimir Marko78f62d82022-01-10 16:25:19 +00008342bool ClassLinker::LinkMethodsHelper<kPointerSize>::LinkJavaLangObjectMethods(
Vladimir Markob91402f2021-12-21 15:55:06 +00008343 Thread* self,
8344 Handle<mirror::Class> klass) {
8345 DCHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(class_linker_));
8346 DCHECK_EQ(klass->NumVirtualMethods(), mirror::Object::kVTableLength);
8347 static_assert(IsUint<16>(mirror::Object::kVTableLength));
8348 ObjPtr<mirror::PointerArray> vtable =
8349 class_linker_->AllocPointerArray(self, mirror::Object::kVTableLength);
8350 if (UNLIKELY(vtable == nullptr)) {
8351 self->AssertPendingOOMException();
8352 return false;
8353 }
8354 for (size_t i = 0; i < mirror::Object::kVTableLength; ++i) {
8355 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, kPointerSize);
8356 vtable->SetElementPtrSize(i, virtual_method, kPointerSize);
8357 virtual_method->SetMethodIndex(i);
8358 }
8359 klass->SetVTable(vtable);
8360 InitializeObjectVirtualMethodHashes(
8361 klass.Get(),
8362 kPointerSize,
8363 ArrayRef<uint32_t>(class_linker_->object_virtual_method_hashes_));
Vladimir Marko78f62d82022-01-10 16:25:19 +00008364 // The interface table is already allocated but there are no interface methods to link.
8365 DCHECK(klass->GetIfTable() != nullptr);
8366 DCHECK_EQ(klass->GetIfTableCount(), 0);
Vladimir Markob91402f2021-12-21 15:55:06 +00008367 return true;
8368}
8369
Vladimir Markobc893672021-11-10 15:25:46 +00008370// Populate the class vtable and itable. Compute return type indices.
8371bool ClassLinker::LinkMethods(Thread* self,
8372 Handle<mirror::Class> klass,
8373 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
8374 bool* out_new_conflict,
8375 ArtMethod** out_imt) {
8376 self->AllowThreadSuspension();
Vladimir Markobc893672021-11-10 15:25:46 +00008377 // Link virtual methods then interface methods.
8378 Runtime* const runtime = Runtime::Current();
Vladimir Markob91402f2021-12-21 15:55:06 +00008379 if (LIKELY(GetImagePointerSize() == kRuntimePointerSize)) {
8380 LinkMethodsHelper<kRuntimePointerSize> helper(this, klass, self, runtime);
Vladimir Marko78f62d82022-01-10 16:25:19 +00008381 return helper.LinkMethods(self, klass, interfaces, out_new_conflict, out_imt);
Vladimir Markob91402f2021-12-21 15:55:06 +00008382 } else {
8383 constexpr PointerSize kOtherPointerSize =
8384 (kRuntimePointerSize == PointerSize::k64) ? PointerSize::k32 : PointerSize::k64;
8385 LinkMethodsHelper<kOtherPointerSize> helper(this, klass, self, runtime);
Vladimir Marko78f62d82022-01-10 16:25:19 +00008386 return helper.LinkMethods(self, klass, interfaces, out_new_conflict, out_imt);
Vladimir Markob91402f2021-12-21 15:55:06 +00008387 }
Vladimir Markobc893672021-11-10 15:25:46 +00008388}
8389
Vladimir Marko42bee502021-01-28 14:58:35 +00008390class ClassLinker::LinkFieldsHelper {
8391 public:
8392 static bool LinkFields(ClassLinker* class_linker,
8393 Thread* self,
8394 Handle<mirror::Class> klass,
8395 bool is_static,
8396 size_t* class_size)
8397 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008398
Vladimir Marko42bee502021-01-28 14:58:35 +00008399 private:
8400 enum class FieldTypeOrder : uint16_t;
8401 class FieldGaps;
8402
8403 struct FieldTypeOrderAndIndex {
8404 FieldTypeOrder field_type_order;
8405 uint16_t field_index;
8406 };
8407
8408 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8409
8410 template <size_t kSize>
8411 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8412 REQUIRES_SHARED(Locks::mutator_lock_);
8413};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008414
Vladimir Markoc7993d52021-01-27 15:20:56 +00008415// We use the following order of field types for assigning offsets.
8416// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008417enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008418 kReference = 0u,
8419 kLong,
8420 kDouble,
8421 kInt,
8422 kFloat,
8423 kChar,
8424 kShort,
8425 kBoolean,
8426 kByte,
8427
8428 kLast64BitType = kDouble,
8429 kLast32BitType = kFloat,
8430 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008431};
8432
Vladimir Markoc7993d52021-01-27 15:20:56 +00008433ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008434ClassLinker::LinkFieldsHelper::FieldTypeOrder
8435ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008436 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008437 case 'J':
8438 return FieldTypeOrder::kLong;
8439 case 'D':
8440 return FieldTypeOrder::kDouble;
8441 case 'I':
8442 return FieldTypeOrder::kInt;
8443 case 'F':
8444 return FieldTypeOrder::kFloat;
8445 case 'C':
8446 return FieldTypeOrder::kChar;
8447 case 'S':
8448 return FieldTypeOrder::kShort;
8449 case 'Z':
8450 return FieldTypeOrder::kBoolean;
8451 case 'B':
8452 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008453 default:
8454 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8455 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008456 }
8457}
8458
8459// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008460class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008461 public:
8462 template <uint32_t kSize>
8463 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8464 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8465 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8466 uint32_t gap_start = field_offset.Uint32Value();
8467 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8468 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8469 }
8470 return field_offset;
8471 }
8472
8473 template <uint32_t kSize>
8474 bool HasGap() const {
8475 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8476 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8477 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8478 gap4_offset_ != kNoOffset;
8479 }
8480
8481 template <uint32_t kSize>
8482 MemberOffset ReleaseGap() {
8483 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8484 uint32_t result;
8485 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8486 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8487 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8488 result = gap1_offset_;
8489 gap1_offset_ = kNoOffset;
8490 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8491 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8492 result = gap2_offset_;
8493 gap2_offset_ = kNoOffset;
8494 if (kSize < 2u) {
8495 AddGaps<1u>(result + kSize, result + 2u);
8496 }
8497 } else {
8498 DCHECK_NE(gap4_offset_, kNoOffset);
8499 result = gap4_offset_;
8500 gap4_offset_ = kNoOffset;
8501 if (kSize < 4u) {
8502 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8503 }
8504 }
8505 return MemberOffset(result);
8506 }
8507
8508 private:
8509 template <uint32_t kGapsToCheck>
8510 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8511 if ((kGapsToCheck & 1u) != 0u) {
8512 DCHECK_LT(gap_start, gap_end);
8513 DCHECK_ALIGNED(gap_end, 2u);
8514 if ((gap_start & 1u) != 0u) {
8515 DCHECK_EQ(gap1_offset_, kNoOffset);
8516 gap1_offset_ = gap_start;
8517 gap_start += 1u;
8518 if (kGapsToCheck == 1u || gap_start == gap_end) {
8519 DCHECK_EQ(gap_start, gap_end);
8520 return;
8521 }
8522 }
8523 }
8524
8525 if ((kGapsToCheck & 2u) != 0u) {
8526 DCHECK_LT(gap_start, gap_end);
8527 DCHECK_ALIGNED(gap_start, 2u);
8528 DCHECK_ALIGNED(gap_end, 4u);
8529 if ((gap_start & 2u) != 0u) {
8530 DCHECK_EQ(gap2_offset_, kNoOffset);
8531 gap2_offset_ = gap_start;
8532 gap_start += 2u;
8533 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8534 DCHECK_EQ(gap_start, gap_end);
8535 return;
8536 }
8537 }
8538 }
8539
8540 if ((kGapsToCheck & 4u) != 0u) {
8541 DCHECK_LT(gap_start, gap_end);
8542 DCHECK_ALIGNED(gap_start, 4u);
8543 DCHECK_ALIGNED(gap_end, 8u);
8544 DCHECK_EQ(gap_start + 4u, gap_end);
8545 DCHECK_EQ(gap4_offset_, kNoOffset);
8546 gap4_offset_ = gap_start;
8547 return;
8548 }
8549
8550 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8551 << " after checking " << kGapsToCheck;
8552 }
8553
8554 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8555
8556 uint32_t gap4_offset_ = kNoOffset;
8557 uint32_t gap2_offset_ = kNoOffset;
8558 uint32_t gap1_offset_ = kNoOffset;
8559};
8560
8561template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008562ALWAYS_INLINE
8563MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8564 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008565 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8566 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8567 field->SetOffset(field_offset);
8568 return MemberOffset(field_offset.Uint32Value() + kSize);
8569}
8570
Vladimir Marko42bee502021-01-28 14:58:35 +00008571bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8572 Thread* self,
8573 Handle<mirror::Class> klass,
8574 bool is_static,
8575 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008576 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008577 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008578 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8579 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008580
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008581 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008582 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008583 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008584 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8585 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008586 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008587 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008588 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008589 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008590 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008591 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008592 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008593 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008594
David Sehr709b0702016-10-13 09:12:37 -07008595 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008596
Brian Carlstromdbc05252011-09-09 01:59:59 -07008597 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008598 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008599 //
8600 // The overall sort order order is:
8601 // 1) All object reference fields, sorted alphabetically.
8602 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8603 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8604 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8605 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8606 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8607 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8608 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8609 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8610 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008611 // (References are first to increase the chance of reference visiting
8612 // being able to take a fast path using a bitmap of references at the
8613 // start of the object, see `Class::reference_instance_offsets_`.)
8614 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008615 // Once the fields are sorted in this order we will attempt to fill any gaps
8616 // that might be present in the memory layout of the structure.
8617 // Note that we shall not fill gaps between the superclass fields.
8618
8619 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008620 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008621 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008622 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8623 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8624 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8625 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008626 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008627 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008628 } else {
8629 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008630 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008631 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008632 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008633 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008634 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008635 for (size_t i = 0; i != num_fields; ++i) {
8636 ArtField* field = &fields->At(i);
8637 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008638 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8639 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008640 // Insert references to the start, other fields to the end.
8641 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008642 if (field_type_order == FieldTypeOrder::kReference) {
8643 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008644 ++num_reference_fields;
8645 } else {
8646 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008647 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008648 }
8649 }
8650 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008651
Vladimir Marko42bee502021-01-28 14:58:35 +00008652 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008653 DCHECK(std::is_sorted(
8654 sorted_fields.begin(),
8655 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008656 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8657 ArtField* lhs_field = &fields->At(lhs.field_index);
8658 ArtField* rhs_field = &fields->At(rhs.field_index);
8659 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8660 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8661 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8662 lhs.field_index < rhs.field_index);
8663 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008664 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008665 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008666 DCHECK(std::is_sorted(
8667 sorted_fields.begin() + primitive_fields_start,
8668 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008669 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8670 ArtField* lhs_field = &fields->At(lhs.field_index);
8671 ArtField* rhs_field = &fields->At(rhs.field_index);
8672 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8673 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8674 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8675 lhs.field_index > rhs.field_index);
8676 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008677 }));
8678 // Sort the primitive fields by the field type order, then field index.
8679 std::sort(sorted_fields.begin() + primitive_fields_start,
8680 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008681 [](const auto& lhs, const auto& rhs) {
8682 if (lhs.field_type_order != rhs.field_type_order) {
8683 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008684 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008685 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008686 }
8687 });
8688 // Primitive fields are now sorted by field size (descending), then type, then field index.
8689 DCHECK(std::is_sorted(
8690 sorted_fields.begin() + primitive_fields_start,
8691 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008692 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8693 ArtField* lhs_field = &fields->At(lhs.field_index);
8694 ArtField* rhs_field = &fields->At(rhs.field_index);
8695 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008696 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008697 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008698 CHECK_NE(rhs_type, Primitive::kPrimNot);
8699 if (lhs_type != rhs_type) {
8700 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8701 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8702 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8703 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008704 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008705 }
8706 }));
8707
8708 // Process reference fields.
8709 FieldGaps field_gaps;
8710 size_t index = 0u;
8711 if (num_reference_fields != 0u) {
8712 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8713 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8714 for (; index != num_reference_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008715 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008716 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008717 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008718 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008719 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008720 if (index != num_fields &&
8721 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008722 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008723 while (index != num_fields &&
8724 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8725 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008726 field_offset = AssignFieldOffset<8u>(field, field_offset);
8727 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008728 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008729 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008730 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008731 if (index != num_fields &&
8732 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008733 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8734 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008735 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008736 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8737 ++index;
8738 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8739 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008740 while (index != num_fields &&
8741 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8742 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008743 field_offset = AssignFieldOffset<4u>(field, field_offset);
8744 ++index;
8745 }
8746 }
8747 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008748 if (index != num_fields &&
8749 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008750 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8751 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008752 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008753 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008754 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008755 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8756 ++index;
8757 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008758 while (index != num_fields &&
8759 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8760 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008761 field_offset = AssignFieldOffset<2u>(field, field_offset);
8762 ++index;
8763 }
8764 }
8765 // Process 8-bit fields.
8766 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008767 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008768 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8769 }
8770 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008771 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008772 field_offset = AssignFieldOffset<1u>(field, field_offset);
8773 }
8774
Ian Rogers7b078e82014-09-10 14:44:24 -07008775 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008776
Elliott Hughesadb460d2011-10-05 17:02:34 -07008777 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Vladimir Marko42bee502021-01-28 14:58:35 +00008778 DCHECK(!class_linker->init_done_ || !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
8779 if (!is_static &&
8780 UNLIKELY(!class_linker->init_done_) &&
8781 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008782 // We know there are no non-reference fields in the Reference classes, and we know
8783 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008784 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008785 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008786 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008787 --num_reference_fields;
8788 }
8789
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008790 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008791 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008792 if (is_static) {
8793 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008794 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008795 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008796 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008797 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008798 if (num_reference_fields == 0 || super_class == nullptr) {
8799 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008800 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008801 if (super_class == nullptr ||
8802 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8803 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008804 }
8805 }
8806 if (kIsDebugBuild) {
8807 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8808 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008809 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008810 while (cur_super != nullptr) {
8811 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8812 cur_super = cur_super->GetSuperClass();
8813 }
8814 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008815 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008816 } else {
8817 // Check that there is at least num_reference_fields other than Object.class.
8818 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008819 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008820 }
8821 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008822 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008823 std::string temp;
8824 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8825 size_t previous_size = klass->GetObjectSize();
8826 if (previous_size != 0) {
8827 // Make sure that we didn't originally have an incorrect size.
8828 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008829 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008830 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008831 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008832 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008833
8834 if (kIsDebugBuild) {
8835 // Make sure that the fields array is ordered by name but all reference
8836 // offsets are at the beginning as far as alignment allows.
8837 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00008838 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008839 : klass->GetFirstReferenceInstanceFieldOffset();
8840 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8841 num_reference_fields *
8842 sizeof(mirror::HeapReference<mirror::Object>));
8843 MemberOffset current_ref_offset = start_ref_offset;
8844 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008845 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008846 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008847 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8848 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008849 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008850 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008851 // NOTE: The field names can be the same. This is not possible in the Java language
8852 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008853 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008854 }
8855 Primitive::Type type = field->GetTypeAsPrimitiveType();
8856 bool is_primitive = type != Primitive::kPrimNot;
8857 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8858 strcmp("referent", field->GetName()) == 0) {
8859 is_primitive = true; // We lied above, so we have to expect a lie here.
8860 }
8861 MemberOffset offset = field->GetOffsetDuringLinking();
8862 if (is_primitive) {
8863 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8864 // Shuffled before references.
8865 size_t type_size = Primitive::ComponentSize(type);
8866 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8867 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8868 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8869 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8870 }
8871 } else {
8872 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8873 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8874 sizeof(mirror::HeapReference<mirror::Object>));
8875 }
8876 }
8877 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8878 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008879 return true;
8880}
8881
Vladimir Marko42bee502021-01-28 14:58:35 +00008882bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
8883 CHECK(klass != nullptr);
8884 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
8885}
8886
8887bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
8888 CHECK(klass != nullptr);
8889 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
8890}
8891
Vladimir Marko76649e82014-11-10 18:32:59 +00008892// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008893void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008894 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008895 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008896 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008897 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008898 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008899 // Compute reference offsets unless our superclass overflowed.
8900 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8901 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008902 if (num_reference_fields != 0u) {
8903 // All of the fields that contain object references are guaranteed be grouped in memory
8904 // starting at an appropriately aligned address after super class object data.
8905 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8906 sizeof(mirror::HeapReference<mirror::Object>));
8907 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008908 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008909 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008910 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008911 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008912 reference_offsets |= (0xffffffffu << start_bit) &
8913 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008914 }
8915 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008916 }
8917 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008918 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008919}
8920
Vladimir Marko18090d12018-06-01 16:53:12 +01008921ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8922 ObjPtr<mirror::DexCache> dex_cache) {
8923 StackHandleScope<1> hs(Thread::Current());
8924 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8925 return DoResolveString(string_idx, h_dex_cache);
8926}
8927
8928ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8929 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008930 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008931 uint32_t utf16_length;
8932 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008933 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008934 if (string != nullptr) {
8935 dex_cache->SetResolvedString(string_idx, string);
8936 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008937 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008938}
8939
Vladimir Marko18090d12018-06-01 16:53:12 +01008940ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8941 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008942 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008943 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008944 uint32_t utf16_length;
8945 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008946 ObjPtr<mirror::String> string =
8947 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008948 if (string != nullptr) {
8949 dex_cache->SetResolvedString(string_idx, string);
8950 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008951 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008952}
8953
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008954ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008955 ObjPtr<mirror::Class> referrer) {
8956 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8957}
8958
8959ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008960 ObjPtr<mirror::DexCache> dex_cache,
8961 ObjPtr<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01008962 DCHECK(dex_cache->GetClassLoader() == class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008963 const DexFile& dex_file = *dex_cache->GetDexFile();
8964 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Vladimir Markoc63d9672021-03-31 15:50:39 +01008965 ObjPtr<mirror::Class> type = LookupResolvedType(descriptor, class_loader);
8966 if (type != nullptr) {
8967 DCHECK(type->IsResolved());
8968 dex_cache->SetResolvedType(type_idx, type);
8969 }
8970 return type;
8971}
8972
8973ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const char* descriptor,
8974 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008975 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8976 ObjPtr<mirror::Class> type = nullptr;
8977 if (descriptor[1] == '\0') {
8978 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8979 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008980 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008981 } else {
8982 Thread* const self = Thread::Current();
8983 DCHECK(self != nullptr);
8984 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8985 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008986 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008987 }
Vladimir Markoc63d9672021-03-31 15:50:39 +01008988 return (type != nullptr && type->IsResolved()) ? type : nullptr;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008989}
8990
Andreas Gampeb0625e02019-05-01 12:43:31 -07008991template <typename RefType>
8992ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008993 StackHandleScope<2> hs(Thread::Current());
8994 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8995 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8996 return DoResolveType(type_idx, dex_cache, class_loader);
8997}
8998
Andreas Gampe4835d212018-11-21 14:55:10 -08008999// Instantiate the above.
9000template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9001 ArtField* referrer);
9002template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9003 ArtMethod* referrer);
9004template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
9005 ObjPtr<mirror::Class> referrer);
9006
Vladimir Marko09c5ca42018-05-31 15:15:31 +01009007ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009008 Handle<mirror::DexCache> dex_cache,
9009 Handle<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009010 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009011 Thread* self = Thread::Current();
9012 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
9013 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
9014 if (resolved != nullptr) {
9015 // TODO: we used to throw here if resolved's class loader was not the
9016 // boot class loader. This was to permit different classes with the
9017 // same name to be loaded simultaneously by different loaders
9018 dex_cache->SetResolvedType(type_idx, resolved);
9019 } else {
9020 CHECK(self->IsExceptionPending())
9021 << "Expected pending exception for failed resolution of: " << descriptor;
9022 // Convert a ClassNotFoundException to a NoClassDefFoundError.
9023 StackHandleScope<1> hs(self);
9024 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009025 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009026 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
9027 self->ClearException();
9028 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
9029 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009030 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009031 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00009032 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07009033 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00009034 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009035}
9036
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009037ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
9038 ObjPtr<mirror::DexCache> dex_cache,
9039 ObjPtr<mirror::ClassLoader> class_loader,
9040 uint32_t method_idx) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009041 DCHECK(dex_cache->GetClassLoader() == class_loader);
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009042 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
9043 // functions can optimize the search if the dex_cache is the same as the DexCache
9044 // of the class, with fall-back to name and signature search otherwise.
9045 ArtMethod* resolved = nullptr;
9046 if (klass->IsInterface()) {
9047 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9048 } else {
9049 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9050 }
9051 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009052 if (resolved != nullptr &&
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009053 // We pass AccessMethod::kNone instead of kLinking to not warn yet on the
9054 // access, as we'll be looking if the method can be accessed through an
9055 // interface.
David Brazdilf50ac102018-10-17 18:00:06 +01009056 hiddenapi::ShouldDenyAccessToMember(resolved,
9057 hiddenapi::AccessContext(class_loader, dex_cache),
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009058 hiddenapi::AccessMethod::kNone)) {
9059 // The resolved method that we have found cannot be accessed due to
9060 // hiddenapi (typically it is declared up the hierarchy and is not an SDK
9061 // method). Try to find an interface method from the implemented interfaces which is
Nicolas Geoffrayaf61f502021-03-31 16:03:50 +00009062 // part of the SDK.
9063 ArtMethod* itf_method = klass->FindAccessibleInterfaceMethod(resolved, image_pointer_size_);
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009064 if (itf_method == nullptr) {
9065 // No interface method. Call ShouldDenyAccessToMember again but this time
9066 // with AccessMethod::kLinking to ensure that an appropriate warning is
9067 // logged.
9068 hiddenapi::ShouldDenyAccessToMember(resolved,
9069 hiddenapi::AccessContext(class_loader, dex_cache),
9070 hiddenapi::AccessMethod::kLinking);
9071 resolved = nullptr;
9072 } else {
9073 // We found an interface method that is accessible, continue with the resolved method.
9074 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009075 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009076 if (resolved != nullptr) {
9077 // In case of jmvti, the dex file gets verified before being registered, so first
9078 // check if it's registered before checking class tables.
9079 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009080 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
9081 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009082 << "DexFile referrer: " << dex_file.GetLocation()
9083 << " ClassLoader: " << DescribeLoaders(class_loader, "");
9084 // Be a good citizen and update the dex cache to speed subsequent calls.
David Srbecky5de5efe2021-02-15 21:23:00 +00009085 dex_cache->SetResolvedMethod(method_idx, resolved);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009086 // Disable the following invariant check as the verifier breaks it. b/73760543
9087 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
9088 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
9089 // << "Method: " << resolved->PrettyMethod() << ", "
9090 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
9091 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009092 }
9093 return resolved;
9094}
9095
David Brazdil4525e0b2018-04-05 16:57:32 +01009096// Returns true if `method` is either null or hidden.
9097// Does not print any warnings if it is hidden.
9098static bool CheckNoSuchMethod(ArtMethod* method,
9099 ObjPtr<mirror::DexCache> dex_cache,
9100 ObjPtr<mirror::ClassLoader> class_loader)
9101 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009102 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
David Brazdil4525e0b2018-04-05 16:57:32 +01009103 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01009104 hiddenapi::ShouldDenyAccessToMember(method,
9105 hiddenapi::AccessContext(class_loader, dex_cache),
9106 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01009107}
9108
9109ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
9110 ObjPtr<mirror::DexCache> dex_cache,
9111 ObjPtr<mirror::ClassLoader> class_loader,
9112 uint32_t method_idx) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009113 DCHECK(dex_cache->GetClassLoader() == class_loader);
David Brazdil4525e0b2018-04-05 16:57:32 +01009114 if (klass->IsInterface()) {
9115 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9116 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
9117 } else {
9118 // If there was an interface method with the same signature, we would have
9119 // found it in the "copied" methods. Only DCHECK that the interface method
9120 // really does not exist.
9121 if (kIsDebugBuild) {
9122 ArtMethod* method =
9123 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9124 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
9125 }
9126 return nullptr;
9127 }
9128}
9129
Vladimir Marko89011192017-12-11 13:45:05 +00009130ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009131 Handle<mirror::DexCache> dex_cache,
9132 Handle<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009133 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
David Srbecky5de5efe2021-02-15 21:23:00 +00009134 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009135 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009136 if (resolved != nullptr) {
9137 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009138 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9139 return resolved;
9140 }
9141 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009142 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009143 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009144 if (klass == nullptr) {
9145 Thread::Current()->AssertPendingException();
9146 return nullptr;
9147 }
9148 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009149 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9150 } else {
9151 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009152 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009153 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009154 hiddenapi::ShouldDenyAccessToMember(
9155 resolved,
9156 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9157 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009158 resolved = nullptr;
9159 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009160 return resolved;
9161}
9162
Vladimir Markof44d36c2017-03-14 14:18:46 +00009163ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9164 ObjPtr<mirror::DexCache> dex_cache,
9165 ObjPtr<mirror::ClassLoader> class_loader,
9166 bool is_static) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009167 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009168 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009169 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009170 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9171 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009172 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009173 }
9174 if (klass == nullptr) {
9175 // The class has not been resolved yet, so the field is also unresolved.
9176 return nullptr;
9177 }
9178 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009179
David Brazdil1ab0fa82018-05-04 11:28:03 +01009180 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009181}
9182
Vladimir Markoe11dd502017-12-08 14:09:45 +00009183ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009184 Handle<mirror::DexCache> dex_cache,
9185 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009186 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009187 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
David Srbecky5de5efe2021-02-15 21:23:00 +00009188 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009189 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009190 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009191 return resolved;
9192 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009193 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009194 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009195 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009196 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009197 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009198 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009199 }
9200
David Brazdil1ab0fa82018-05-04 11:28:03 +01009201 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9202 if (resolved == nullptr) {
9203 const char* name = dex_file.GetFieldName(field_id);
9204 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009205 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009206 }
9207 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009208}
9209
David Brazdil1ab0fa82018-05-04 11:28:03 +01009210ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9211 ObjPtr<mirror::DexCache> dex_cache,
9212 ObjPtr<mirror::ClassLoader> class_loader,
9213 uint32_t field_idx,
9214 bool is_static) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009215 DCHECK(dex_cache->GetClassLoader() == class_loader);
Vladimir Markob10668c2021-06-10 09:52:53 +01009216 ArtField* resolved = is_static ? klass->FindStaticField(dex_cache, field_idx)
9217 : klass->FindInstanceField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009218 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009219 hiddenapi::ShouldDenyAccessToMember(resolved,
9220 hiddenapi::AccessContext(class_loader, dex_cache),
9221 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009222 resolved = nullptr;
9223 }
9224
9225 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009226 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009227 }
9228
9229 return resolved;
9230}
9231
9232ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9233 ObjPtr<mirror::DexCache> dex_cache,
9234 ObjPtr<mirror::ClassLoader> class_loader,
9235 uint32_t field_idx) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009236 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
Vladimir Markob10668c2021-06-10 09:52:53 +01009237 ArtField* resolved = klass->FindField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009238
9239 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009240 hiddenapi::ShouldDenyAccessToMember(resolved,
9241 hiddenapi::AccessContext(class_loader, dex_cache),
9242 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009243 resolved = nullptr;
9244 }
9245
9246 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009247 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009248 }
9249
9250 return resolved;
9251}
9252
Vladimir Markoaf940202017-12-08 15:01:18 +00009253ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9254 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009255 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009256 Handle<mirror::DexCache> dex_cache,
9257 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009258 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009259 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009260 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
Narayan Kamath25352fc2016-08-03 12:46:58 +01009261
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009262 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009263 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009264 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009265 }
9266
Narayan Kamath25352fc2016-08-03 12:46:58 +01009267 StackHandleScope<4> hs(self);
9268
9269 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009270 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009271 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009272 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009273 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009274 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009275 DCHECK(self->IsExceptionPending());
9276 return nullptr;
9277 }
9278
9279 // Then resolve the argument types.
9280 //
9281 // TODO: Is there a better way to figure out the number of method arguments
9282 // other than by looking at the shorty ?
9283 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9284
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009285 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009286 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9287 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009288 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009289 DCHECK(self->IsExceptionPending());
9290 return nullptr;
9291 }
9292
9293 DexFileParameterIterator it(dex_file, proto_id);
9294 int32_t i = 0;
9295 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9296 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009297 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009298 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009299 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009300 DCHECK(self->IsExceptionPending());
9301 return nullptr;
9302 }
9303
9304 method_params->Set(i++, param_class.Get());
9305 }
9306
9307 DCHECK(!it.HasNext());
9308
9309 Handle<mirror::MethodType> type = hs.NewHandle(
9310 mirror::MethodType::Create(self, return_type, method_params));
Nicolas Geoffray4aebd582021-07-23 15:27:31 +01009311 if (type != nullptr) {
9312 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9313 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01009314
9315 return type.Get();
9316}
9317
Vladimir Markoaf940202017-12-08 15:01:18 +00009318ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009319 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009320 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009321 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009322 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9323 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009324 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009325}
9326
Vladimir Marko5aead702019-03-27 11:00:36 +00009327ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009328 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009329 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009330 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009331 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009332 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9333 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009334 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009335 bool is_static;
9336 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009337 switch (handle_type) {
9338 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009339 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009340 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009341 is_static = true;
9342 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009343 break;
9344 }
9345 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009346 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009347 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009348 is_static = true;
9349 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009350 break;
9351 }
9352 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009353 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009354 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009355 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009356 num_params = 2;
9357 break;
9358 }
9359 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009360 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009361 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009362 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009363 num_params = 1;
9364 break;
9365 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009366 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009367 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009368 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009369 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009370 case DexFile::MethodHandleType::kInvokeInterface:
9371 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009372 }
9373
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009374 ArtField* target_field =
9375 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9376 if (LIKELY(target_field != nullptr)) {
9377 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9378 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9379 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9380 ThrowIllegalAccessErrorField(referring_class, target_field);
9381 return nullptr;
9382 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009383 if (UNLIKELY(is_put && target_field->IsFinal())) {
9384 ThrowIllegalAccessErrorField(referring_class, target_field);
9385 return nullptr;
9386 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009387 } else {
9388 DCHECK(Thread::Current()->IsExceptionPending());
9389 return nullptr;
9390 }
9391
9392 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009393 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009394 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9395 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009396 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009397 DCHECK(self->IsExceptionPending());
9398 return nullptr;
9399 }
9400
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009401 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009402 Handle<mirror::Class> return_type;
9403 switch (handle_type) {
9404 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009405 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009406 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009407 break;
9408 }
9409 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009410 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009411 break;
9412 }
9413 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009414 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009415 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009416 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009417 break;
9418 }
9419 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009420 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009421 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009422 break;
9423 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009424 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009425 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009426 case DexFile::MethodHandleType::kInvokeConstructor:
9427 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009428 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009429 UNREACHABLE();
9430 }
9431
9432 for (int32_t i = 0; i < num_params; ++i) {
9433 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9434 DCHECK(self->IsExceptionPending());
9435 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009436 }
9437 }
9438
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009439 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009440 DCHECK(self->IsExceptionPending());
9441 return nullptr;
9442 }
9443
9444 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009445 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9446 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009447 DCHECK(self->IsExceptionPending());
9448 return nullptr;
9449 }
Orion Hodson631827d2017-04-10 14:53:47 +01009450
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009451 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9452 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9453}
9454
Vladimir Marko5aead702019-03-27 11:00:36 +00009455ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009456 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009457 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009458 ArtMethod* referrer) {
9459 DexFile::MethodHandleType handle_type =
9460 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9461 mirror::MethodHandle::Kind kind;
9462 uint32_t receiver_count = 0;
9463 ArtMethod* target_method = nullptr;
9464 switch (handle_type) {
9465 case DexFile::MethodHandleType::kStaticPut:
9466 case DexFile::MethodHandleType::kStaticGet:
9467 case DexFile::MethodHandleType::kInstancePut:
9468 case DexFile::MethodHandleType::kInstanceGet:
9469 UNREACHABLE();
9470 case DexFile::MethodHandleType::kInvokeStatic: {
9471 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9472 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009473 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9474 method_handle.field_or_method_idx_,
9475 referrer,
9476 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009477 break;
9478 }
9479 case DexFile::MethodHandleType::kInvokeInstance: {
9480 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9481 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009482 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9483 method_handle.field_or_method_idx_,
9484 referrer,
9485 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009486 break;
9487 }
9488 case DexFile::MethodHandleType::kInvokeConstructor: {
9489 // Constructors are currently implemented as a transform. They
9490 // are special cased later in this method.
9491 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9492 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009493 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9494 method_handle.field_or_method_idx_,
9495 referrer,
9496 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009497 break;
9498 }
9499 case DexFile::MethodHandleType::kInvokeDirect: {
9500 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9501 receiver_count = 1;
9502 StackHandleScope<2> hs(self);
9503 // A constant method handle with type kInvokeDirect can refer to
9504 // a method that is private or to a method in a super class. To
9505 // disambiguate the two options, we resolve the method ignoring
9506 // the invocation type to determine if the method is private. We
9507 // then resolve again specifying the intended invocation type to
9508 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009509 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009510 hs.NewHandle(referrer->GetDexCache()),
9511 hs.NewHandle(referrer->GetClassLoader()));
9512 if (UNLIKELY(target_method == nullptr)) {
9513 break;
9514 }
9515
9516 if (target_method->IsPrivate()) {
9517 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009518 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9519 method_handle.field_or_method_idx_,
9520 referrer,
9521 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009522 } else {
9523 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009524 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9525 method_handle.field_or_method_idx_,
9526 referrer,
9527 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009528 if (UNLIKELY(target_method == nullptr)) {
9529 break;
9530 }
9531 // Find the method specified in the parent in referring class
9532 // so invoke-super invokes the method in the parent of the
9533 // referrer.
9534 target_method =
9535 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9536 kRuntimePointerSize);
9537 }
9538 break;
9539 }
9540 case DexFile::MethodHandleType::kInvokeInterface: {
9541 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9542 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009543 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9544 method_handle.field_or_method_idx_,
9545 referrer,
9546 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009547 break;
9548 }
Orion Hodson631827d2017-04-10 14:53:47 +01009549 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009550
9551 if (UNLIKELY(target_method == nullptr)) {
9552 DCHECK(Thread::Current()->IsExceptionPending());
9553 return nullptr;
9554 }
9555
9556 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9557 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9558 uint32_t access_flags = target_method->GetAccessFlags();
9559 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9560 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9561 return nullptr;
9562 }
9563
9564 // Calculate the number of parameters from the method shorty. We add the
9565 // receiver count (0 or 1) and deduct one for the return value.
9566 uint32_t shorty_length;
9567 target_method->GetShorty(&shorty_length);
9568 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9569
Orion Hodsonecd58562018-09-24 11:27:33 +01009570 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009571 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009572 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9573 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9574 if (method_params.Get() == nullptr) {
9575 DCHECK(self->IsExceptionPending());
9576 return nullptr;
9577 }
9578
Orion Hodsonecd58562018-09-24 11:27:33 +01009579 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009580 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009581 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009582 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009583 // Insert receiver. Use the class identified in the method handle rather than the declaring
9584 // class of the resolved method which may be super class or default interface method
9585 // (b/115964401).
9586 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9587 // receiver_class should have been resolved when resolving the target method.
9588 DCHECK(receiver_class != nullptr);
9589 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009590 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009591
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009592 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009593 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009594 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009595 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009596 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009597 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009598 if (nullptr == klass) {
9599 DCHECK(self->IsExceptionPending());
9600 return nullptr;
9601 }
9602 method_params->Set(index++, klass);
9603 it.Next();
9604 }
9605
Orion Hodsonecd58562018-09-24 11:27:33 +01009606 Handle<mirror::Class> return_type =
9607 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009608 if (UNLIKELY(return_type.IsNull())) {
9609 DCHECK(self->IsExceptionPending());
9610 return nullptr;
9611 }
9612
9613 Handle<mirror::MethodType>
9614 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9615 if (UNLIKELY(method_type.IsNull())) {
9616 DCHECK(self->IsExceptionPending());
9617 return nullptr;
9618 }
9619
9620 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9621 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9622 Handle<mirror::MethodHandlesLookup> lookup =
9623 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9624 return lookup->FindConstructor(self, constructor_class, method_type);
9625 }
9626
9627 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9628 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9629}
9630
Vladimir Markoaf940202017-12-08 15:01:18 +00009631ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9632 uint32_t method_handle_idx,
9633 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009634 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009635 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009636 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009637 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9638 case DexFile::MethodHandleType::kStaticPut:
9639 case DexFile::MethodHandleType::kStaticGet:
9640 case DexFile::MethodHandleType::kInstancePut:
9641 case DexFile::MethodHandleType::kInstanceGet:
9642 return ResolveMethodHandleForField(self, method_handle, referrer);
9643 case DexFile::MethodHandleType::kInvokeStatic:
9644 case DexFile::MethodHandleType::kInvokeInstance:
9645 case DexFile::MethodHandleType::kInvokeConstructor:
9646 case DexFile::MethodHandleType::kInvokeDirect:
9647 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009648 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009649 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009650}
9651
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009652bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9653 return (entry_point == GetQuickResolutionStub()) ||
9654 (quick_resolution_trampoline_ == entry_point);
9655}
9656
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009657bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9658 return (entry_point == GetQuickToInterpreterBridge()) ||
9659 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9660}
9661
9662bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9663 return (entry_point == GetQuickGenericJniStub()) ||
9664 (quick_generic_jni_trampoline_ == entry_point);
9665}
9666
David Sehra49e0532017-08-25 08:05:29 -07009667bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009668 return entry_point == GetJniDlsymLookupStub() ||
9669 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009670}
9671
Vladimir Markofa458ac2020-02-12 14:08:07 +00009672bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9673 return entry_point == GetJniDlsymLookupCriticalStub() ||
9674 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9675}
9676
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009677const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9678 return GetQuickGenericJniStub();
9679}
9680
Alex Lightdb01a092017-04-03 15:39:55 -07009681void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9682 DCHECK(method->IsObsolete());
9683 // We cannot mess with the entrypoints of native methods because they are used to determine how
9684 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9685 if (!method->IsNative()) {
9686 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9687 }
9688}
9689
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009690void ClassLinker::DumpForSigQuit(std::ostream& os) {
Hans Boehmfb3ad722021-08-16 16:53:17 +00009691 ScopedObjectAccess soa(Thread::Current());
9692 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009693 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9694 << NumNonZygoteClasses() << "\n";
Hans Boehmfb3ad722021-08-16 16:53:17 +00009695 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009696 os << "Dumping registered class loaders\n";
9697 size_t class_loader_index = 0;
9698 for (const ClassLoaderData& class_loader : class_loaders_) {
9699 ObjPtr<mirror::ClassLoader> loader =
Hans Boehmfb3ad722021-08-16 16:53:17 +00009700 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009701 if (loader != nullptr) {
9702 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9703 bool saw_one_dex_file = false;
David Srbecky6fbcc292021-02-23 01:05:32 +00009704 for (const auto& entry : dex_caches_) {
9705 const DexCacheData& dex_cache = entry.second;
9706 if (dex_cache.class_table == class_loader.class_table) {
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009707 if (saw_one_dex_file) {
9708 os << ":";
9709 }
9710 saw_one_dex_file = true;
David Srbecky6fbcc292021-02-23 01:05:32 +00009711 os << entry.first->GetLocation();
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009712 }
9713 }
9714 os << "]";
9715 bool found_parent = false;
9716 if (loader->GetParent() != nullptr) {
9717 size_t parent_index = 0;
9718 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9719 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
Hans Boehmfb3ad722021-08-16 16:53:17 +00009720 soa.Self()->DecodeJObject(class_loader2.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009721 if (loader2 == loader->GetParent()) {
9722 os << ", parent #" << parent_index;
9723 found_parent = true;
9724 break;
9725 }
9726 parent_index++;
9727 }
9728 if (!found_parent) {
9729 os << ", unregistered parent of type "
9730 << loader->GetParent()->GetClass()->PrettyDescriptor();
9731 }
9732 } else {
9733 os << ", no parent";
9734 }
9735 os << "\n";
9736 }
9737 }
9738 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009739 Runtime* runtime = Runtime::Current();
9740 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9741 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009742}
9743
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009744class CountClassesVisitor : public ClassLoaderVisitor {
9745 public:
9746 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9747
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009748 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009749 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009750 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009751 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009752 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9753 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009754 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009755 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009756
9757 size_t num_zygote_classes;
9758 size_t num_non_zygote_classes;
9759};
9760
9761size_t ClassLinker::NumZygoteClasses() const {
9762 CountClassesVisitor visitor;
9763 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009764 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009765}
9766
9767size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009768 CountClassesVisitor visitor;
9769 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009770 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009771}
9772
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009773size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009774 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009775 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009776 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009777}
9778
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009779pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009780 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009781}
9782
9783pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009784 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009785}
9786
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009787void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009788 DCHECK(!init_done_);
9789
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009790 DCHECK(klass != nullptr);
9791 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009792
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009793 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009794 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009795 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9796 int32_t index = static_cast<int32_t>(class_root);
9797 DCHECK(class_roots->Get(index) == nullptr);
9798 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009799}
9800
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009801ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9802 Thread* self,
9803 const std::vector<const DexFile*>& dex_files,
9804 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009805 Handle<mirror::ClassLoader> parent_loader,
Brad Stenning9c924e82021-10-11 19:09:00 -07009806 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries,
9807 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries_after) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009808
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009809 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009810
Mathieu Chartierc7853442015-03-27 14:35:38 -07009811 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009812 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009813
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009814 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009815 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009816 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009817 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009818 mirror::ObjectArray<mirror::Object>::Alloc(self,
9819 dex_elements_class.Get(),
9820 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009821 Handle<mirror::Class> h_dex_element_class =
9822 hs.NewHandle(dex_elements_class->GetComponentType());
9823
Mathieu Chartierc7853442015-03-27 14:35:38 -07009824 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009825 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009826 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009827
Andreas Gampe08883de2016-11-08 13:20:52 -08009828 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009829 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009830
Andreas Gampe08883de2016-11-08 13:20:52 -08009831 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009832 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009833
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009834 // Fill the elements array.
9835 int32_t index = 0;
9836 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009837 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009838
Calin Juravle7865ac72017-06-28 11:03:12 -07009839 // CreateWellKnownClassLoader is only used by gtests and compiler.
9840 // 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 -07009841 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9842 self,
9843 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009844 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009845 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009846
Mathieu Chartier3738e982017-05-12 16:07:28 -07009847 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9848 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009849 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009850 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009851 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009852 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009853
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009854 Handle<mirror::String> h_file_name = hs2.NewHandle(
9855 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009856 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009857 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9858
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009859 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009860 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009861 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009862
9863 h_dex_elements->Set(index, h_element.Get());
9864 index++;
9865 }
9866 DCHECK_EQ(index, h_dex_elements->GetLength());
9867
9868 // Create DexPathList.
9869 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009870 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009871 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009872 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009873 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009874 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9875 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9876 // elements.
9877 {
9878 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9879 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9880 DCHECK(native_lib_dirs != nullptr);
9881 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9882 DCHECK(list_class != nullptr);
9883 {
9884 StackHandleScope<1> h_list_scope(self);
9885 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9886 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9887 DCHECK(list_init);
9888 list_class = h_list_class.Get();
9889 }
9890 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9891 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9892 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9893 // normally never null), as long as one does not try to add elements, this will still
9894 // work.
9895 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9896 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009897
Calin Juravle7865ac72017-06-28 11:03:12 -07009898 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009899 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9900 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009901 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009902 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009903 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009904 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009905 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009906 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009907
9908 // Make a pretend boot-classpath.
9909 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009910 ArtField* const parent_field =
Vladimir Markoe300c4e2021-06-08 16:00:05 +01009911 jni::DecodeArtField(WellKnownClasses::java_lang_ClassLoader_parent);
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009912 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009913 if (parent_loader.Get() == nullptr) {
9914 ScopedObjectAccessUnchecked soa(self);
9915 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9916 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9917 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9918 } else {
9919 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9920 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009921
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009922 ArtField* shared_libraries_field =
9923 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9924 DCHECK(shared_libraries_field != nullptr);
9925 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9926
Brad Stenning9c924e82021-10-11 19:09:00 -07009927 ArtField* shared_libraries_after_field =
9928 jni::DecodeArtField(
9929 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
9930 DCHECK(shared_libraries_after_field != nullptr);
9931 shared_libraries_after_field->SetObject<false>(h_class_loader.Get(),
9932 shared_libraries_after.Get());
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009933 return h_class_loader.Get();
9934}
9935
9936jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9937 const std::vector<const DexFile*>& dex_files,
9938 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009939 jobject parent_loader,
Brad Stenning9c924e82021-10-11 19:09:00 -07009940 jobject shared_libraries,
9941 jobject shared_libraries_after) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009942 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9943 WellKnownClasses::dalvik_system_PathClassLoader) ||
9944 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009945 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9946 self->GetJniEnv()->IsSameObject(loader_class,
9947 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009948
9949 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9950 // We could move the jobject to the callers, but all call-sites do this...
9951 ScopedObjectAccessUnchecked soa(self);
9952
9953 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Brad Stenning9c924e82021-10-11 19:09:00 -07009954 StackHandleScope<5> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009955
9956 Handle<mirror::Class> h_loader_class =
9957 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009958 Handle<mirror::ClassLoader> h_parent =
9959 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9960 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9961 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Brad Stenning9c924e82021-10-11 19:09:00 -07009962 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries_after =
9963 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries_after));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009964
9965 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9966 self,
9967 dex_files,
9968 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009969 h_parent,
Brad Stenning9c924e82021-10-11 19:09:00 -07009970 h_shared_libraries,
9971 h_shared_libraries_after);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009972
9973 // Make it a global ref and return.
9974 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009975 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009976 return soa.Env()->NewGlobalRef(local_ref.get());
9977}
9978
Calin Juravle7865ac72017-06-28 11:03:12 -07009979jobject ClassLinker::CreatePathClassLoader(Thread* self,
9980 const std::vector<const DexFile*>& dex_files) {
9981 return CreateWellKnownClassLoader(self,
9982 dex_files,
9983 WellKnownClasses::dalvik_system_PathClassLoader,
9984 nullptr);
9985}
9986
Andreas Gampe8ac75952015-06-02 21:01:45 -07009987void ClassLinker::DropFindArrayClassCache() {
9988 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9989 find_array_class_cache_next_victim_ = 0;
9990}
9991
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009992void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009993 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009994 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009995 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009996 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9997 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009998 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009999 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010000 }
10001 }
10002}
10003
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010004void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10005 for (const ClassLoaderData& data : class_loaders_) {
10006 LinearAlloc* alloc = data.allocator;
10007 if (alloc != nullptr && !visitor->Visit(alloc)) {
10008 break;
10009 }
10010 }
10011}
10012
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010013void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10014 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010015 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010016 Thread* const self = Thread::Current();
10017 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010018 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010019 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010020 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010021 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10022 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010023 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010024 }
10025}
10026
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010027void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010028 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010029 std::vector<ClassLoaderData> to_delete;
10030 // Do the delete outside the lock to avoid lock violation in jit code cache.
10031 {
10032 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10033 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10034 const ClassLoaderData& data = *it;
10035 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010036 ObjPtr<mirror::ClassLoader> class_loader =
10037 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010038 if (class_loader != nullptr) {
10039 ++it;
10040 } else {
10041 VLOG(class_linker) << "Freeing class loader";
10042 to_delete.push_back(data);
10043 it = class_loaders_.erase(it);
10044 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010045 }
10046 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010047 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010048 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010049 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010050 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010051}
10052
Mathieu Chartier65975772016-08-05 10:46:36 -070010053class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10054 public:
10055 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10056 : method_(method),
10057 pointer_size_(pointer_size) {}
10058
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010059 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010060 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10061 holder_ = klass;
10062 }
10063 // Return false to stop searching if holder_ is not null.
10064 return holder_ == nullptr;
10065 }
10066
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010067 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010068 const ArtMethod* const method_;
10069 const PointerSize pointer_size_;
10070};
10071
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010072ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010073 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10074 CHECK(method->IsCopied());
10075 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10076 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010077 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010078}
10079
Calin Juravle33787682019-07-26 14:27:18 -070010080bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10081 REQUIRES_SHARED(Locks::mutator_lock_) {
10082 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10083 LOG(FATAL) << "UNREACHABLE";
10084 UNREACHABLE();
10085}
10086
10087bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10088 REQUIRES_SHARED(Locks::mutator_lock_) {
10089 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10090 LOG(FATAL) << "UNREACHABLE";
10091 UNREACHABLE();
10092}
10093
10094bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10095 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10096 LOG(FATAL) << "UNREACHABLE";
10097 UNREACHABLE();
10098}
10099
Calin Juravle2c2724c2021-01-14 19:54:23 -080010100void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10101 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10102 LOG(FATAL) << "UNREACHABLE";
10103 UNREACHABLE();
10104}
10105
Roland Levillain0e840272018-08-23 19:55:30 +010010106// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010107template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010108 Thread* self,
10109 ObjPtr<mirror::Class> java_lang_Class,
10110 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010111template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010112 Thread* self,
10113 ObjPtr<mirror::Class> java_lang_Class,
10114 uint32_t class_size);
10115
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010116} // namespace art