blob: 5de7adf3650fec023ba56620a12fbb4448f1a463 [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 Geoffray60d4abc2020-07-27 13:58:51 +0000204static void ChangeInterpreterBridgeToNterp(ArtMethod* method, ClassLinker* class_linker)
205 REQUIRES_SHARED(Locks::mutator_lock_) {
206 Runtime* runtime = Runtime::Current();
207 if (class_linker->IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode()) &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000208 CanMethodUseNterp(method)) {
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000209 if (method->GetDeclaringClass()->IsVisiblyInitialized() ||
210 !NeedsClinitCheckBeforeCall(method)) {
211 runtime->GetInstrumentation()->UpdateMethodsCode(method, interpreter::GetNterpEntryPoint());
212 } else {
213 // Put the resolution stub, which will initialize the class and then
214 // call the method with nterp.
215 runtime->GetInstrumentation()->UpdateMethodsCode(method, GetQuickResolutionStub());
216 }
217 }
218}
219
Nicolas Geoffray66934ef2021-07-07 14:56:23 +0100220static void UpdateClassAfterVerification(Handle<mirror::Class> klass,
221 PointerSize pointer_size,
222 verifier::FailureKind failure_kind)
Andreas Gampe5b20b352018-10-11 19:03:20 -0700223 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000224 Runtime* runtime = Runtime::Current();
225 ClassLinker* class_linker = runtime->GetClassLinker();
Nicolas Geoffray66934ef2021-07-07 14:56:23 +0100226 if (failure_kind == verifier::FailureKind::kNoFailure) {
Andreas Gampe5b20b352018-10-11 19:03:20 -0700227 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +0100228 }
229
230 // Now that the class has passed verification, try to set nterp entrypoints
231 // to methods that currently use the switch interpreter.
232 if (interpreter::CanRuntimeUseNterp()) {
233 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
234 ChangeInterpreterBridgeToNterp(&m, class_linker);
Nicolas Geoffray00391822019-12-10 10:17:23 +0000235 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700236 }
237}
238
Vladimir Markobf121912019-06-04 13:49:05 +0100239// Callback responsible for making a batch of classes visibly initialized
240// after all threads have called it from a checkpoint, ensuring visibility.
241class ClassLinker::VisiblyInitializedCallback final
242 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
243 public:
244 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
245 : class_linker_(class_linker),
246 num_classes_(0u),
247 thread_visibility_counter_(0),
248 barriers_() {
249 std::fill_n(classes_, kMaxClasses, nullptr);
250 }
251
252 bool IsEmpty() const {
253 DCHECK_LE(num_classes_, kMaxClasses);
254 return num_classes_ == 0u;
255 }
256
257 bool IsFull() const {
258 DCHECK_LE(num_classes_, kMaxClasses);
259 return num_classes_ == kMaxClasses;
260 }
261
262 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
263 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
264 DCHECK(!IsFull());
265 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
266 ++num_classes_;
267 }
268
269 void AddBarrier(Barrier* barrier) {
270 barriers_.push_front(barrier);
271 }
272
273 std::forward_list<Barrier*> GetAndClearBarriers() {
274 std::forward_list<Barrier*> result;
275 result.swap(barriers_);
276 result.reverse(); // Return barriers in insertion order.
277 return result;
278 }
279
280 void MakeVisible(Thread* self) {
281 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
282 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
283 AdjustThreadVisibilityCounter(self, count);
284 }
285
286 void Run(Thread* self) override {
287 self->ClearMakeVisiblyInitializedCounter();
288 AdjustThreadVisibilityCounter(self, -1);
289 }
290
291 private:
292 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
293 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
294 if (old + adjustment == 0) {
295 // All threads passed the checkpoint. Mark classes as visibly initialized.
296 {
297 ScopedObjectAccess soa(self);
298 StackHandleScope<1u> hs(self);
299 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
300 JavaVMExt* vm = self->GetJniEnv()->GetVm();
301 for (size_t i = 0, num = num_classes_; i != num; ++i) {
302 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
303 vm->DeleteWeakGlobalRef(self, classes_[i]);
304 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100305 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100306 class_linker_->FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100307 }
308 }
309 num_classes_ = 0u;
310 }
311 class_linker_->VisiblyInitializedCallbackDone(self, this);
312 }
313 }
314
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100315 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100316
317 ClassLinker* const class_linker_;
318 size_t num_classes_;
319 jweak classes_[kMaxClasses];
320
321 // The thread visibility counter starts at 0 and it is incremented by the number of
322 // threads that need to run this callback (by the thread that request the callback
323 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
324 // whether after the increment or after a decrement, we know that `Run()` was executed
325 // for all threads and therefore we can mark the classes as visibly initialized.
326 std::atomic<ssize_t> thread_visibility_counter_;
327
328 // List of barries to `Pass()` for threads that wait for the callback to complete.
329 std::forward_list<Barrier*> barriers_;
330};
331
332void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
333 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
334 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
335 }
336 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
337 if (wait) {
338 maybe_barrier.emplace(0);
339 }
340 int wait_count = 0;
341 VisiblyInitializedCallback* callback = nullptr;
342 {
343 MutexLock lock(self, visibly_initialized_callback_lock_);
344 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
345 callback = visibly_initialized_callback_.release();
346 running_visibly_initialized_callbacks_.push_front(*callback);
347 }
348 if (wait) {
349 DCHECK(maybe_barrier.has_value());
350 Barrier* barrier = std::addressof(*maybe_barrier);
351 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
352 cb.AddBarrier(barrier);
353 ++wait_count;
354 }
355 }
356 }
357 if (callback != nullptr) {
358 callback->MakeVisible(self);
359 }
360 if (wait_count != 0) {
361 DCHECK(maybe_barrier.has_value());
362 maybe_barrier->Increment(self, wait_count);
363 }
364}
365
366void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
367 VisiblyInitializedCallback* callback) {
368 MutexLock lock(self, visibly_initialized_callback_lock_);
369 // Pass the barriers if requested.
370 for (Barrier* barrier : callback->GetAndClearBarriers()) {
371 barrier->Pass(self);
372 }
373 // Remove the callback from the list of running callbacks.
374 auto before = running_visibly_initialized_callbacks_.before_begin();
375 auto it = running_visibly_initialized_callbacks_.begin();
376 DCHECK(it != running_visibly_initialized_callbacks_.end());
377 while (std::addressof(*it) != callback) {
378 before = it;
379 ++it;
380 DCHECK(it != running_visibly_initialized_callbacks_.end());
381 }
382 running_visibly_initialized_callbacks_.erase_after(before);
383 // Reuse or destroy the callback object.
384 if (visibly_initialized_callback_ == nullptr) {
385 visibly_initialized_callback_.reset(callback);
386 } else {
387 delete callback;
388 }
389}
390
Alex Lightfb119572019-09-18 15:04:53 -0700391void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
392 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
393 if (cb != nullptr) {
394 cb->MakeVisible(self);
395 }
396 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
397 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
398}
399
Vladimir Markobf121912019-06-04 13:49:05 +0100400ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
401 Thread* self, Handle<mirror::Class> klass) {
402 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
403 // Thanks to the x86 memory model, we do not need any memory fences and
404 // we can immediately mark the class as visibly initialized.
405 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100406 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100407 return nullptr;
408 }
409 if (Runtime::Current()->IsActiveTransaction()) {
410 // Transactions are single-threaded, so we can mark the class as visibly intialized.
411 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
412 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100413 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100414 return nullptr;
415 }
416 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
417 MutexLock lock(self, visibly_initialized_callback_lock_);
418 if (visibly_initialized_callback_ == nullptr) {
419 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
420 }
421 DCHECK(!visibly_initialized_callback_->IsFull());
422 visibly_initialized_callback_->AddClass(self, klass.Get());
423
424 if (visibly_initialized_callback_->IsFull()) {
425 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
426 running_visibly_initialized_callbacks_.push_front(*callback);
427 return callback;
428 } else {
429 return nullptr;
430 }
431}
432
Vladimir Marko86c87522020-05-11 16:55:55 +0100433const void* ClassLinker::RegisterNative(
434 Thread* self, ArtMethod* method, const void* native_method) {
435 CHECK(method->IsNative()) << method->PrettyMethod();
436 CHECK(native_method != nullptr) << method->PrettyMethod();
437 void* new_native_method = nullptr;
438 Runtime* runtime = Runtime::Current();
439 runtime->GetRuntimeCallbacks()->RegisterNativeMethod(method,
440 native_method,
441 /*out*/&new_native_method);
442 if (method->IsCriticalNative()) {
443 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
444 // Remove old registered method if any.
445 auto it = critical_native_code_with_clinit_check_.find(method);
446 if (it != critical_native_code_with_clinit_check_.end()) {
447 critical_native_code_with_clinit_check_.erase(it);
448 }
449 // To ensure correct memory visibility, we need the class to be visibly
450 // initialized before we can set the JNI entrypoint.
451 if (method->GetDeclaringClass()->IsVisiblyInitialized()) {
452 method->SetEntryPointFromJni(new_native_method);
453 } else {
454 critical_native_code_with_clinit_check_.emplace(method, new_native_method);
455 }
456 } else {
457 method->SetEntryPointFromJni(new_native_method);
458 }
459 return new_native_method;
460}
461
462void ClassLinker::UnregisterNative(Thread* self, ArtMethod* method) {
463 CHECK(method->IsNative()) << method->PrettyMethod();
464 // Restore stub to lookup native pointer via dlsym.
465 if (method->IsCriticalNative()) {
466 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
467 auto it = critical_native_code_with_clinit_check_.find(method);
468 if (it != critical_native_code_with_clinit_check_.end()) {
469 critical_native_code_with_clinit_check_.erase(it);
470 }
471 method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
472 } else {
473 method->SetEntryPointFromJni(GetJniDlsymLookupStub());
474 }
475}
476
477const void* ClassLinker::GetRegisteredNative(Thread* self, ArtMethod* method) {
478 if (method->IsCriticalNative()) {
479 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
480 auto it = critical_native_code_with_clinit_check_.find(method);
481 if (it != critical_native_code_with_clinit_check_.end()) {
482 return it->second;
483 }
484 const void* native_code = method->GetEntryPointFromJni();
485 return IsJniDlsymLookupCriticalStub(native_code) ? nullptr : native_code;
486 } else {
487 const void* native_code = method->GetEntryPointFromJni();
488 return IsJniDlsymLookupStub(native_code) ? nullptr : native_code;
489 }
490}
491
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800492void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
493 bool wrap_in_no_class_def,
494 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700495 // The class failed to initialize on a previous attempt, so we want to throw
496 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
497 // failed in verification, in which case v2 5.4.1 says we need to re-throw
498 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800499 Runtime* const runtime = Runtime::Current();
500 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700501 std::string extra;
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100502 ObjPtr<mirror::Object> verify_error = GetErroneousStateError(c);
Vladimir Markobb206de2019-03-28 10:30:32 +0000503 if (verify_error != nullptr) {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100504 DCHECK(!verify_error->IsClass());
505 extra = verify_error->AsThrowable()->Dump();
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700506 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800507 if (log) {
508 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
509 << ": " << extra;
510 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700511 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700512
David Sehr709b0702016-10-13 09:12:37 -0700513 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800514 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800515 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700516 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700517 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000518 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700519 } else {
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100520 ObjPtr<mirror::Object> erroneous_state_error = GetErroneousStateError(c);
521 if (erroneous_state_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800522 // Rethrow stored error.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100523 HandleEarlierErroneousStateError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800524 }
Alex Lightd6251582016-10-31 11:12:30 -0700525 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
526 // might have meant to go down the earlier if statement with the original error but it got
527 // swallowed by the OOM so we end up here.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +0100528 if (erroneous_state_error == nullptr ||
529 (wrap_in_no_class_def && !IsVerifyError(erroneous_state_error))) {
Andreas Gampecb086952015-11-02 16:20:00 -0800530 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
531 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
532 // exception will be a cause.
533 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700534 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700535 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700536 }
537}
538
Brian Carlstromb23eab12014-10-08 17:55:21 -0700539static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700540 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700541 if (VLOG_IS_ON(class_linker)) {
542 std::string temp;
543 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000544 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700545 }
546}
547
548static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700549 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700550 Thread* self = Thread::Current();
551 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700552
553 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700554 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700555
David Srbecky346fd962020-07-27 16:51:00 +0100556 // Boot classpath classes should not fail initialization. This is a consistency debug check.
557 // This cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800558 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800559 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800560 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
561 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
562 // could have caused the error.
563 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
564 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
565 << " failed initialization: "
566 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800567 }
568
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700569 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700570 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
571 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700572
Elliott Hughesa4f94742012-05-29 16:28:38 -0700573 // We only wrap non-Error exceptions; an Error can just be used as-is.
574 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000575 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700576 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700577 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700578}
579
Andreas Gampe87658f32019-04-18 18:39:02 +0000580ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700581 : boot_class_table_(new ClassTable()),
582 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800583 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800584 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700585 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000586 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700587 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000588 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000589 jni_dlsym_lookup_trampoline_(nullptr),
Vladimir Markofa458ac2020-02-12 14:08:07 +0000590 jni_dlsym_lookup_critical_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800591 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800592 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100593 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800594 quick_to_interpreter_bridge_trampoline_(nullptr),
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000595 nterp_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700596 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100597 visibly_initialized_callback_lock_("visibly initialized callback lock"),
598 visibly_initialized_callback_(nullptr),
Vladimir Marko86c87522020-05-11 16:55:55 +0100599 critical_native_code_with_clinit_check_lock_("critical native code with clinit check lock"),
600 critical_native_code_with_clinit_check_(),
Andreas Gampe7dface32017-07-25 21:32:59 -0700601 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
602 // For CHA disabled during Aot, see b/34193647.
603
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700604 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700605 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
606 "Array cache size wrong.");
607 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700608}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700609
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800610void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700611 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800612 if (c2 == nullptr) {
613 LOG(FATAL) << "Could not find class " << descriptor;
614 UNREACHABLE();
615 }
616 if (c1.Get() != c2) {
617 std::ostringstream os1, os2;
618 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
619 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
620 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
621 << ". This is most likely the result of a broken build. Make sure that "
622 << "libcore and art projects match.\n\n"
623 << os1.str() << "\n\n" << os2.str();
624 UNREACHABLE();
625 }
626}
627
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800628bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
629 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800630 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700631
Mathieu Chartiere401d142015-04-22 13:56:20 -0700632 Thread* const self = Thread::Current();
633 Runtime* const runtime = Runtime::Current();
634 gc::Heap* const heap = runtime->GetHeap();
635
Jeff Haodcdc85b2015-12-04 14:06:18 -0800636 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700637 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700638
Mathieu Chartiere401d142015-04-22 13:56:20 -0700639 // Use the pointer size from the runtime since we are probably creating the image.
640 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
641
Elliott Hughes30646832011-10-13 16:59:46 -0700642 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700643 // 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 -0800644 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700645 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700646 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700647 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
648 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000649 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100650 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800651 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100652 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700653 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700654 if (kUseBakerReadBarrier) {
655 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800656 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700657 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700658 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800659 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700660 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700661
Elliott Hughes418d20f2011-09-22 14:00:39 -0700662 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700663 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700664 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700665 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700666 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700667
Ian Rogers23435d02012-09-24 11:23:12 -0700668 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700669 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700670 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800671 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700672 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700673 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000674 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700675
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700676 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800677 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
678 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100679 runtime->SetSentinel(heap->AllocNonMovableObject(self,
680 java_lang_Object.Get(),
681 java_lang_Object->GetObjectSize(),
682 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700683
Igor Murashkin86083f72017-10-27 10:59:04 -0700684 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000685 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700686 // It might seem the lock here is unnecessary, however all the SubtypeCheck
687 // functions are annotated to require locks all the way down.
688 //
689 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
690 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000691 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
692 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700693 }
694
Ian Rogers23435d02012-09-24 11:23:12 -0700695 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700696 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700697 AllocClass(self, java_lang_Class.Get(),
698 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700699 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700700
Roland Levillain0e840272018-08-23 19:55:30 +0100701 // Setup java.lang.String.
702 //
703 // We make this class non-movable for the unlikely case where it were to be
704 // moved by a sticky-bit (minor) collection when using the Generational
705 // Concurrent Copying (CC) collector, potentially creating a stale reference
706 // in the `klass_` field of one of its instances allocated in the Large-Object
707 // Space (LOS) -- see the comment about the dirty card scanning logic in
708 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700709 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700710 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100711 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700712 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000713 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400714
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700715 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700716 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700717 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700718 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000719 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700720
Ian Rogers23435d02012-09-24 11:23:12 -0700721 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700722 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100723 mirror::ObjectArray<mirror::Class>::Alloc(self,
724 object_array_class.Get(),
725 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700726 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100727 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
728 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
729 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
730 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100731 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
732 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700733
Mathieu Chartier6beced42016-11-15 15:51:31 -0800734 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
735 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
736
Vladimir Marko02610552018-06-04 14:38:00 +0100737 // Create array interface entries to populate once we can load system classes.
738 object_array_class->SetIfTable(AllocIfTable(self, 2));
739 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
740
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700741 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100742 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
743 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
744 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
745 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
746 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
747 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
748 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
749 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
750 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700751
Vladimir Marko70e2a762019-07-12 16:49:00 +0100752 // Allocate the primitive array classes. We need only the native pointer
753 // array at this point (int[] or long[], depending on architecture) but
754 // we shall perform the same setup steps for all primitive array classes.
755 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
756 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
757 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
758 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
759 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
760 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
761 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
762 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700763
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700764 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700765
Ian Rogers52813c92012-10-11 11:50:38 -0700766 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700767 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700768 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100769 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100770 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700771 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000772 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700773
Alex Lightd6251582016-10-31 11:12:30 -0700774
775 // Setup dalvik.system.ClassExt
776 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
777 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100778 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000779 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700780
Mathieu Chartier66f19252012-09-18 08:57:04 -0700781 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700782 Handle<mirror::Class> object_array_string(hs.NewHandle(
783 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700784 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700785 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100786 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700787
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000788 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700789 // Create runtime resolution and imt conflict methods.
790 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000791 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
792 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700793
Ian Rogers23435d02012-09-24 11:23:12 -0700794 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
795 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
796 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800797 if (boot_class_path.empty()) {
798 *error_msg = "Boot classpath is empty.";
799 return false;
800 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800801 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800802 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800803 *error_msg = "Null dex file.";
804 return false;
805 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800806 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800807 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700808 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700809
810 // now we can use FindSystemClass
811
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700812 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
813 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700814 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800815 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700816 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000817 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Vladimir Markofa458ac2020-02-12 14:08:07 +0000818 jni_dlsym_lookup_critical_trampoline_ = GetJniDlsymLookupCriticalStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700819 quick_resolution_trampoline_ = GetQuickResolutionStub();
820 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000821 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700822 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000823 nterp_trampoline_ = interpreter::GetNterpEntryPoint();
Alex Light64ad14d2014-08-19 14:23:13 -0700824 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700825
Alex Lightd6251582016-10-31 11:12:30 -0700826 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000827 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800828 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700829 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000830 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800831 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000832 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800833 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700834 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000835 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700836 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
837 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700838
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800839 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
840 // in class_table_.
841 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700842
Vladimir Marko70e2a762019-07-12 16:49:00 +0100843 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
844 // arrays - can't be done until Object has a vtable and component classes are loaded.
845 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
846 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
847 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
848 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
849 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
850 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
851 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
852 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
853 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
854 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
855 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700856
Ian Rogers23435d02012-09-24 11:23:12 -0700857 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700858 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800859 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700860 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800861 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700862 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
863 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100864 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
865 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700866
Vladimir Markob10668c2021-06-10 09:52:53 +0100867 // Check Class[] and Object[]'s interfaces.
868 CHECK_EQ(java_lang_Cloneable.Get(), class_array_class->GetDirectInterface(0));
869 CHECK_EQ(java_io_Serializable.Get(), class_array_class->GetDirectInterface(1));
870 CHECK_EQ(java_lang_Cloneable.Get(), object_array_class->GetDirectInterface(0));
871 CHECK_EQ(java_io_Serializable.Get(), object_array_class->GetDirectInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700872
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700873 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100874 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700875
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800876 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700877
Ian Rogers23435d02012-09-24 11:23:12 -0700878 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100879 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
880 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700881
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700882 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100883 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700884 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100885 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700886
887 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700888 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
889 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100890 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700891
892 // Create java.lang.reflect.Constructor.class root and array root.
893 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
894 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100895 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700896 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
897 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100898 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700899
900 // Create java.lang.reflect.Method.class root and array root.
901 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
902 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100903 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700904 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
905 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100906 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700907
Orion Hodson005ac512017-10-24 15:43:43 +0100908 // Create java.lang.invoke.CallSite.class root
909 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
910 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100911 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100912
Narayan Kamathafa48272016-08-03 12:46:58 +0100913 // Create java.lang.invoke.MethodType.class root
914 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
915 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100916 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100917
918 // Create java.lang.invoke.MethodHandleImpl.class root
919 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
920 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100921 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100922 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100923
Orion Hodsonc069a302017-01-18 09:23:12 +0000924 // Create java.lang.invoke.MethodHandles.Lookup.class root
925 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
926 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100927 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000928
Orion Hodson005ac512017-10-24 15:43:43 +0100929 // Create java.lang.invoke.VarHandle.class root
930 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000931 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100932 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100933
934 // Create java.lang.invoke.FieldVarHandle.class root
935 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
936 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100937 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100938
Orion Hodsondd411962021-06-25 08:55:22 +0100939 // Create java.lang.invoke.StaticFieldVarHandle.class root
940 class_root = FindSystemClass(self, "Ljava/lang/invoke/StaticFieldVarHandle;");
941 CHECK(class_root != nullptr);
942 SetClassRoot(ClassRoot::kJavaLangInvokeStaticFieldVarHandle, class_root);
943
Orion Hodson005ac512017-10-24 15:43:43 +0100944 // Create java.lang.invoke.ArrayElementVarHandle.class root
945 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
946 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100947 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100948
949 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
950 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
951 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100952 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100953
954 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
955 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
956 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100957 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000958
Narayan Kamath000e1882016-10-24 17:14:25 +0100959 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
960 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100961 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100962
Brian Carlstrom1f870082011-08-23 16:02:11 -0700963 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700964 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000965 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800966 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700967 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700968 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
969 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700970 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700971 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700972 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700973 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700974 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700975 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700976 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700977 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700978 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700979 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700980 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700981 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700982
Ian Rogers23435d02012-09-24 11:23:12 -0700983 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700984 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700985 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700986 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100987 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700988
jeffhao8cd6dda2012-02-22 10:15:34 -0800989 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700990 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100991 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100992 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700993 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100994 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
995 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
996 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700997 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000998 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
999 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001000
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001001 // Create conflict tables that depend on the class linker.
1002 runtime->FixupConflictTables();
1003
Ian Rogers98379392014-02-24 16:53:16 -08001004 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001005
Brian Carlstroma004aa92012-02-08 18:05:09 -08001006 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001007
1008 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001009}
1010
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001011static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1012 REQUIRES_SHARED(Locks::mutator_lock_) {
1013 // Find String.<init> -> StringFactory bindings.
1014 ObjPtr<mirror::Class> string_factory_class =
1015 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1016 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001017 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001018 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1019 // Update the primordial thread.
1020 self->InitStringEntryPoints();
1021}
1022
Ian Rogers98379392014-02-24 16:53:16 -08001023void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001024 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001025
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001026 CreateStringInitBindings(self, this);
1027
Brian Carlstrom16192862011-09-12 17:50:06 -07001028 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001029 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001030 // as the types of the field can't be resolved prior to the runtime being
1031 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001032 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001033 Handle<mirror::Class> java_lang_ref_Reference =
1034 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001035 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1036 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001037
Mathieu Chartierc7853442015-03-27 14:35:38 -07001038 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001039 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1040 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001041
Mathieu Chartierc7853442015-03-27 14:35:38 -07001042 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001043 CHECK_STREQ(queue->GetName(), "queue");
1044 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001045
Mathieu Chartierc7853442015-03-27 14:35:38 -07001046 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001047 CHECK_STREQ(queueNext->GetName(), "queueNext");
1048 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001049
Mathieu Chartierc7853442015-03-27 14:35:38 -07001050 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001051 CHECK_STREQ(referent->GetName(), "referent");
1052 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001053
Mathieu Chartierc7853442015-03-27 14:35:38 -07001054 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001055 CHECK_STREQ(zombie->GetName(), "zombie");
1056 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001057
Brian Carlstroma663ea52011-08-19 23:33:41 -07001058 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001059 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001060 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001061 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001062 CHECK(klass != nullptr);
1063 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001064 // note SetClassRoot does additional validation.
1065 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001066 }
1067
Vladimir Marko02610552018-06-04 14:38:00 +01001068 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001069
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001070 // disable the slow paths in FindClass and CreatePrimitiveClass now
1071 // that Object, Class, and Object[] are setup
1072 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001073
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001074 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1075 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1076 // ensure that the class will be initialized.
1077 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001078 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001079
1080 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1081 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1082 // Strange, but don't crash.
1083 LOG(WARNING) << "Could not prepare StackOverflowError.";
1084 self->ClearException();
1085 }
1086 }
1087
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001088 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001089}
1090
Vladimir Markodcfcce42018-06-27 10:00:28 +00001091void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001092 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1093 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001094 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001095 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001096 Handle<mirror::Class> h_class(hs.NewHandle(c));
David Srbecky08110ef2020-05-20 19:33:43 +01001097 if (!EnsureInitialized(self, h_class, true, true)) {
1098 LOG(FATAL) << "Exception when initializing " << h_class->PrettyClass()
1099 << ": " << self->GetException()->Dump();
1100 }
Vladimir Markodcfcce42018-06-27 10:00:28 +00001101 } else {
1102 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001103 }
1104 }
1105}
1106
Vladimir Marko43354742021-02-03 15:37:01 +00001107static void InitializeObjectVirtualMethodHashes(ObjPtr<mirror::Class> java_lang_Object,
1108 PointerSize pointer_size,
1109 /*out*/ ArrayRef<uint32_t> virtual_method_hashes)
1110 REQUIRES_SHARED(Locks::mutator_lock_) {
1111 ArraySlice<ArtMethod> virtual_methods = java_lang_Object->GetVirtualMethods(pointer_size);
1112 DCHECK_EQ(virtual_method_hashes.size(), virtual_methods.size());
1113 for (size_t i = 0; i != virtual_method_hashes.size(); ++i) {
Vladimir Markob4bd92f2021-07-05 12:18:26 +01001114 std::string_view name = virtual_methods[i].GetNameView();
Vladimir Marko43354742021-02-03 15:37:01 +00001115 virtual_method_hashes[i] = ComputeModifiedUtf8Hash(name);
1116 }
1117}
1118
Jeff Haodcdc85b2015-12-04 14:06:18 -08001119struct TrampolineCheckData {
1120 const void* quick_resolution_trampoline;
1121 const void* quick_imt_conflict_trampoline;
1122 const void* quick_generic_jni_trampoline;
1123 const void* quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001124 const void* nterp_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001125 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001126 ArtMethod* m;
1127 bool error;
1128};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001129
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001130bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1131 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001132 CHECK(!init_done_);
1133
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001134 Runtime* const runtime = Runtime::Current();
1135 Thread* const self = Thread::Current();
1136 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001137 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1138 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001139 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1140 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001141 if (!ValidPointerSize(pointer_size_unchecked)) {
1142 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001143 return false;
1144 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001145 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001146 if (!runtime->IsAotCompiler()) {
1147 // Only the Aot compiler supports having an image with a different pointer size than the
1148 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1149 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001150 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001151 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001152 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001153 sizeof(void*));
1154 return false;
1155 }
1156 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001157 DCHECK(!runtime->HasResolutionMethod());
1158 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1159 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1160 runtime->SetImtUnimplementedMethod(
1161 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1162 runtime->SetCalleeSaveMethod(
1163 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1164 CalleeSaveType::kSaveAllCalleeSaves);
1165 runtime->SetCalleeSaveMethod(
1166 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1167 CalleeSaveType::kSaveRefsOnly);
1168 runtime->SetCalleeSaveMethod(
1169 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1170 CalleeSaveType::kSaveRefsAndArgs);
1171 runtime->SetCalleeSaveMethod(
1172 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1173 CalleeSaveType::kSaveEverything);
1174 runtime->SetCalleeSaveMethod(
1175 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1176 CalleeSaveType::kSaveEverythingForClinit);
1177 runtime->SetCalleeSaveMethod(
1178 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1179 CalleeSaveType::kSaveEverythingForSuspendCheck);
1180
Jeff Haodcdc85b2015-12-04 14:06:18 -08001181 std::vector<const OatFile*> oat_files =
1182 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1183 DCHECK(!oat_files.empty());
1184 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001185 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001186 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001187 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1188 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1189 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1190 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001191 nterp_trampoline_ = default_oat_header.GetNterpTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001192 if (kIsDebugBuild) {
1193 // Check that the other images use the same trampoline.
1194 for (size_t i = 1; i < oat_files.size(); ++i) {
1195 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001196 const void* ith_jni_dlsym_lookup_trampoline_ =
1197 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001198 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1199 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001200 const void* ith_quick_resolution_trampoline =
1201 ith_oat_header.GetQuickResolutionTrampoline();
1202 const void* ith_quick_imt_conflict_trampoline =
1203 ith_oat_header.GetQuickImtConflictTrampoline();
1204 const void* ith_quick_generic_jni_trampoline =
1205 ith_oat_header.GetQuickGenericJniTrampoline();
1206 const void* ith_quick_to_interpreter_bridge_trampoline =
1207 ith_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001208 const void* ith_nterp_trampoline =
1209 ith_oat_header.GetNterpTrampoline();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001210 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001211 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001212 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001213 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1214 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001215 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_ ||
1216 ith_nterp_trampoline != nterp_trampoline_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001217 // Make sure that all methods in this image do not contain those trampolines as
1218 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1219 TrampolineCheckData data;
1220 data.error = false;
1221 data.pointer_size = GetImagePointerSize();
1222 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1223 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1224 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1225 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001226 data.nterp_trampoline = ith_nterp_trampoline;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001227 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001228 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1229 if (obj->IsClass()) {
1230 ObjPtr<mirror::Class> klass = obj->AsClass();
1231 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1232 const void* entrypoint =
1233 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1234 if (entrypoint == data.quick_resolution_trampoline ||
1235 entrypoint == data.quick_imt_conflict_trampoline ||
1236 entrypoint == data.quick_generic_jni_trampoline ||
1237 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1238 data.m = &m;
1239 data.error = true;
1240 return;
1241 }
1242 }
1243 }
1244 };
1245 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001246 if (data.error) {
1247 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001248 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001249 *error_msg = "Found an ArtMethod with a bad entrypoint";
1250 return false;
1251 }
1252 }
1253 }
1254 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001255
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001256 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001257 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001258 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001259 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001260
Vladimir Marko024d69f2019-06-13 10:52:32 +01001261 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1262 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1263 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1264 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1265 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1266 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001267
Vladimir Markod1908512018-11-22 14:57:28 +00001268 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001269 // Boot class loader, use a null handle.
1270 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001271 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001272 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001273 /*out*/&dex_files,
1274 error_msg)) {
1275 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001276 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001277 // Append opened dex files at the end.
1278 boot_dex_files_.insert(boot_dex_files_.end(),
1279 std::make_move_iterator(dex_files.begin()),
1280 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001281 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001282 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
Jared Duke95bb9952021-08-11 15:07:25 -07001283 OatDexFile::MadviseDexFileAtLoad(*dex_file);
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001284 }
Vladimir Marko43354742021-02-03 15:37:01 +00001285 InitializeObjectVirtualMethodHashes(GetClassRoot<mirror::Object>(this),
1286 image_pointer_size_,
1287 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Ian Rogers98379392014-02-24 16:53:16 -08001288 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001289
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001290 VLOG(startup) << __FUNCTION__ << " exiting";
1291 return true;
1292}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001293
Vladimir Marko4433c432018-12-04 14:57:47 +00001294void ClassLinker::AddExtraBootDexFiles(
1295 Thread* self,
1296 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1297 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001298 AppendToBootClassPath(self, dex_file.get());
Orion Hodson771708f2021-01-06 15:45:16 +00001299 if (kIsDebugBuild) {
1300 for (const auto& boot_dex_file : boot_dex_files_) {
1301 DCHECK_NE(boot_dex_file->GetLocation(), dex_file->GetLocation());
1302 }
1303 }
Vladimir Marko4433c432018-12-04 14:57:47 +00001304 boot_dex_files_.push_back(std::move(dex_file));
1305 }
1306}
1307
Jeff Hao5872d7c2016-04-27 11:07:41 -07001308bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001309 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001310 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001311 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1312 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001313}
1314
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001315class CHAOnDeleteUpdateClassVisitor {
1316 public:
1317 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1318 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1319 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1320 self_(Thread::Current()) {}
1321
1322 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1323 // This class is going to be unloaded. Tell CHA about it.
1324 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1325 return true;
1326 }
1327 private:
1328 const LinearAlloc* allocator_;
1329 const ClassHierarchyAnalysis* cha_;
1330 const PointerSize pointer_size_;
1331 const Thread* self_;
1332};
1333
Chris Wailes0c61be42018-09-26 17:27:34 -07001334/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001335 * A class used to ensure that all references to strings interned in an AppImage have been
1336 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001337 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001338class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001339 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001340 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1341 const InternTable::UnorderedSet& image_interns)
1342 : space_(space),
1343 image_interns_(image_interns),
1344 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001345
Chris Wailes0c61be42018-09-26 17:27:34 -07001346 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001347 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001348 if (referred_obj != nullptr &&
1349 space_.HasAddress(referred_obj.Ptr()) &&
1350 referred_obj->IsString()) {
1351 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001352 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1353 if (it != image_interns_.end() && it->Read() == referred_str) {
1354 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001355 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001356 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001357 }
1358
Chris Wailes0c61be42018-09-26 17:27:34 -07001359 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001360 mirror::CompressedReference<mirror::Object>* root) const
1361 REQUIRES_SHARED(Locks::mutator_lock_) {
1362 if (!root->IsNull()) {
1363 VisitRoot(root);
1364 }
1365 }
1366
Chris Wailes0c61be42018-09-26 17:27:34 -07001367 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001368 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001369 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001370 }
1371
1372 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001373 void operator()(ObjPtr<mirror::Object> obj,
1374 MemberOffset offset,
1375 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001376 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001377 // References within image or across images don't need a read barrier.
1378 ObjPtr<mirror::Object> referred_obj =
1379 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1380 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001381 }
1382
1383 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1384 ObjPtr<mirror::Reference> ref) const
1385 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001386 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001387 }
1388
Vladimir Marko8e05f092019-06-10 11:10:38 +01001389 size_t GetCount() const {
1390 return count_;
1391 }
1392
1393 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001394 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001395 const InternTable::UnorderedSet& image_interns_;
1396 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001397};
1398
Chris Wailes0c61be42018-09-26 17:27:34 -07001399/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001400 * This function counts references to strings interned in the AppImage.
1401 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001402 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001403size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1404 const InternTable::UnorderedSet& image_interns)
1405 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001406 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1407 const ImageHeader& image_header = space.GetImageHeader();
1408 const uint8_t* target_base = space.GetMemMap()->Begin();
1409 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001410
1411 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1412 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001413
Vladimir Marko8e05f092019-06-10 11:10:38 +01001414 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001415 bitmap->VisitMarkedRange(objects_begin,
1416 objects_end,
1417 [&space, &visitor](mirror::Object* obj)
1418 REQUIRES_SHARED(Locks::mutator_lock_) {
1419 if (space.HasAddress(obj)) {
1420 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001421 obj->VisitReferences</* kVisitNativeRoots= */ true,
1422 kVerifyNone,
1423 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001424 } else {
1425 // Don't visit native roots for non-dex-cache as they can't contain
1426 // native references to strings. This is verified during compilation
1427 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001428 obj->VisitReferences</* kVisitNativeRoots= */ false,
1429 kVerifyNone,
1430 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001431 }
1432 }
1433 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001434 return visitor.GetCount();
1435}
1436
1437template <typename Visitor>
1438static void VisitInternedStringReferences(
1439 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001440 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1441 const uint8_t* target_base = space->Begin();
1442 const ImageSection& sro_section =
1443 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1444 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1445
1446 VLOG(image)
1447 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1448 << num_string_offsets;
1449
1450 const auto* sro_base =
1451 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1452
1453 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1454 uint32_t base_offset = sro_base[offset_index].first;
1455
David Srbecky86d6cd52020-12-02 18:13:10 +00001456 uint32_t raw_member_offset = sro_base[offset_index].second;
1457 DCHECK_ALIGNED(base_offset, 2);
1458 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001459
David Srbecky86d6cd52020-12-02 18:13:10 +00001460 ObjPtr<mirror::Object> obj_ptr =
1461 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1462 MemberOffset member_offset(raw_member_offset);
1463 ObjPtr<mirror::String> referred_string =
1464 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001465 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001466 kWithoutReadBarrier,
1467 /* kIsVolatile= */ false>(member_offset);
1468 DCHECK(referred_string != nullptr);
1469
1470 ObjPtr<mirror::String> visited = visitor(referred_string);
1471 if (visited != referred_string) {
1472 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1473 /* kCheckTransaction= */ false,
1474 kVerifyNone,
1475 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001476 }
1477 }
1478}
1479
1480static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1481 REQUIRES_SHARED(Locks::mutator_lock_) {
1482 InternTable::UnorderedSet image_interns;
1483 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1484 if (section.Size() > 0) {
1485 size_t read_count;
1486 const uint8_t* data = space->Begin() + section.Offset();
1487 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1488 image_set.swap(image_interns);
1489 }
1490 size_t num_recorded_refs = 0u;
1491 VisitInternedStringReferences(
1492 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001493 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1494 REQUIRES_SHARED(Locks::mutator_lock_) {
1495 auto it = image_interns.find(GcRoot<mirror::String>(str));
1496 CHECK(it != image_interns.end());
1497 CHECK(it->Read() == str);
1498 ++num_recorded_refs;
1499 return str;
1500 });
1501 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1502 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001503}
1504
Andreas Gampe2af99022017-04-25 08:32:59 -07001505// new_class_set is the set of classes that were read from the class table section in the image.
1506// If there was no class table section, it is null.
1507// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001508class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001509 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001510 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001511 ClassLinker* class_linker,
1512 gc::space::ImageSpace* space,
1513 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001514 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001515 REQUIRES(!Locks::dex_lock_)
1516 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001517
Chris Wailesfbeef462018-10-19 14:16:35 -07001518 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001519 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001520};
1521
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001522void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001523 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001524 gc::space::ImageSpace* space,
1525 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001526 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001527 REQUIRES(!Locks::dex_lock_)
1528 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001529 ScopedTrace app_image_timing("AppImage:Updating");
1530
Vladimir Marko8e05f092019-06-10 11:10:38 +01001531 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1532 // In debug build, verify the string references before applying
1533 // the Runtime::LoadAppImageStartupCache() option.
1534 VerifyInternedStringReferences(space);
1535 }
1536
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001537 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001538 Runtime* const runtime = Runtime::Current();
1539 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001540 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001541 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001542 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001543 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001544 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001545 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001546 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001547 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001548 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001549 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001550 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001551 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001552 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001553
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001554 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001555 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001556 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001557
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001558 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001559 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001560 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001561 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1562 header.VisitPackedArtMethods([&](ArtMethod& method)
1563 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1564 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1565 if (klass != nullptr) {
1566 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1567 }
1568 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001569 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001570}
1571
Chris Wailesfbeef462018-10-19 14:16:35 -07001572void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001573 // Iterate over the string reference offsets stored in the image and intern
1574 // the strings they point to.
1575 ScopedTrace timing("AppImage:InternString");
1576
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001577 Runtime* const runtime = Runtime::Current();
1578 InternTable* const intern_table = runtime->GetInternTable();
1579
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001580 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1581 // for faster lookup.
1582 // TODO: Optimize with a bitmap or bloom filter
1583 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001584 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001585 REQUIRES_SHARED(Locks::mutator_lock_)
1586 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001587 const size_t non_boot_image_strings = intern_table->CountInterns(
1588 /*visit_boot_images=*/false,
1589 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001590 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001591 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1592 // Visit the smaller of the two sets to compute the intersection.
1593 if (interns.size() < non_boot_image_strings) {
1594 for (auto it = interns.begin(); it != interns.end(); ) {
1595 ObjPtr<mirror::String> string = it->Read();
1596 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1597 if (existing == nullptr) {
1598 existing = intern_table->LookupStrongLocked(string);
1599 }
1600 if (existing != nullptr) {
1601 intern_remap.Put(string.Ptr(), existing.Ptr());
1602 it = interns.erase(it);
1603 } else {
1604 ++it;
1605 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001606 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001607 } else {
1608 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1609 REQUIRES_SHARED(Locks::mutator_lock_)
1610 REQUIRES(Locks::intern_table_lock_) {
1611 auto it = interns.find(root);
1612 if (it != interns.end()) {
1613 ObjPtr<mirror::String> existing = root.Read();
1614 intern_remap.Put(it->Read(), existing.Ptr());
1615 it = interns.erase(it);
1616 }
1617 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1618 }
David Srbecky346fd962020-07-27 16:51:00 +01001619 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001620 if (kIsDebugBuild) {
1621 for (GcRoot<mirror::String>& root : interns) {
1622 ObjPtr<mirror::String> string = root.Read();
1623 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1624 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001625 }
1626 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001627 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001628 intern_table->AddImageStringsToTable(space, func);
1629 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001630 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001631 VisitInternedStringReferences(
1632 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001633 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1634 auto it = intern_remap.find(str.Ptr());
1635 if (it != intern_remap.end()) {
1636 return ObjPtr<mirror::String>(it->second);
1637 }
1638 return str;
1639 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001640 }
1641}
1642
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001643static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1644 const char* location,
1645 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001646 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001647 DCHECK(error_msg != nullptr);
1648 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001649 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001650 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001651 return std::unique_ptr<const DexFile>();
1652 }
1653 std::string inner_error_msg;
1654 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1655 if (dex_file == nullptr) {
1656 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1657 location,
1658 oat_file->GetLocation().c_str(),
1659 inner_error_msg.c_str());
1660 return std::unique_ptr<const DexFile>();
1661 }
1662
1663 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1664 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1665 location,
1666 dex_file->GetLocationChecksum(),
1667 oat_dex_file->GetDexFileLocationChecksum());
1668 return std::unique_ptr<const DexFile>();
1669 }
1670 return dex_file;
1671}
1672
1673bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1674 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1675 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001676 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001677 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001678 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001679 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001680 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001681 dex_caches_object->AsObjectArray<mirror::DexCache>();
1682 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001683 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001684 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1685 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1686 dex_file_location.c_str(),
1687 error_msg);
1688 if (dex_file == nullptr) {
1689 return false;
1690 }
1691 dex_cache->SetDexFile(dex_file.get());
1692 out_dex_files->push_back(std::move(dex_file));
1693 }
1694 return true;
1695}
1696
Andreas Gampe0793bec2016-12-01 11:37:33 -08001697// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1698// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001699class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001700 public:
1701 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1702 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001703 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001704 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1705 DCHECK(obj != nullptr);
1706 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1707 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1708 if (obj->IsClass()) {
1709 auto klass = obj->AsClass();
1710 for (ArtField& field : klass->GetIFields()) {
1711 CHECK_EQ(field.GetDeclaringClass(), klass);
1712 }
1713 for (ArtField& field : klass->GetSFields()) {
1714 CHECK_EQ(field.GetDeclaringClass(), klass);
1715 }
Orion Hodson5880c772020-07-28 20:12:08 +01001716 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001717 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001718 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001719 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001720 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001721 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001722 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001723 }
1724 if (klass->ShouldHaveImt()) {
1725 ImTable* imt = klass->GetImt(pointer_size);
1726 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001727 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001728 }
1729 }
1730 if (klass->ShouldHaveEmbeddedVTable()) {
1731 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001732 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001733 }
1734 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001735 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001736 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1737 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001738 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001739 }
1740 }
1741 }
1742 };
1743 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001744 }
1745
Andreas Gampe0793bec2016-12-01 11:37:33 -08001746 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001747 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001748 : spaces_(heap->GetBootImageSpaces()),
1749 pointer_size_(class_linker->GetImagePointerSize()) {
1750 space_begin_.reserve(spaces_.size());
1751 method_sections_.reserve(spaces_.size());
1752 runtime_method_sections_.reserve(spaces_.size());
1753 for (gc::space::ImageSpace* space : spaces_) {
1754 space_begin_.push_back(space->Begin());
1755 auto& header = space->GetImageHeader();
1756 method_sections_.push_back(&header.GetMethodsSection());
1757 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1758 }
1759 }
1760
Orion Hodson5880c772020-07-28 20:12:08 +01001761 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001762 REQUIRES_SHARED(Locks::mutator_lock_) {
1763 if (m->IsRuntimeMethod()) {
1764 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1765 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1766 } else if (m->IsCopied()) {
1767 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1768 } else if (expected_class != nullptr) {
1769 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1770 }
1771 if (!spaces_.empty()) {
1772 bool contains = false;
1773 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1774 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1775 contains = method_sections_[i]->Contains(offset) ||
1776 runtime_method_sections_[i]->Contains(offset);
1777 }
1778 CHECK(contains) << m << " not found";
1779 }
1780 }
1781
Orion Hodson5880c772020-07-28 20:12:08 +01001782 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1783 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001784 REQUIRES_SHARED(Locks::mutator_lock_) {
1785 CHECK(arr != nullptr);
1786 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1787 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1788 // expected_class == null means we are a dex cache.
1789 if (expected_class != nullptr) {
1790 CHECK(method != nullptr);
1791 }
1792 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001793 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001794 }
1795 }
1796 }
1797
Andreas Gampe0793bec2016-12-01 11:37:33 -08001798 const std::vector<gc::space::ImageSpace*>& spaces_;
1799 const PointerSize pointer_size_;
1800
1801 // Cached sections from the spaces.
1802 std::vector<const uint8_t*> space_begin_;
1803 std::vector<const ImageSection*> method_sections_;
1804 std::vector<const ImageSection*> runtime_method_sections_;
1805};
1806
Andreas Gampebe7af222017-07-25 09:57:28 -07001807static void VerifyAppImage(const ImageHeader& header,
1808 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001809 ClassTable* class_table,
1810 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001811 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001812 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1813 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1814 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1815 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1816 << mirror::Class::PrettyClass(klass);
1817 }
1818 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001819 {
1820 // Verify that all direct interfaces of classes in the class table are also resolved.
1821 std::vector<ObjPtr<mirror::Class>> classes;
1822 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1823 REQUIRES_SHARED(Locks::mutator_lock_) {
1824 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1825 classes.push_back(klass);
1826 }
1827 return true;
1828 };
1829 class_table->Visit(verify_direct_interfaces_in_table);
Andreas Gampebe7af222017-07-25 09:57:28 -07001830 for (ObjPtr<mirror::Class> klass : classes) {
1831 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +01001832 CHECK(klass->GetDirectInterface(i) != nullptr)
Andreas Gampebe7af222017-07-25 09:57:28 -07001833 << klass->PrettyDescriptor() << " iface #" << i;
1834 }
1835 }
1836 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001837}
1838
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001839bool ClassLinker::AddImageSpace(
1840 gc::space::ImageSpace* space,
1841 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001842 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1843 std::string* error_msg) {
1844 DCHECK(out_dex_files != nullptr);
1845 DCHECK(error_msg != nullptr);
1846 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001847 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001848 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001849 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001850 DCHECK(dex_caches_object != nullptr);
1851 Runtime* const runtime = Runtime::Current();
1852 gc::Heap* const heap = runtime->GetHeap();
1853 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001854 // Check that the image is what we are expecting.
1855 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1856 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1857 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1858 image_pointer_size_);
1859 return false;
1860 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001861 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1862 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1863 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1864 expected_image_roots,
1865 header.GetImageRoots()->GetLength());
1866 return false;
1867 }
1868 StackHandleScope<3> hs(self);
1869 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1870 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1871 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1872 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001873 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001874 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1875 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001876 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001877 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001878 *error_msg = StringPrintf("Expected %d class roots but got %d",
1879 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001880 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001881 return false;
1882 }
1883 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001884 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1885 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1886 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001887 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1888 return false;
1889 }
1890 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001891 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001892 if (oat_file->GetOatHeader().GetDexFileCount() !=
1893 static_cast<uint32_t>(dex_caches->GetLength())) {
1894 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1895 "image";
1896 return false;
1897 }
1898
Alex Lighta9bbc082019-11-14 14:51:41 -08001899 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001900 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001901 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1902 dex_file_location.c_str(),
1903 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001904 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001905 return false;
1906 }
1907
David Srbecky86d6cd52020-12-02 18:13:10 +00001908 {
David Srbecky33df0e32021-09-30 14:36:32 +00001909 // Native fields are all null. Initialize them.
David Srbecky86d6cd52020-12-02 18:13:10 +00001910 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky33df0e32021-09-30 14:36:32 +00001911 dex_cache->Initialize(dex_file.get(), class_loader.Get());
David Srbecky86d6cd52020-12-02 18:13:10 +00001912 }
1913 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001914 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001915 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001916 }
1917 out_dex_files->push_back(std::move(dex_file));
1918 }
1919
1920 if (app_image) {
1921 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001922 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001923 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1924 *error_msg = "Unexpected BootClassLoader in app image";
1925 return false;
1926 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001927 }
1928
Orion Hodson5880c772020-07-28 20:12:08 +01001929 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001930 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001931 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001932 }
1933 }
1934
1935 // Set entry point to interpreter if in InterpretOnly mode.
1936 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001937 // Set image methods' entry point to interpreter.
1938 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1939 if (!method.IsRuntimeMethod()) {
1940 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001941 if (!method.IsNative() && !method.IsResolutionMethod()) {
1942 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1943 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001944 }
1945 }
1946 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001947 }
1948
Nicolas Geoffray47171752020-08-31 15:03:20 +01001949 if (!runtime->IsAotCompiler()) {
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001950 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001951 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001952 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01001953 // In the image, the `data` pointer field of the ArtMethod contains the code
1954 // item offset. Change this to the actual pointer to the code item.
1955 if (method.HasCodeItem()) {
1956 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
1957 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01001958 method.SetCodeItem(code_item);
Nicolas Geoffray61673dc2021-11-06 13:58:31 +00001959 // The hotness counter may have changed since we compiled the image, so
1960 // reset it with the runtime value.
1961 method.ResetCounter();
Nicolas Geoffray47171752020-08-31 15:03:20 +01001962 }
1963 // Set image methods' entry point that point to the interpreter bridge to the
1964 // nterp entry point.
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001965 if (method.GetEntryPointFromQuickCompiledCode() == nterp_trampoline_) {
1966 if (can_use_nterp) {
Nicolas Geoffrayb1cf8372021-02-02 13:32:20 +00001967 DCHECK(!NeedsClinitCheckBeforeCall(&method) ||
1968 method.GetDeclaringClass()->IsVisiblyInitialized());
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001969 method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
1970 } else {
1971 method.SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1972 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01001973 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001974 }, space->Begin(), image_pointer_size_);
1975 }
1976
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00001977 if (runtime->IsVerificationSoftFail()) {
1978 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1979 if (!method.IsNative() && method.IsInvokable()) {
1980 method.ClearSkipAccessChecks();
1981 }
1982 }, space->Begin(), image_pointer_size_);
1983 }
1984
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001985 ClassTable* class_table = nullptr;
1986 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001987 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001988 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08001989 }
1990 // If we have a class table section, read it and use it for verification in
1991 // UpdateAppImageClassLoadersAndDexCaches.
1992 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001993 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08001994 const bool added_class_table = class_table_section.Size() > 0u;
1995 if (added_class_table) {
1996 const uint64_t start_time2 = NanoTime();
1997 size_t read_count = 0;
1998 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1999 /*make copy*/false,
2000 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002001 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002002 }
2003 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002004 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002005
2006 {
2007 ScopedTrace trace("AppImage:UpdateClassLoaders");
2008 // Update class loader and resolved strings. If added_class_table is false, the resolved
2009 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002010 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002011 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002012 // Note: We probably don't need the read barrier unless we copy the app image objects into
2013 // the region space.
2014 ObjPtr<mirror::Class> klass(root.Read());
2015 // Do not update class loader for boot image classes where the app image
2016 // class loader is only the initiating loader but not the defining loader.
2017 // Avoid read barrier since we are comparing against null.
2018 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002019 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002020 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002021 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002022 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002023
Vladimir Marko305c38b2018-02-14 11:50:07 +00002024 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002025 // Every class in the app image has initially SubtypeCheckInfo in the
2026 // Uninitialized state.
2027 //
2028 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2029 // after class initialization is complete. The app image ClassStatus as-is
2030 // are almost all ClassStatus::Initialized, and being in the
2031 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2032 //
2033 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2034 //
2035 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002036 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002037 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2038 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002039 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002040 }
2041 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002042 }
2043 if (!oat_file->GetBssGcRoots().empty()) {
2044 // Insert oat file to class table for visiting .bss GC roots.
2045 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002046 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002047
Mathieu Chartier69731002016-03-02 16:08:31 -08002048 if (added_class_table) {
2049 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2050 class_table->AddClassSet(std::move(temp_set));
2051 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002052
Mathieu Chartier69731002016-03-02 16:08:31 -08002053 if (kIsDebugBuild && app_image) {
2054 // This verification needs to happen after the classes have been added to the class loader.
2055 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002056 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002057 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002058 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002059
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002060 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002061 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002062}
2063
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002064void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002065 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2066 // enabling tracing requires the mutator lock, there are no race conditions here.
2067 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002068 Thread* const self = Thread::Current();
2069 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002070 if (kUseReadBarrier) {
2071 // We do not track new roots for CC.
2072 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2073 kVisitRootFlagClearRootLog |
2074 kVisitRootFlagStartLoggingNewRoots |
2075 kVisitRootFlagStopLoggingNewRoots));
2076 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002077 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002078 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2079 // There is 3 GC cases to handle:
2080 // Non moving concurrent:
2081 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002082 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002083 //
2084 // Moving non-concurrent:
2085 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2086 // To prevent missing roots, this case needs to ensure that there is no
2087 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2088 // class which is in the class table.
2089 //
2090 // Moving concurrent:
2091 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2092 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002093 //
2094 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2095 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2096 // these objects.
2097 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002098 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002099 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002100 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002101 for (const ClassLoaderData& data : class_loaders_) {
2102 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2103 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2104 }
2105 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002106 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002107 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002108 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002109 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002110 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002111 // Concurrent moving GC marked new roots through the to-space invariant.
2112 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002113 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002114 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2115 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2116 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2117 if (old_ref != nullptr) {
2118 DCHECK(old_ref->IsClass());
2119 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2120 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2121 // Concurrent moving GC marked new roots through the to-space invariant.
2122 CHECK_EQ(new_ref, old_ref);
2123 }
2124 }
2125 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002126 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002127 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002128 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002129 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002130 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002131 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002132 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002133 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002134 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002135 }
2136 // We deliberately ignore the class roots in the image since we
2137 // handle image roots by using the MS/CMS rescanning of dirty cards.
2138}
2139
Brian Carlstroma663ea52011-08-19 23:33:41 -07002140// Keep in sync with InitCallback. Anything we visit, we need to
2141// reinit references to when reinitializing a ClassLinker from a
2142// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002143void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002144 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002145 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002146 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2147 // unloading if we are marking roots.
2148 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002149}
2150
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002151class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2152 public:
2153 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2154 : visitor_(visitor),
2155 done_(false) {}
2156
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002157 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002158 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002159 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002160 if (!done_ && class_table != nullptr) {
2161 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2162 if (!class_table->Visit(visitor)) {
2163 // If the visitor ClassTable returns false it means that we don't need to continue.
2164 done_ = true;
2165 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002166 }
2167 }
2168
2169 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002170 // Class visitor that limits the class visits from a ClassTable to the classes with
2171 // the provided defining class loader. This filter is used to avoid multiple visits
2172 // of the same class which can be recorded for multiple initiating class loaders.
2173 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2174 public:
2175 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2176 ClassVisitor* visitor)
2177 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2178
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002179 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002180 if (klass->GetClassLoader() != defining_class_loader_) {
2181 return true;
2182 }
2183 return (*visitor_)(klass);
2184 }
2185
Vladimir Marko0984e482019-03-27 16:41:41 +00002186 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002187 ClassVisitor* const visitor_;
2188 };
2189
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002190 ClassVisitor* const visitor_;
2191 // If done is true then we don't need to do any more visiting.
2192 bool done_;
2193};
2194
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002195void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002196 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002197 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2198 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002199 }
2200}
2201
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002202void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002203 Thread* const self = Thread::Current();
2204 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2205 // Not safe to have thread suspension when we are holding a lock.
2206 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002207 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002208 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002209 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002210 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002211 }
2212}
2213
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002214class GetClassesInToVector : public ClassVisitor {
2215 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002216 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002217 classes_.push_back(klass);
2218 return true;
2219 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002220 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002221};
2222
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002223class GetClassInToObjectArray : public ClassVisitor {
2224 public:
2225 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2226 : arr_(arr), index_(0) {}
2227
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002228 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002229 ++index_;
2230 if (index_ <= arr_->GetLength()) {
2231 arr_->Set(index_ - 1, klass);
2232 return true;
2233 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002234 return false;
2235 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002236
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002237 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002238 return index_ <= arr_->GetLength();
2239 }
2240
2241 private:
2242 mirror::ObjectArray<mirror::Class>* const arr_;
2243 int32_t index_;
2244};
2245
2246void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002247 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2248 // is avoiding duplicates.
2249 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002250 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002251 GetClassesInToVector accumulator;
2252 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002253 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002254 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002255 return;
2256 }
2257 }
2258 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002259 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002260 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002261 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002262 // We size the array assuming classes won't be added to the class table during the visit.
2263 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002264 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002265 size_t class_table_size;
2266 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002267 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002268 // Add 100 in case new classes get loaded when we are filling in the object array.
2269 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002270 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002271 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002272 classes.Assign(
2273 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002274 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002275 GetClassInToObjectArray accumulator(classes.Get());
2276 VisitClasses(&accumulator);
2277 if (accumulator.Succeeded()) {
2278 break;
2279 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002280 }
2281 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2282 // If the class table shrank during creation of the clases array we expect null elements. If
2283 // the class table grew then the loop repeats. If classes are created after the loop has
2284 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002285 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002286 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002287 return;
2288 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002289 }
2290 }
2291}
2292
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002293ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002294 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002295 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002296 // CHA unloading analysis is not needed. No negative consequences are expected because
2297 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002298 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002299 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002300 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002301 while (!running_visibly_initialized_callbacks_.empty()) {
2302 std::unique_ptr<VisiblyInitializedCallback> callback(
2303 std::addressof(running_visibly_initialized_callbacks_.front()));
2304 running_visibly_initialized_callbacks_.pop_front();
2305 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002306}
2307
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002308void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002309 Runtime* const runtime = Runtime::Current();
2310 JavaVMExt* const vm = runtime->GetJavaVM();
2311 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002312 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002313 if (runtime->GetJit() != nullptr) {
2314 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2315 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002316 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002317 code_cache->RemoveMethodsIn(self, *data.allocator);
2318 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002319 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002320 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002321 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002322 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002323 // Cleanup references to single implementation ArtMethods that will be deleted.
2324 if (cleanup_cha) {
2325 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2326 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2327 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002328 {
2329 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2330 auto end = critical_native_code_with_clinit_check_.end();
2331 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2332 if (data.allocator->ContainsUnsafe(it->first)) {
2333 it = critical_native_code_with_clinit_check_.erase(it);
2334 } else {
2335 ++it;
2336 }
2337 }
2338 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002339
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002340 delete data.allocator;
2341 delete data.class_table;
2342}
2343
Vladimir Markobcf17522018-06-01 13:14:32 +01002344ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2345 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002346 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002347 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2348 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002349}
2350
David Srbecky86d6cd52020-12-02 18:13:10 +00002351ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002352 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002353 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002354 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002355 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002356 self->AssertPendingOOMException();
2357 return nullptr;
2358 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002359 // Use InternWeak() so that the location String can be collected when the ClassLoader
2360 // with this DexCache is collected.
2361 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002362 if (location == nullptr) {
2363 self->AssertPendingOOMException();
2364 return nullptr;
2365 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002366 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002367 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002368}
2369
David Srbecky33df0e32021-09-30 14:36:32 +00002370ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(
2371 Thread* self, const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
2372 StackHandleScope<1> hs(self);
2373 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00002374 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002375 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002376 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky33df0e32021-09-30 14:36:32 +00002377 dex_cache->Initialize(&dex_file, h_class_loader.Get());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002378 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002379 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002380}
2381
Vladimir Marko70e2a762019-07-12 16:49:00 +01002382template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002383ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2384 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002385 uint32_t class_size,
2386 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002387 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002388 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002389 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002390 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2391 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002392 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002393 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002394 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002395 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002396 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002397}
2398
Vladimir Marko70e2a762019-07-12 16:49:00 +01002399template <bool kMovable>
2400ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2401 ObjPtr<mirror::Class> java_lang_Class,
2402 uint32_t class_size) {
2403 mirror::Class::InitializeClassVisitor visitor(class_size);
2404 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2405}
2406
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002407ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002408 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002409}
2410
Vladimir Marko70e2a762019-07-12 16:49:00 +01002411void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2412 ClassRoot primitive_root,
2413 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002414 // We make this class non-movable for the unlikely case where it were to be
2415 // moved by a sticky-bit (minor) collection when using the Generational
2416 // Concurrent Copying (CC) collector, potentially creating a stale reference
2417 // in the `klass_` field of one of its instances allocated in the Large-Object
2418 // Space (LOS) -- see the comment about the dirty card scanning logic in
2419 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002420 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2421 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2422 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2423 DCHECK(component_type->IsPrimitive());
2424 array_class->SetComponentType(component_type);
2425 SetClassRoot(array_root, array_class);
2426}
2427
2428void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2429 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2430 array_class->SetSuperClass(java_lang_Object);
2431 array_class->SetVTable(java_lang_Object->GetVTable());
2432 array_class->SetPrimitiveType(Primitive::kPrimNot);
2433 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2434 array_class->SetClassFlags(component_type->IsPrimitive()
2435 ? mirror::kClassFlagNoReferenceFields
2436 : mirror::kClassFlagObjectArray);
2437 array_class->SetClassLoader(component_type->GetClassLoader());
2438 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2439 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2440 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2441 array_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002442 DCHECK_EQ(array_class->NumMethods(), 0u);
2443
2444 // don't need to set new_class->SetObjectSize(..)
2445 // because Object::SizeOf delegates to Array::SizeOf
2446
2447 // All arrays have java/lang/Cloneable and java/io/Serializable as
2448 // interfaces. We need to set that up here, so that stuff like
2449 // "instanceof" works right.
2450
2451 // Use the single, global copies of "interfaces" and "iftable"
2452 // (remember not to free them for arrays).
2453 {
2454 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2455 CHECK(array_iftable != nullptr);
2456 array_class->SetIfTable(array_iftable);
2457 }
2458
2459 // Inherit access flags from the component type.
2460 int access_flags = component_type->GetAccessFlags();
2461 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2462 access_flags &= kAccJavaFlagsMask;
2463 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2464 // and remove "interface".
2465 access_flags |= kAccAbstract | kAccFinal;
2466 access_flags &= ~kAccInterface;
Vladimir Marko70e2a762019-07-12 16:49:00 +01002467
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002468 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002469
Vladimir Markobf121912019-06-04 13:49:05 +01002470 // Array classes are fully initialized either during single threaded startup,
2471 // or from a pre-fence visitor, so visibly initialized.
2472 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002473}
2474
2475void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2476 // Do not hold lock on the array class object, the initialization of
2477 // core array classes is done while the process is still single threaded.
2478 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2479 FinishArrayClassSetup(array_class);
2480
2481 std::string temp;
2482 const char* descriptor = array_class->GetDescriptor(&temp);
2483 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2484 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2485 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002486}
2487
Vladimir Markobcf17522018-06-01 13:14:32 +01002488ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002489 Thread* self,
2490 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002491 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002492 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002493}
2494
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002495ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2496 const char* descriptor,
2497 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002498 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002499 if (kIsDebugBuild) {
2500 StackHandleScope<1> hs(self);
2501 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2502 Thread::PoisonObjectPointersIfDebug();
2503 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002504
2505 // For temporary classes we must wait for them to be retired.
2506 if (init_done_ && klass->IsTemp()) {
2507 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002508 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002509 ThrowEarlierClassFailure(klass);
2510 return nullptr;
2511 }
2512 StackHandleScope<1> hs(self);
2513 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2514 ObjectLock<mirror::Class> lock(self, h_class);
2515 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002516 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002517 lock.WaitIgnoringInterrupts();
2518 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002519 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002520 ThrowEarlierClassFailure(h_class.Get());
2521 return nullptr;
2522 }
2523 CHECK(h_class->IsRetired());
2524 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002525 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002526 }
2527
Brian Carlstromaded5f72011-10-07 17:15:04 -07002528 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002529 size_t index = 0;
2530 // Maximum number of yield iterations until we start sleeping.
2531 static const size_t kNumYieldIterations = 1000;
2532 // How long each sleep is in us.
2533 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002534 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002535 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002536 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002537 {
2538 ObjectTryLock<mirror::Class> lock(self, h_class);
2539 // Can not use a monitor wait here since it may block when returning and deadlock if another
2540 // thread has locked klass.
2541 if (lock.Acquired()) {
2542 // Check for circular dependencies between classes, the lock is required for SetStatus.
2543 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2544 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002545 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002546 return nullptr;
2547 }
2548 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002549 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002550 {
2551 // Handle wrapper deals with klass moving.
2552 ScopedThreadSuspension sts(self, kSuspended);
2553 if (index < kNumYieldIterations) {
2554 sched_yield();
2555 } else {
2556 usleep(kSleepDurationUS);
2557 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002558 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002559 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002560 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002561
Vladimir Marko72ab6842017-01-20 19:32:50 +00002562 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002563 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002564 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002565 }
2566 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002567 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002568 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002569 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002570}
2571
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002572using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002573
2574// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002575ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002576 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002577 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002578 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002579 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002580 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002581 return ClassPathEntry(dex_file, dex_class_def);
2582 }
2583 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002584 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002585}
2586
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002587// Helper macro to make sure each class loader lookup call handles the case the
2588// class loader is not recognized, or the lookup threw an exception.
2589#define RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(call_, result_, thread_) \
2590do { \
2591 auto local_call = call_; \
2592 if (!local_call) { \
2593 return false; \
2594 } \
2595 auto local_result = result_; \
2596 if (local_result != nullptr) { \
2597 return true; \
2598 } \
2599 auto local_thread = thread_; \
2600 if (local_thread->IsExceptionPending()) { \
2601 /* Pending exception means there was an error other than */ \
2602 /* ClassNotFound that must be returned to the caller. */ \
2603 return false; \
2604 } \
2605} while (0)
2606
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002607bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2608 Thread* self,
2609 const char* descriptor,
2610 size_t hash,
2611 Handle<mirror::ClassLoader> class_loader,
2612 /*out*/ ObjPtr<mirror::Class>* result) {
2613 ArtField* field =
2614 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
Brad Stenning9c924e82021-10-11 19:09:00 -07002615 return FindClassInSharedLibrariesHelper(soa, self, descriptor, hash, class_loader, field, result);
2616}
2617
2618bool ClassLinker::FindClassInSharedLibrariesHelper(ScopedObjectAccessAlreadyRunnable& soa,
2619 Thread* self,
2620 const char* descriptor,
2621 size_t hash,
2622 Handle<mirror::ClassLoader> class_loader,
2623 ArtField* field,
2624 /*out*/ ObjPtr<mirror::Class>* result) {
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002625 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2626 if (raw_shared_libraries == nullptr) {
2627 return true;
2628 }
2629
2630 StackHandleScope<2> hs(self);
2631 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2632 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2633 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002634 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2635 temp_loader.Assign(loader);
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002636 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2637 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result),
2638 *result,
2639 self);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002640 }
2641 return true;
2642}
2643
Brad Stenning9c924e82021-10-11 19:09:00 -07002644bool ClassLinker::FindClassInSharedLibrariesAfter(ScopedObjectAccessAlreadyRunnable& soa,
2645 Thread* self,
2646 const char* descriptor,
2647 size_t hash,
2648 Handle<mirror::ClassLoader> class_loader,
2649 /*out*/ ObjPtr<mirror::Class>* result) {
2650 ArtField* field = jni::DecodeArtField(
2651 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
2652 return FindClassInSharedLibrariesHelper(soa, self, descriptor, hash, class_loader, field, result);
2653}
2654
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002655bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2656 Thread* self,
2657 const char* descriptor,
2658 size_t hash,
2659 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002660 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002661 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002662 if (IsBootClassLoader(soa, class_loader.Get())) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002663 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2664 FindClassInBootClassLoaderClassPath(self, descriptor, hash, result), *result, self);
Andreas Gampef865ea92015-04-13 22:14:19 -07002665 return true;
2666 }
2667
David Brazdil05909d82018-12-06 16:25:16 +00002668 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002669 // For regular path or dex class loader the search order is:
2670 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002671 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002672 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002673
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002674 // Create a handle as RegisterDexFile may allocate dex caches (and cause thread suspension).
Calin Juravlecdd49122017-07-05 20:09:53 -07002675 StackHandleScope<1> hs(self);
2676 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002677 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2678 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result),
2679 *result,
2680 self);
2681 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2682 FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result),
2683 *result,
2684 self);
2685 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2686 FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader, result),
2687 *result,
2688 self);
Brad Stenning9c924e82021-10-11 19:09:00 -07002689 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2690 FindClassInSharedLibrariesAfter(soa, self, descriptor, hash, class_loader, result),
2691 *result,
2692 self);
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002693 // We did not find a class, but the class loader chain was recognized, so we
2694 // return true.
2695 return true;
Andreas Gampef865ea92015-04-13 22:14:19 -07002696 }
2697
Calin Juravlecdd49122017-07-05 20:09:53 -07002698 if (IsDelegateLastClassLoader(soa, class_loader)) {
2699 // For delegate last, the search order is:
2700 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002701 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002702 // - class loader dex files
2703 // - parent
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002704 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2705 FindClassInBootClassLoaderClassPath(self, descriptor, hash, result), *result, self);
2706 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2707 FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result),
2708 *result,
2709 self);
2710 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2711 FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader, result),
2712 *result,
2713 self);
Brad Stenning9c924e82021-10-11 19:09:00 -07002714 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2715 FindClassInSharedLibrariesAfter(soa, self, descriptor, hash, class_loader, result),
2716 *result,
2717 self);
Calin Juravlecdd49122017-07-05 20:09:53 -07002718
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002719 // Create a handle as RegisterDexFile may allocate dex caches (and cause thread suspension).
Calin Juravlecdd49122017-07-05 20:09:53 -07002720 StackHandleScope<1> hs(self);
2721 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002722 RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION(
2723 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result),
2724 *result,
2725 self);
2726 // We did not find a class, but the class loader chain was recognized, so we
2727 // return true.
2728 return true;
Calin Juravlecdd49122017-07-05 20:09:53 -07002729 }
2730
2731 // Unsupported class loader.
2732 *result = nullptr;
2733 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002734}
2735
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002736#undef RETURN_IF_UNRECOGNIZED_OR_FOUND_OR_EXCEPTION
2737
Andreas Gampe501c3b02019-04-17 21:54:27 +00002738namespace {
2739
2740// Matches exceptions caught in DexFile.defineClass.
2741ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2742 ClassLinker* class_linker)
2743 REQUIRES_SHARED(Locks::mutator_lock_) {
2744 return
2745 // ClassNotFoundException.
2746 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2747 class_linker))
2748 ||
2749 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2750 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2751}
2752
2753// Clear exceptions caught in DexFile.defineClass.
2754ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2755 REQUIRES_SHARED(Locks::mutator_lock_) {
2756 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2757 self->ClearException();
2758 }
2759}
2760
2761} // namespace
2762
Calin Juravle415dc3d2017-06-28 11:03:12 -07002763// Finds the class in the boot class loader.
2764// If the class is found the method returns the resolved class. Otherwise it returns null.
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002765bool ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2766 const char* descriptor,
2767 size_t hash,
2768 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002769 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2770 if (pair.second != nullptr) {
2771 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2772 if (klass != nullptr) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002773 *result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002774 } else {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002775 *result = DefineClass(self,
2776 descriptor,
2777 hash,
2778 ScopedNullHandle<mirror::ClassLoader>(),
2779 *pair.first,
2780 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002781 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002782 if (*result == nullptr) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002783 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002784 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002785 }
2786 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002787 // The boot classloader is always a known lookup.
2788 return true;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002789}
Andreas Gampef865ea92015-04-13 22:14:19 -07002790
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002791bool ClassLinker::FindClassInBaseDexClassLoaderClassPath(
Calin Juravle415dc3d2017-06-28 11:03:12 -07002792 ScopedObjectAccessAlreadyRunnable& soa,
2793 const char* descriptor,
2794 size_t hash,
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002795 Handle<mirror::ClassLoader> class_loader,
2796 /*out*/ ObjPtr<mirror::Class>* result) {
David Brazdil05909d82018-12-06 16:25:16 +00002797 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2798 IsInMemoryDexClassLoader(soa, class_loader) ||
2799 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002800 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002801
Vladimir Marko68c07582021-04-19 16:01:15 +00002802 const DexFile* dex_file = nullptr;
2803 const dex::ClassDef* class_def = nullptr;
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002804 ObjPtr<mirror::Class> ret;
Vladimir Marko68c07582021-04-19 16:01:15 +00002805 auto find_class_def = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2806 const dex::ClassDef* cp_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2807 if (cp_class_def != nullptr) {
2808 dex_file = cp_dex_file;
2809 class_def = cp_class_def;
2810 return false; // Found a class definition, stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002811 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002812 return true; // Continue with the next DexFile.
2813 };
Vladimir Marko68c07582021-04-19 16:01:15 +00002814 VisitClassLoaderDexFiles(soa, class_loader, find_class_def);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002815
Vladimir Marko68c07582021-04-19 16:01:15 +00002816 if (class_def != nullptr) {
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002817 *result = DefineClass(soa.Self(), descriptor, hash, class_loader, *dex_file, *class_def);
2818 if (UNLIKELY(*result == nullptr)) {
Vladimir Marko68c07582021-04-19 16:01:15 +00002819 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2820 FilterDexFileCaughtExceptions(soa.Self(), this);
2821 } else {
2822 DCHECK(!soa.Self()->IsExceptionPending());
2823 }
2824 }
Nicolas Geoffraye8445e52021-09-23 14:10:05 +01002825 // A BaseDexClassLoader is always a known lookup.
2826 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002827}
2828
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002829ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2830 const char* descriptor,
2831 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002832 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002833 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002834 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002835 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002836 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002837 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2838 // for primitive classes that aren't backed by dex files.
2839 return FindPrimitiveClass(descriptor[0]);
2840 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002841 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002842 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002843 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002844 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002845 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002846 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002847 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002848 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002849 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002850 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002851 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002852 return DefineClass(self,
2853 descriptor,
2854 hash,
2855 ScopedNullHandle<mirror::ClassLoader>(),
2856 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002857 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002858 } else {
2859 // The boot class loader is searched ahead of the application class loader, failures are
2860 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2861 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002862 ObjPtr<mirror::Throwable> pre_allocated =
2863 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002864 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002865 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002866 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002867 }
2868 ObjPtr<mirror::Class> result_ptr;
2869 bool descriptor_equals;
2870 if (descriptor[0] == '[') {
2871 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2872 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2873 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2874 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002875 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002876 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002877 bool known_hierarchy =
2878 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2879 if (result_ptr != nullptr) {
2880 // The chain was understood and we found the class. We still need to add the class to
2881 // the class table to protect from racy programs that can try and redefine the path list
2882 // which would change the Class<?> returned for subsequent evaluation of const-class.
2883 DCHECK(known_hierarchy);
2884 DCHECK(result_ptr->DescriptorEquals(descriptor));
2885 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002886 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002887 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002888 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2889 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002890 //
2891 // If the chain was understood but we did not find the class, let the Java-side
2892 // rediscover all this and throw the exception with the right stack trace. Note that
2893 // the Java-side could still succeed for racy programs if another thread is actively
2894 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002895
Alex Light185a4612018-10-04 15:54:25 -07002896 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002897 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002898 // Oops, we can't call into java so we can't run actual class-loader code.
2899 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002900 ObjPtr<mirror::Throwable> pre_allocated =
2901 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2902 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002903 return nullptr;
2904 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002905
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002906 // Inlined DescriptorToDot(descriptor) with extra validation.
2907 //
2908 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2909 // the DescriptorEquals() check below and give a confusing error message. For example,
2910 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2911 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2912 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2913 size_t descriptor_length = strlen(descriptor);
2914 if (UNLIKELY(descriptor[0] != 'L') ||
2915 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2916 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2917 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2918 return nullptr;
2919 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002920
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002921 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2922 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002923 if (known_hierarchy &&
2924 fast_class_not_found_exceptions_ &&
2925 !Runtime::Current()->IsJavaDebuggable()) {
2926 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2927 // debuggable, optimize this path by throwing directly here without going back to Java
2928 // language. This reduces how many ClassNotFoundExceptions happen.
2929 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2930 "%s",
2931 class_name_string.c_str());
2932 } else {
2933 ScopedLocalRef<jobject> class_loader_object(
2934 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2935 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2936 {
2937 ScopedThreadStateChange tsc(self, kNative);
2938 ScopedLocalRef<jobject> class_name_object(
2939 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2940 if (class_name_object.get() == nullptr) {
2941 DCHECK(self->IsExceptionPending()); // OOME.
2942 return nullptr;
2943 }
2944 CHECK(class_loader_object.get() != nullptr);
2945 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2946 WellKnownClasses::java_lang_ClassLoader_loadClass,
2947 class_name_object.get()));
2948 }
2949 if (result.get() == nullptr && !self->IsExceptionPending()) {
2950 // broken loader - throw NPE to be compatible with Dalvik
2951 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2952 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002953 return nullptr;
2954 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002955 result_ptr = soa.Decode<mirror::Class>(result.get());
2956 // Check the name of the returned class.
2957 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002958 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002959 } else {
2960 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002961 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002962 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002963
2964 if (self->IsExceptionPending()) {
2965 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2966 // However, to comply with the RI behavior, first check if another thread succeeded.
2967 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2968 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2969 self->ClearException();
2970 return EnsureResolved(self, descriptor, result_ptr);
2971 }
2972 return nullptr;
2973 }
2974
2975 // Try to insert the class to the class table, checking for mismatch.
2976 ObjPtr<mirror::Class> old;
2977 {
2978 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2979 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2980 old = class_table->Lookup(descriptor, hash);
2981 if (old == nullptr) {
2982 old = result_ptr; // For the comparison below, after releasing the lock.
2983 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002984 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002985 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002986 } // else throw below, after releasing the lock.
2987 }
2988 }
2989 if (UNLIKELY(old != result_ptr)) {
2990 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2991 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01002992 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002993 const char* loader_class_name =
2994 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2995 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2996 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2997 << DescriptorToDot(descriptor) << "\").";
2998 return EnsureResolved(self, descriptor, old);
2999 }
3000 if (UNLIKELY(!descriptor_equals)) {
3001 std::string result_storage;
3002 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3003 std::string loader_storage;
3004 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3005 ThrowNoClassDefFoundError(
3006 "Initiating class loader of type %s returned class %s instead of %s.",
3007 DescriptorToDot(loader_class_name).c_str(),
3008 DescriptorToDot(result_name).c_str(),
3009 DescriptorToDot(descriptor).c_str());
3010 return nullptr;
3011 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003012 // Success.
3013 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003014}
3015
Alex Light270db1c2019-12-03 12:20:01 +00003016// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3017// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3018// like pausing class definition.
3019struct ScopedDefiningClass {
3020 public:
3021 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3022 : self_(self), returned_(false) {
3023 Locks::mutator_lock_->AssertSharedHeld(self_);
3024 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3025 self_->IncrDefineClassCount();
3026 }
3027 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3028 Locks::mutator_lock_->AssertSharedHeld(self_);
3029 CHECK(returned_);
3030 }
3031
3032 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3033 REQUIRES_SHARED(Locks::mutator_lock_) {
3034 CHECK(!returned_);
3035 self_->DecrDefineClassCount();
3036 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3037 Thread::PoisonObjectPointersIfDebug();
3038 returned_ = true;
3039 return h_klass.Get();
3040 }
3041
3042 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3043 REQUIRES_SHARED(Locks::mutator_lock_) {
3044 StackHandleScope<1> hs(self_);
3045 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3046 return Finish(h_klass);
3047 }
3048
3049 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3050 REQUIRES_SHARED(Locks::mutator_lock_) {
3051 ScopedNullHandle<mirror::Class> snh;
3052 return Finish(snh);
3053 }
3054
3055 private:
3056 Thread* self_;
3057 bool returned_;
3058};
3059
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003060ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3061 const char* descriptor,
3062 size_t hash,
3063 Handle<mirror::ClassLoader> class_loader,
3064 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003065 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003066 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003067 StackHandleScope<3> hs(self);
Eric Holk74584e62021-02-18 14:39:17 -08003068 metrics::AutoTimer timer{GetMetrics()->ClassLoadingTotalTime()};
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003069 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003070
Brian Carlstromaded5f72011-10-07 17:15:04 -07003071 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003072 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003073 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003074 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003075 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003076 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003077 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003078 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003079 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003080 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003081 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003082 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003083 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003084 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003085 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003086 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003087 }
3088
Calin Juravle33787682019-07-26 14:27:18 -07003089 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3090 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3091 // public class path then we prevent the definition of the class.
3092 //
3093 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3094 // classpath is not checked.
3095 if (class_loader == nullptr &&
3096 Runtime::Current()->IsAotCompiler() &&
3097 DenyAccessBasedOnPublicSdk(descriptor)) {
3098 ObjPtr<mirror::Throwable> pre_allocated =
3099 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3100 self->SetException(pre_allocated);
3101 return sdc.Finish(nullptr);
3102 }
3103
Alex Lighte9f61032018-09-24 16:04:51 -07003104 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3105 // code to be executed. We put it up here so we can avoid all the allocations associated with
3106 // creating the class. This can happen with (eg) jit threads.
3107 if (!self->CanLoadClasses()) {
3108 // Make sure we don't try to load anything, potentially causing an infinite loop.
3109 ObjPtr<mirror::Throwable> pre_allocated =
3110 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3111 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003112 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003113 }
3114
Andreas Gampefa4333d2017-02-14 11:10:34 -08003115 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003116 // Allocate a class with the status of not ready.
3117 // Interface object should get the right size here. Regular class will
3118 // figure out the right size later and be replaced with one of the right
3119 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003120 if (CanAllocClass()) {
3121 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3122 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003123 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003124 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003125 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003126 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003127 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003128 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003129 }
Alex Lightb0f11922017-01-23 14:25:17 -08003130 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3131 // nothing.
3132 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003133 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003134 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3135 // will only be called once.
3136 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3137 klass,
3138 class_loader,
3139 dex_file,
3140 dex_class_def,
3141 &new_dex_file,
3142 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003143 // Check to see if an exception happened during runtime callbacks. Return if so.
3144 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003145 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003146 }
Alex Lightb0f11922017-01-23 14:25:17 -08003147 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003148 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003149 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003150 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003151 }
3152 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003153 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003154
Jeff Hao848f70a2014-01-15 13:49:50 -08003155 // Mark the string class by setting its access flag.
3156 if (UNLIKELY(!init_done_)) {
3157 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3158 klass->SetStringClass();
3159 }
3160 }
3161
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003162 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003163 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003164 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003165 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003166
Mathieu Chartier590fee92013-09-13 13:46:47 -07003167 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003168 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003169 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003170 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3171 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003172 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003173 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003174
Mathieu Chartierc7853442015-03-27 14:35:38 -07003175 // Load the fields and other things after we are inserted in the table. This is so that we don't
3176 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3177 // other reason is that the field roots are only visited from the class table. So we need to be
3178 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003179 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003180 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003181 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003182 // An exception occured during load, set status to erroneous while holding klass' lock in case
3183 // notification is necessary.
3184 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003185 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003186 }
Alex Light270db1c2019-12-03 12:20:01 +00003187 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003188 }
3189
Brian Carlstromaded5f72011-10-07 17:15:04 -07003190 // Finish loading (if necessary) by finding parents
3191 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003192 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003193 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003194 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003195 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003196 }
Alex Light270db1c2019-12-03 12:20:01 +00003197 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003198 }
3199 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003200
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003201 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003202 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003203 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003204
Brian Carlstromaded5f72011-10-07 17:15:04 -07003205 // Link the class (if necessary)
3206 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003207 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003208 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003209
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003210 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003211 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003212 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003213 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003214 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003215 }
Alex Light270db1c2019-12-03 12:20:01 +00003216 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003217 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003218 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003219 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Markof9e82e52021-10-06 08:34:40 +01003220 CHECK(h_new_class->IsResolved()) << descriptor << " " << h_new_class->GetStatus();
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003221
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003222 // Instrumentation may have updated entrypoints for all methods of all
3223 // classes. However it could not update methods of this class while we
3224 // were loading it. Now the class is resolved, we can update entrypoints
3225 // as required by instrumentation.
3226 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3227 // We must be in the kRunnable state to prevent instrumentation from
3228 // suspending all threads to update entrypoints while we are doing it
3229 // for this class.
3230 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003231 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003232 }
3233
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003234 /*
3235 * We send CLASS_PREPARE events to the debugger from here. The
3236 * definition of "preparation" is creating the static fields for a
3237 * class and initializing them to the standard default values, but not
3238 * executing any code (that comes later, during "initialization").
3239 *
3240 * We did the static preparation in LinkClass.
3241 *
3242 * The class has been prepared and resolved but possibly not yet verified
3243 * at this point.
3244 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003245 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003246
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003247 // Notify native debugger of the new class and its layout.
3248 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3249
Alex Light270db1c2019-12-03 12:20:01 +00003250 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003251}
3252
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003253uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003254 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003255 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003256 size_t num_8 = 0;
3257 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003258 size_t num_32 = 0;
3259 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003260 ClassAccessor accessor(dex_file, dex_class_def);
3261 // We allow duplicate definitions of the same field in a class_data_item
3262 // but ignore the repeated indexes here, b/21868015.
3263 uint32_t last_field_idx = dex::kDexNoIndex;
3264 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3265 uint32_t field_idx = field.GetIndex();
3266 // Ordering enforced by DexFileVerifier.
3267 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3268 if (UNLIKELY(field_idx == last_field_idx)) {
3269 continue;
3270 }
3271 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003272 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003273 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3274 char c = descriptor[0];
3275 switch (c) {
3276 case 'L':
3277 case '[':
3278 num_ref++;
3279 break;
3280 case 'J':
3281 case 'D':
3282 num_64++;
3283 break;
3284 case 'I':
3285 case 'F':
3286 num_32++;
3287 break;
3288 case 'S':
3289 case 'C':
3290 num_16++;
3291 break;
3292 case 'B':
3293 case 'Z':
3294 num_8++;
3295 break;
3296 default:
3297 LOG(FATAL) << "Unknown descriptor: " << c;
3298 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003299 }
3300 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003301 return mirror::Class::ComputeClassSize(false,
3302 0,
3303 num_8,
3304 num_16,
3305 num_32,
3306 num_64,
3307 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003308 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003309}
3310
Alex Lightfc49fec2018-01-16 22:28:36 +00003311// Special case to get oat code without overwriting a trampoline.
3312const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003313 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003314 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003315 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003316 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003317 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003318 if (code != nullptr) {
3319 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003320 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003321
3322 jit::Jit* jit = Runtime::Current()->GetJit();
3323 if (jit != nullptr) {
3324 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3325 if (code != nullptr) {
3326 return code;
3327 }
3328 }
3329
Alex Lightfc49fec2018-01-16 22:28:36 +00003330 if (method->IsNative()) {
3331 // No code and native? Use generic trampoline.
3332 return GetQuickGenericJniStub();
3333 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003334
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003335 if (interpreter::CanRuntimeUseNterp() && CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003336 return interpreter::GetNterpEntryPoint();
3337 }
3338
Alex Lightfc49fec2018-01-16 22:28:36 +00003339 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003340}
3341
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003342bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003343 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003344 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3345 return false;
3346 }
3347
Elliott Hughes956af0f2014-12-11 14:34:28 -08003348 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003349 return true;
3350 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003351
3352 Runtime* runtime = Runtime::Current();
3353 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3354 if (instr->InterpretOnly()) {
3355 return true;
3356 }
3357
3358 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3359 // Doing this check avoids doing compiled/interpreter transitions.
3360 return true;
3361 }
3362
Alex Lightfc588092020-01-23 15:39:08 -08003363 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003364 // Force the use of interpreter when it is required by the debugger.
3365 return true;
3366 }
3367
Alex Light8f34aba2017-10-09 13:46:32 -07003368 if (Thread::Current()->IsAsyncExceptionPending()) {
3369 // Force use of interpreter to handle async-exceptions
3370 return true;
3371 }
3372
Alex Light2d441b12018-06-08 15:33:21 -07003373 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3374 const void* instr_target = instr->GetCodeForInvoke(method);
3375 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3376 return ShouldUseInterpreterEntrypoint(method, instr_target);
3377 }
3378
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003379 if (runtime->IsJavaDebuggable()) {
3380 // For simplicity, we ignore precompiled code and go to the interpreter
3381 // assuming we don't already have jitted code.
3382 // We could look at the oat file where `quick_code` is being defined,
3383 // and check whether it's been compiled debuggable, but we decided to
3384 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003385 jit::Jit* jit = Runtime::Current()->GetJit();
3386 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3387 }
3388
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003389 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003390 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003391 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003392 // since we want to JIT it (at first use) with extra stackmaps for native
3393 // debugging. We keep however all AOT code from the boot image,
3394 // since the JIT-at-first-use is blocking and would result in non-negligible
3395 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003396 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003397 }
3398
3399 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003400}
3401
Vladimir Marko86c87522020-05-11 16:55:55 +01003402void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003403 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003404 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003405 size_t num_direct_methods = klass->NumDirectMethods();
3406 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003407 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003408 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003409 if (UNLIKELY(klass->IsProxyClass())) {
3410 return;
3411 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003412 PointerSize pointer_size = image_pointer_size_;
3413 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3414 klass->GetDirectMethods(pointer_size).end(),
3415 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3416 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3417 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3418 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3419 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3420 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3421 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3422 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3423 lb->first->SetEntryPointFromJni(lb->second);
3424 lb = critical_native_code_with_clinit_check_.erase(lb);
3425 }
3426 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003427 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003428 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003429 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003430 return; // OAT file unavailable.
3431 }
Ian Rogers19846512012-02-24 11:42:47 -08003432 }
Alex Light64ad14d2014-08-19 14:23:13 -07003433
Mathieu Chartierf8322842014-05-16 10:59:25 -07003434 const DexFile& dex_file = klass->GetDexFile();
Ian Rogers97b52f82014-08-14 11:34:07 -07003435 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003436 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3437 klass->GetDexClassDefIndex(),
3438 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003439 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003440 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3441 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003442 if (!method->IsStatic()) {
3443 // Only update static methods.
3444 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003445 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003446 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003447
3448 // In order:
3449 // 1) Check if we have AOT Code.
3450 // 2) Check if we have JIT Code.
3451 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003452 if (has_oat_class) {
3453 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003454 quick_code = oat_method.GetQuickCode();
3455 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003456
Vladimir Markocce414f2019-10-07 08:51:33 +01003457 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003458 if (quick_code == nullptr && jit != nullptr) {
3459 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003460 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003461
3462 if (quick_code == nullptr &&
3463 interpreter::CanRuntimeUseNterp() &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003464 CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003465 quick_code = interpreter::GetNterpEntryPoint();
3466 }
3467
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003468 // Check whether the method is native, in which case it's generic JNI.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003469 if (quick_code == nullptr && method->IsNative()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003470 quick_code = GetQuickGenericJniStub();
3471 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003472 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003473 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3474 // If we have the trampoline or the bridge already, no need to update.
3475 // This saves in not dirtying boot image memory.
3476 continue;
3477 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003478 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003479 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003480 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003481 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003482 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003483 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003484}
3485
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003486// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3487// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003488inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3489 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003490 DCHECK(method != nullptr);
3491 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003492 method->SetEntryPointFromQuickCompiledCodePtrSize(
3493 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3494 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003495}
3496
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003497static void LinkCode(ClassLinker* class_linker,
3498 ArtMethod* method,
3499 const OatFile::OatClass* oat_class,
3500 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003501 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003502 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003503 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003504 // The following code only applies to a non-compiler runtime.
3505 return;
3506 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003507
Ian Rogers62d6c772013-02-27 08:32:07 -08003508 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003509 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003510
Alex Light9139e002015-10-09 15:59:48 -07003511 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003512 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003513 return;
3514 }
Ian Rogers19846512012-02-24 11:42:47 -08003515
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003516 const void* quick_code = nullptr;
3517 if (oat_class != nullptr) {
3518 // Every kind of method should at least get an invoke stub from the oat_method.
3519 // non-abstract methods also get their code pointers.
3520 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3521 quick_code = oat_method.GetQuickCode();
3522 }
3523
3524 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3525
3526 // Note: this mimics the logic in image_writer.cc that installs the resolution
3527 // stub only if we have compiled code and the method needs a class initialization
3528 // check.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003529 if (quick_code == nullptr) {
Nicolas Geoffray4ef36492021-06-16 17:26:51 +01003530 if (method->IsNative()) {
3531 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Nicolas Geoffray4ef36492021-06-16 17:26:51 +01003532 } else {
Nicolas Geoffray6cd7ab32021-07-07 09:35:50 +01003533 // Note we cannot use the nterp entrypoint because we do not know if the
3534 // method will need the slow interpreter for lock verification. This will
3535 // be updated in EnsureSkipAccessChecksMethods.
Nicolas Geoffray4ef36492021-06-16 17:26:51 +01003536 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
3537 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003538 } else if (enter_interpreter) {
3539 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003540 } else if (NeedsClinitCheckBeforeCall(method)) {
3541 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3542 // If we do have code but the method needs a class initialization check before calling
3543 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003544 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3545 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003546 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003547 } else {
3548 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003549 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003550
Ian Rogers62d6c772013-02-27 08:32:07 -08003551 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003552 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3553 // as the extra processing for @CriticalNative is not needed yet.
3554 method->SetEntryPointFromJni(
3555 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Andreas Gampe90546832014-03-12 18:07:19 -07003556
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003557 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003558 // We have a native method here without code. Then it should have the generic JNI
3559 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003560 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003561 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003562 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003563 }
3564}
3565
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003566void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003567 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003568 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003569 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003570 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003571 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003572 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003573 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003574 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003575
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003576 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003577 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003578 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003579 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003580 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003581 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003582 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003583
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003584 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003585 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003586}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003587
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003588LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3589 LinearAlloc* allocator,
3590 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003591 if (length == 0) {
3592 return nullptr;
3593 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003594 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3595 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3596 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003597 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003598 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003599 CHECK(ret != nullptr);
3600 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3601 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003602}
3603
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003604LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3605 LinearAlloc* allocator,
3606 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003607 if (length == 0) {
3608 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003609 }
Vladimir Marko14632852015-08-17 12:07:23 +01003610 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3611 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003612 const size_t storage_size =
3613 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003614 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003615 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003616 CHECK(ret != nullptr);
3617 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003618 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003619 }
3620 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003621}
3622
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003623LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003624 if (class_loader == nullptr) {
3625 return Runtime::Current()->GetLinearAlloc();
3626 }
3627 LinearAlloc* allocator = class_loader->GetAllocator();
3628 DCHECK(allocator != nullptr);
3629 return allocator;
3630}
3631
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003632LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003633 if (class_loader == nullptr) {
3634 return Runtime::Current()->GetLinearAlloc();
3635 }
3636 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3637 LinearAlloc* allocator = class_loader->GetAllocator();
3638 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003639 RegisterClassLoader(class_loader);
3640 allocator = class_loader->GetAllocator();
3641 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003642 }
3643 return allocator;
3644}
3645
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003646void ClassLinker::LoadClass(Thread* self,
3647 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003648 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003649 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003650 ClassAccessor accessor(dex_file,
3651 dex_class_def,
3652 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003653 if (!accessor.HasClassData()) {
3654 return;
3655 }
3656 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003657 {
3658 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3659 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003660 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003661 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003662 // We allow duplicate definitions of the same field in a class_data_item
3663 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003664 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003665 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3666 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003667 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003668 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3669 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003670 accessor.NumInstanceFields());
3671 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003672 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003673 uint32_t last_static_field_idx = 0u;
3674 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003675
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003676 // Methods
3677 bool has_oat_class = false;
3678 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3679 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3680 : OatFile::OatClass::Invalid();
3681 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3682 klass->SetMethodsPtr(
3683 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3684 accessor.NumDirectMethods(),
3685 accessor.NumVirtualMethods());
3686 size_t class_def_method_index = 0;
3687 uint32_t last_dex_method_index = dex::kDexNoIndex;
3688 size_t last_class_def_method_index = 0;
3689
3690 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3691 // methods needs to decode all of the fields.
3692 accessor.VisitFieldsAndMethods([&](
3693 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3694 uint32_t field_idx = field.GetIndex();
3695 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3696 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3697 LoadField(field, klass, &sfields->At(num_sfields));
3698 ++num_sfields;
3699 last_static_field_idx = field_idx;
3700 }
3701 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3702 uint32_t field_idx = field.GetIndex();
3703 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3704 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3705 LoadField(field, klass, &ifields->At(num_ifields));
3706 ++num_ifields;
3707 last_instance_field_idx = field_idx;
3708 }
3709 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3710 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3711 image_pointer_size_);
3712 LoadMethod(dex_file, method, klass, art_method);
3713 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3714 uint32_t it_method_index = method.GetIndex();
3715 if (last_dex_method_index == it_method_index) {
3716 // duplicate case
3717 art_method->SetMethodIndex(last_class_def_method_index);
3718 } else {
3719 art_method->SetMethodIndex(class_def_method_index);
3720 last_dex_method_index = it_method_index;
3721 last_class_def_method_index = class_def_method_index;
3722 }
3723 ++class_def_method_index;
3724 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3725 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3726 class_def_method_index - accessor.NumDirectMethods(),
3727 image_pointer_size_);
3728 LoadMethod(dex_file, method, klass, art_method);
3729 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3730 ++class_def_method_index;
3731 });
3732
3733 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003734 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003735 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3736 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3737 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003738 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3739 if (sfields != nullptr) {
3740 sfields->SetSize(num_sfields);
3741 }
3742 if (ifields != nullptr) {
3743 ifields->SetSize(num_ifields);
3744 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003745 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003746 // Set the field arrays.
3747 klass->SetSFieldsPtr(sfields);
3748 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003749 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003750 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003751 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003752 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003753 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003754 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003755}
3756
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003757void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003758 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003759 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003760 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003761 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003762 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003763
David Brazdil85865692018-10-30 17:26:20 +00003764 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3765 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003766}
3767
Mathieu Chartier268764d2016-09-13 12:09:38 -07003768void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003769 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003770 Handle<mirror::Class> klass,
3771 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003772 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003773 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003774 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003775
Mathieu Chartier268764d2016-09-13 12:09:38 -07003776 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003777 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003778 dst->SetDeclaringClass(klass.Get());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003779
David Brazdil85865692018-10-30 17:26:20 +00003780 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3781 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003782
Ian Rogersdfb325e2013-10-30 01:00:44 -07003783 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003784 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003785 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3786 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003787 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003788 klass->SetFinalizable();
3789 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003790 std::string temp;
3791 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003792 // The Enum class declares a "final" finalize() method to prevent subclasses from
3793 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3794 // subclasses, so we exclude it here.
3795 // We also want to avoid setting the flag on Object, where we know that finalize() is
3796 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003797 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3798 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003799 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003800 }
3801 }
3802 }
3803 } else if (method_name[0] == '<') {
3804 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003805 bool is_init = (strcmp("<init>", method_name) == 0);
3806 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003807 if (UNLIKELY(!is_init && !is_clinit)) {
3808 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3809 } else {
3810 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3811 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003812 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003813 access_flags |= kAccConstructor;
3814 }
3815 }
3816 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003817 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3818 // Check if the native method is annotated with @FastNative or @CriticalNative.
3819 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3820 dex_file, dst->GetClassDef(), dex_method_idx);
3821 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003822 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003823 // Must be done after SetAccessFlags since IsAbstract depends on it.
3824 if (klass->IsInterface() && dst->IsAbstract()) {
3825 dst->CalculateAndSetImtIndex();
3826 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01003827 if (dst->HasCodeItem()) {
3828 DCHECK_NE(method.GetCodeItemOffset(), 0u);
3829 if (Runtime::Current()->IsAotCompiler()) {
3830 dst->SetDataPtrSize(reinterpret_cast32<void*>(method.GetCodeItemOffset()), image_pointer_size_);
3831 } else {
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01003832 dst->SetCodeItem(dst->GetDexFile()->GetCodeItem(method.GetCodeItemOffset()));
Nicolas Geoffray47171752020-08-31 15:03:20 +01003833 }
3834 } else {
3835 dst->SetDataPtrSize(nullptr, image_pointer_size_);
3836 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3837 }
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003838
3839 // Set optimization flags related to the shorty.
Jared Duke968c8132021-11-02 16:47:54 -07003840 uint32_t shorty_length;
3841 const char* shorty = dst->GetShorty(&shorty_length);
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003842 bool all_parameters_are_reference = true;
3843 bool all_parameters_are_reference_or_int = true;
3844 bool return_type_is_fp = (shorty[0] == 'F' || shorty[0] == 'D');
3845
Jared Duke968c8132021-11-02 16:47:54 -07003846 for (size_t i = 1; i < shorty_length; ++i) {
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003847 if (shorty[i] != 'L') {
3848 all_parameters_are_reference = false;
3849 if (shorty[i] == 'F' || shorty[i] == 'D' || shorty[i] == 'J') {
3850 all_parameters_are_reference_or_int = false;
3851 break;
3852 }
3853 }
3854 }
3855
3856 if (!dst->IsNative() && all_parameters_are_reference) {
3857 dst->SetNterpEntryPointFastPathFlag();
3858 }
3859
3860 if (!return_type_is_fp && all_parameters_are_reference_or_int) {
3861 dst->SetNterpInvokeFastPathFlag();
3862 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003863}
3864
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003865void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
David Srbecky33df0e32021-09-30 14:36:32 +00003866 ObjPtr<mirror::DexCache> dex_cache =
3867 AllocAndInitializeDexCache(self, *dex_file, /* class_loader= */ nullptr);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003868 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003869 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003870}
3871
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003872void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003873 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003874 CHECK(dex_file != nullptr);
3875 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3876 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003877 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003878 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003879}
3880
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003881void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003882 ObjPtr<mirror::DexCache> dex_cache,
3883 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003884 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003885 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003886 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003887 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003888 // For app images, the dex cache location may be a suffix of the dex file location since the
3889 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003890 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3891 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003892 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3893 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003894 // The following paths checks don't work on preopt when using boot dex files, where the dex
3895 // cache location is the one on device, and the dex_file's location is the one on host.
3896 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3897 CHECK_GE(dex_file_location.length(), dex_cache_length)
3898 << dex_cache_location << " " << dex_file.GetLocation();
3899 const std::string dex_file_suffix = dex_file_location.substr(
3900 dex_file_location.length() - dex_cache_length,
3901 dex_cache_length);
3902 // Example dex_cache location is SettingsProvider.apk and
3903 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3904 CHECK_EQ(dex_cache_location, dex_file_suffix);
3905 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003906 const OatFile* oat_file =
3907 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003908 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3909 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3910 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3911 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003912 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003913 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
David Srbecky6fbcc292021-02-23 01:05:32 +00003914 const DexCacheData& data = it->second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003915 if (self->IsJWeakCleared(data.weak_root)) {
3916 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003917 it = dex_caches_.erase(it);
3918 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003919 if (initialize_oat_file_data &&
David Srbecky6fbcc292021-02-23 01:05:32 +00003920 it->first->GetOatDexFile() != nullptr &&
3921 it->first->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003922 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003923 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003924 ++it;
3925 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003926 }
Vladimir Markob066d432018-01-03 13:14:37 +00003927 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003928 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003929 }
David Brazdila5c3a802019-03-08 14:59:41 +00003930 // Let hiddenapi assign a domain to the newly registered dex file.
3931 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3932
Vladimir Markocd556b02017-02-03 11:47:34 +00003933 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003934 DexCacheData data;
3935 data.weak_root = dex_cache_jweak;
Vladimir Markocd556b02017-02-03 11:47:34 +00003936 data.class_table = ClassTableForClassLoader(class_loader);
David Srbecky6fbcc292021-02-23 01:05:32 +00003937 AddNativeDebugInfoForDex(self, &dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003938 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003939 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3940 // path dex caches without an image.
3941 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003942 // Make sure that the dex cache holds the classloader live.
3943 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003944 if (class_loader != nullptr) {
3945 // Since we added a strong root to the class table, do the write barrier as required for
3946 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003947 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003948 }
David Srbecky6fbcc292021-02-23 01:05:32 +00003949 bool inserted = dex_caches_.emplace(&dex_file, std::move(data)).second;
3950 CHECK(inserted);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003951}
3952
Alex Light725da8f2020-02-19 14:46:33 -08003953ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3954 return data != nullptr
3955 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003956 : nullptr;
3957}
3958
Alex Light725da8f2020-02-19 14:46:33 -08003959bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003960 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003961 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003962 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003963 CHECK(data != nullptr);
David Srbecky6fbcc292021-02-23 01:05:32 +00003964 DCHECK_EQ(FindDexCacheDataLocked(*dex_cache->GetDexFile()), data);
Alex Light725da8f2020-02-19 14:46:33 -08003965 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003966}
3967
Alex Light07f06212017-06-01 14:01:43 -07003968void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3969 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003970 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003971 Thread* self = Thread::Current();
3972 StackHandleScope<2> hs(self);
3973 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3974 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3975 const DexFile* dex_file = dex_cache->GetDexFile();
3976 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3977 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003978 ReaderMutexLock mu(self, *Locks::dex_lock_);
3979 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3980 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003981 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3982 << "been registered on dex file " << dex_file->GetLocation();
3983 }
3984 ClassTable* table;
3985 {
3986 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3987 table = InsertClassTableForClassLoader(h_class_loader.Get());
3988 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003989 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3990 // a thread holding the dex lock and blocking on a condition variable regarding
3991 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003992 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003993 WriterMutexLock mu(self, *Locks::dex_lock_);
3994 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3995 table->InsertStrongRoot(h_dex_cache.Get());
3996 if (h_class_loader.Get() != nullptr) {
3997 // Since we added a strong root to the class table, do the write barrier as required for
3998 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003999 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004000 }
4001}
4002
Alex Lightde7f8782020-02-24 10:14:22 -08004003static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
4004 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08004005 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08004006 "Attempt to register dex file %s with multiple class loaders",
4007 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08004008}
4009
Vladimir Markocd556b02017-02-03 11:47:34 +00004010ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4011 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004012 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08004013 ObjPtr<mirror::DexCache> old_dex_cache;
4014 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004015 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004016 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004017 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4018 old_dex_cache = DecodeDexCacheLocked(self, old_data);
4019 if (old_dex_cache != nullptr) {
4020 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
4021 return old_dex_cache;
4022 } else {
4023 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
4024 // be thrown when it's safe to do so to simplify this.
4025 registered_with_another_class_loader = true;
4026 }
4027 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004028 }
Alex Light725da8f2020-02-19 14:46:33 -08004029 // We need to have released the dex_lock_ to allocate safely.
4030 if (registered_with_another_class_loader) {
4031 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4032 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07004033 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004034 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004035 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4036 DCHECK(linear_alloc != nullptr);
4037 ClassTable* table;
4038 {
4039 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4040 table = InsertClassTableForClassLoader(class_loader);
4041 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004042 // Don't alloc while holding the lock, since allocation may need to
4043 // suspend all threads and another thread may need the dex_lock_ to
4044 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004045 StackHandleScope<3> hs(self);
4046 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00004047 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004048 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004049 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4050 // a thread holding the dex lock and blocking on a condition variable regarding
4051 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004052 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004053 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004054 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4055 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004056 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
David Srbecky33df0e32021-09-30 14:36:32 +00004057 // Do Initialize while holding dex lock to make sure two threads don't call it
David Srbecky86d6cd52020-12-02 18:13:10 +00004058 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
4059 // DCHECK that the arrays are null.
David Srbecky33df0e32021-09-30 14:36:32 +00004060 h_dex_cache->Initialize(&dex_file, h_class_loader.Get());
Vladimir Markocd556b02017-02-03 11:47:34 +00004061 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004062 }
Alex Light725da8f2020-02-19 14:46:33 -08004063 if (old_dex_cache != nullptr) {
4064 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4065 // If this thread encountered OOME, ignore it.
4066 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
4067 self->ClearException();
4068 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
4069 // dex_lock_.
4070 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
4071 return old_dex_cache;
4072 } else {
4073 registered_with_another_class_loader = true;
4074 }
4075 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004076 }
Alex Light725da8f2020-02-19 14:46:33 -08004077 if (registered_with_another_class_loader) {
4078 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4079 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004080 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004081 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004082 self->AssertPendingOOMException();
4083 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004084 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004085 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004086 if (h_class_loader.Get() != nullptr) {
4087 // Since we added a strong root to the class table, do the write barrier as required for
4088 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004089 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004090 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004091 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
Nicolas Geoffray4f6bb442021-06-02 18:05:51 +01004092 PaletteNotifyDexFileLoaded(dex_file.GetLocation().c_str());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004093 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004094}
4095
Vladimir Markocd556b02017-02-03 11:47:34 +00004096bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004097 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004098 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004099}
4100
Vladimir Markocd556b02017-02-03 11:47:34 +00004101ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4102 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004103 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4104 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004105 if (dex_cache != nullptr) {
4106 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004107 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004108 // Failure, dump diagnostic and abort.
David Srbecky6fbcc292021-02-23 01:05:32 +00004109 for (const auto& entry : dex_caches_) {
4110 const DexCacheData& data = entry.second;
Alex Light725da8f2020-02-19 14:46:33 -08004111 if (DecodeDexCacheLocked(self, &data) != nullptr) {
David Srbecky6fbcc292021-02-23 01:05:32 +00004112 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << entry.first->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004113 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004114 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004115 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
David Srbecky6fbcc292021-02-23 01:05:32 +00004116 << " " << &dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004117 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004118}
4119
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004120ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const OatDexFile& oat_dex_file) {
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004121 ReaderMutexLock mu(self, *Locks::dex_lock_);
4122 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(oat_dex_file);
4123 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
4124 if (dex_cache != nullptr) {
4125 return dex_cache;
4126 }
4127 // Failure, dump diagnostic and abort.
4128 for (const auto& entry : dex_caches_) {
4129 const DexCacheData& data = entry.second;
4130 if (DecodeDexCacheLocked(self, &data) != nullptr) {
4131 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << entry.first->GetLocation();
4132 }
4133 }
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004134 LOG(FATAL) << "Failed to find DexCache for OatDexFile " << oat_dex_file.GetDexFileLocation()
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004135 << " " << &oat_dex_file;
4136 UNREACHABLE();
4137}
4138
Vladimir Markocd556b02017-02-03 11:47:34 +00004139ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4140 const DexFile* dex_file = dex_cache->GetDexFile();
4141 DCHECK(dex_file != nullptr);
4142 ReaderMutexLock mu(self, *Locks::dex_lock_);
David Srbecky6fbcc292021-02-23 01:05:32 +00004143 auto it = dex_caches_.find(dex_file);
4144 if (it != dex_caches_.end()) {
4145 const DexCacheData& data = it->second;
4146 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
4147 if (registered_dex_cache != nullptr) {
4148 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4149 return data.class_table;
Vladimir Markocd556b02017-02-03 11:47:34 +00004150 }
4151 }
4152 return nullptr;
4153}
4154
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004155const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(
Santiago Aboy Solanes4b8ea5d2021-11-19 10:14:54 +00004156 const OatDexFile& oat_dex_file) {
4157 auto it = std::find_if(dex_caches_.begin(), dex_caches_.end(), [&](const auto& entry) {
4158 return entry.first->GetOatDexFile() == &oat_dex_file;
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01004159 });
4160 return it != dex_caches_.end() ? &it->second : nullptr;
4161}
4162
Alex Light725da8f2020-02-19 14:46:33 -08004163const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
David Srbecky6fbcc292021-02-23 01:05:32 +00004164 auto it = dex_caches_.find(&dex_file);
4165 return it != dex_caches_.end() ? &it->second : nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004166}
4167
Vladimir Marko70e2a762019-07-12 16:49:00 +01004168void ClassLinker::CreatePrimitiveClass(Thread* self,
4169 Primitive::Type type,
4170 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004171 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004172 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004173 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4174 // Do not hold lock on the primitive class object, the initialization of
4175 // primitive classes is done while the process is still single threaded.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004176 primitive_class->SetAccessFlagsDuringLinking(kAccPublic | kAccFinal | kAccAbstract);
Vladimir Marko70e2a762019-07-12 16:49:00 +01004177 primitive_class->SetPrimitiveType(type);
4178 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko70e2a762019-07-12 16:49:00 +01004179 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004180 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4181 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004182 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004183 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004184 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004185 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004186 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004187 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004188}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004189
Vladimir Marko02610552018-06-04 14:38:00 +01004190inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4191 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4192}
4193
Brian Carlstrombe977852011-07-19 14:54:54 -07004194// Create an array class (i.e. the class object for the array, not the
4195// array itself). "descriptor" looks like "[C" or "[[[[B" or
4196// "[Ljava/lang/String;".
4197//
4198// If "descriptor" refers to an array of primitives, look up the
4199// primitive type's internally-generated class object.
4200//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004201// "class_loader" is the class loader of the class that's referring to
4202// us. It's used to ensure that we're looking for the element type in
4203// the right context. It does NOT become the class loader for the
4204// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004205//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004206// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004207ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4208 const char* descriptor,
4209 size_t hash,
4210 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004211 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004212 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004213 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004214
4215 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4216 // code to be executed. We put it up here so we can avoid all the allocations associated with
4217 // creating the class. This can happen with (eg) jit threads.
4218 if (!self->CanLoadClasses()) {
4219 // Make sure we don't try to load anything, potentially causing an infinite loop.
4220 ObjPtr<mirror::Throwable> pre_allocated =
4221 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4222 self->SetException(pre_allocated);
4223 return nullptr;
4224 }
4225
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004226 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4227 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004228 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004229 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004230 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004231 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4232 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004233 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004234 DCHECK(self->IsExceptionPending());
4235 return nullptr;
4236 } else {
4237 self->ClearException();
4238 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004239 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004240 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4241 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4242 return nullptr;
4243 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004244 // See if the component type is already loaded. Array classes are
4245 // always associated with the class loader of their underlying
4246 // element type -- an array of Strings goes with the loader for
4247 // java/lang/String -- so we need to look for it there. (The
4248 // caller should have checked for the existence of the class
4249 // before calling here, but they did so with *their* class loader,
4250 // not the component type's loader.)
4251 //
4252 // If we find it, the caller adds "loader" to the class' initiating
4253 // loader list, which should prevent us from going through this again.
4254 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004255 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004256 // are the same, because our caller (FindClass) just did the
4257 // lookup. (Even if we get this wrong we still have correct behavior,
4258 // because we effectively do this lookup again when we add the new
4259 // class to the hash table --- necessary because of possible races with
4260 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004261 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004262 ObjPtr<mirror::Class> new_class =
4263 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004264 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004265 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004266 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004267 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004268 // Core array classes, i.e. Object[], Class[], String[] and primitive
4269 // arrays, have special initialization and they should be found above.
4270 DCHECK(!component_type->IsObjectClass() ||
4271 // Guard from false positives for errors before setting superclass.
4272 component_type->IsErroneousUnresolved());
4273 DCHECK(!component_type->IsStringClass());
4274 DCHECK(!component_type->IsClassClass());
4275 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004276
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004277 // Fill out the fields in the Class.
4278 //
4279 // It is possible to execute some methods against arrays, because
4280 // all arrays are subclasses of java_lang_Object_, so we need to set
4281 // up a vtable. We can just point at the one in java_lang_Object_.
4282 //
4283 // Array classes are simple enough that we don't need to do a full
4284 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004285 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4286 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4287 size_t usable_size)
4288 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004289 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004290 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4291 init_class(obj, usable_size);
4292 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4293 klass->SetComponentType(component_type.Get());
4294 // Do not hold lock for initialization, the fence issued after the visitor
4295 // returns ensures memory visibility together with the implicit consume
4296 // semantics (for all supported architectures) for any thread that loads
4297 // the array class reference from any memory locations afterwards.
4298 FinishArrayClassSetup(klass);
4299 };
4300 auto new_class = hs.NewHandle<mirror::Class>(
4301 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004302 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004303 self->AssertPendingOOMException();
4304 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004305 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004306
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004307 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004308 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004309 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4310 // duplicate events in case of races. Array classes don't really follow dedicated
4311 // load and prepare, anyways.
4312 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4313 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4314
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004315 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004316 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004317 }
4318 // Another thread must have loaded the class after we
4319 // started but before we finished. Abandon what we've
4320 // done.
4321 //
4322 // (Yes, this happens.)
4323
Vladimir Markobcf17522018-06-01 13:14:32 +01004324 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004325}
4326
Vladimir Marko9186b182018-11-06 14:55:54 +00004327ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4328 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004329 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004330 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4331 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4332 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4333 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4334 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4335 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4336 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4337 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4338 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004339 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004340 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004341 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004342 return GetClassRoot(class_root, this);
4343}
4344
4345ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4346 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4347 if (UNLIKELY(result == nullptr)) {
4348 std::string printable_type(PrintableChar(type));
4349 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4350 }
4351 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004352}
4353
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004354ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4355 ObjPtr<mirror::Class> klass,
4356 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004357 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004358 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004359 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004360 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004361 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004362 source += " from ";
4363 source += dex_cache->GetLocation()->ToModifiedUtf8();
4364 }
4365 LOG(INFO) << "Loaded class " << descriptor << source;
4366 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004367 {
4368 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004369 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004370 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004371 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004372 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004373 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004374 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004375 VerifyObject(klass);
4376 class_table->InsertWithHash(klass, hash);
4377 if (class_loader != nullptr) {
4378 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004379 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004380 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004381 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004382 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004383 }
4384 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004385 if (kIsDebugBuild) {
4386 // Test that copied methods correctly can find their holder.
4387 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4388 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4389 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004390 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004391 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004392}
4393
Vladimir Marko1998cd02017-01-13 13:02:58 +00004394void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004395 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4396 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4397 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4398 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004399 }
4400}
4401
Alex Lighte64300b2015-12-15 15:02:47 -08004402// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004403void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004404 LengthPrefixedArray<ArtMethod>* new_methods) {
4405 klass->SetMethodsPtrUnchecked(new_methods,
4406 klass->NumDirectMethods(),
4407 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004408 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004409 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004410}
4411
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004412ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4413 const char* descriptor,
4414 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004415 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4416}
4417
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004418ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4419 const char* descriptor,
4420 size_t hash,
4421 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004422 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4423 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4424 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004425 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004426 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004427 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004428 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004429 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004430 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004431}
4432
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004433class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4434 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004435 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004436
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004437 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004438 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004439 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004440 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004441 if (class_table != nullptr) {
4442 class_table->FreezeSnapshot();
4443 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004444 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004445};
4446
4447void ClassLinker::MoveClassTableToPreZygote() {
4448 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004449 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004450 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004451 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004452}
4453
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004454// Look up classes by hash and descriptor and put all matching ones in the result array.
4455class LookupClassesVisitor : public ClassLoaderVisitor {
4456 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004457 LookupClassesVisitor(const char* descriptor,
4458 size_t hash,
4459 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004460 : descriptor_(descriptor),
4461 hash_(hash),
4462 result_(result) {}
4463
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004464 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004465 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004466 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004467 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004468 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4469 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004470 result_->push_back(klass);
4471 }
4472 }
4473
4474 private:
4475 const char* const descriptor_;
4476 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004477 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004478};
4479
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004480void ClassLinker::LookupClasses(const char* descriptor,
4481 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004482 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004483 Thread* const self = Thread::Current();
4484 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004485 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004486 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004487 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004488 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004489 result.push_back(klass);
4490 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004491 LookupClassesVisitor visitor(descriptor, hash, &result);
4492 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004493}
4494
Alex Lightf1f10492015-10-07 16:08:36 -07004495bool ClassLinker::AttemptSupertypeVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004496 verifier::VerifierDeps* verifier_deps,
Alex Lightf1f10492015-10-07 16:08:36 -07004497 Handle<mirror::Class> klass,
4498 Handle<mirror::Class> supertype) {
4499 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004500 DCHECK(klass != nullptr);
4501 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004502
Alex Lightf1f10492015-10-07 16:08:36 -07004503 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004504 VerifyClass(self, verifier_deps, supertype);
Alex Lightf1f10492015-10-07 16:08:36 -07004505 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004506
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004507 if (supertype->IsVerified()
4508 || supertype->ShouldVerifyAtRuntime()
4509 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004510 // The supertype is either verified, or we soft failed at AOT time.
4511 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004512 return true;
4513 }
4514 // If we got this far then we have a hard failure.
4515 std::string error_msg =
4516 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004517 klass->PrettyDescriptor().c_str(),
4518 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004519 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004520 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004521 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004522 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004523 // Set during VerifyClass call (if at all).
4524 self->ClearException();
4525 }
4526 // Change into a verify error.
4527 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004528 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004529 self->GetException()->SetCause(cause.Get());
4530 }
4531 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4532 if (Runtime::Current()->IsAotCompiler()) {
4533 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4534 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004535 // Need to grab the lock to change status.
4536 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004537 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004538 return false;
4539}
4540
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004541verifier::FailureKind ClassLinker::VerifyClass(Thread* self,
4542 verifier::VerifierDeps* verifier_deps,
4543 Handle<mirror::Class> klass,
4544 verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004545 {
4546 // TODO: assert that the monitor on the Class is held
4547 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004548
Andreas Gampe884f3b82016-03-30 19:52:58 -07004549 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004550 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004551 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004552 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004553 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4554 // case we may see the same status again. b/62912904. This is why the check is
4555 // greater or equal.
4556 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004557 << "Class '" << klass->PrettyClass()
4558 << "' performed an illegal verification state transition from " << old_status
4559 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004560 old_status = klass->GetStatus();
4561 }
jeffhao98eacac2011-09-14 16:11:53 -07004562
Andreas Gampe884f3b82016-03-30 19:52:58 -07004563 // The class might already be erroneous, for example at compile time if we attempted to verify
4564 // this class as a parent to another.
4565 if (klass->IsErroneous()) {
4566 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004567 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004568 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004569
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004570 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004571 if (klass->IsVerified()) {
Nicolas Geoffray80789962021-04-30 16:50:39 +01004572 if (verifier_deps != nullptr &&
4573 verifier_deps->ContainsDexFile(klass->GetDexFile()) &&
4574 !verifier_deps->HasRecordedVerifiedStatus(klass->GetDexFile(), *klass->GetClassDef()) &&
4575 !Runtime::Current()->IsAotCompiler()) {
4576 // If the klass is verified, but `verifier_deps` did not record it, this
4577 // means we are running background verification of a secondary dex file.
4578 // Re-run the verifier to populate `verifier_deps`.
4579 // No need to run the verification when running on the AOT Compiler, as
4580 // the driver handles those multithreaded cases already.
4581 std::string error_msg;
4582 verifier::FailureKind failure =
4583 PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
4584 // We could have soft failures, so just check that we don't have a hard
4585 // failure.
4586 DCHECK_NE(failure, verifier::FailureKind::kHardFailure) << error_msg;
4587 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004588 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004589 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004590
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004591 if (klass->IsVerifiedNeedsAccessChecks()) {
4592 if (!Runtime::Current()->IsAotCompiler()) {
4593 // Mark the class as having a verification attempt to avoid re-running
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004594 // the verifier.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004595 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4596 }
4597 return verifier::FailureKind::kAccessChecksFailure;
4598 }
4599
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004600 // For AOT, don't attempt to re-verify if we have already found we should
4601 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004602 if (klass->ShouldVerifyAtRuntime()) {
4603 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004604 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004605 }
jeffhao98eacac2011-09-14 16:11:53 -07004606
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004607 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4608 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004609
4610 // Skip verification if disabled.
4611 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004612 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004613 UpdateClassAfterVerification(klass, image_pointer_size_, verifier::FailureKind::kNoFailure);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004614 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004615 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004616 }
4617
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004618 VLOG(class_linker) << "Beginning verification for class: "
4619 << klass->PrettyDescriptor()
4620 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4621
Ian Rogers9ffb0392012-09-10 11:56:50 -07004622 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004623 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004624 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4625 // If we have a superclass and we get a hard verification failure we can return immediately.
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004626 if (supertype != nullptr &&
4627 !AttemptSupertypeVerification(self, verifier_deps, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004628 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004629 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004630 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004631
Alex Lightf1f10492015-10-07 16:08:36 -07004632 // Verify all default super-interfaces.
4633 //
4634 // (1) Don't bother if the superclass has already had a soft verification failure.
4635 //
4636 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4637 // recursive initialization by themselves. This is because when an interface is initialized
4638 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4639 // but choose not to for an optimization. If the interfaces is being verified due to a class
4640 // initialization (which would need all the default interfaces to be verified) the class code
4641 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004642 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004643 && !klass->IsInterface()) { // See (2)
4644 int32_t iftable_count = klass->GetIfTableCount();
4645 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4646 // Loop through all interfaces this class has defined. It doesn't matter the order.
4647 for (int32_t i = 0; i < iftable_count; i++) {
4648 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004649 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004650 // We only care if we have default interfaces and can skip if we are already verified...
4651 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4652 continue;
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004653 } else if (UNLIKELY(!AttemptSupertypeVerification(self, verifier_deps, klass, iface))) {
Alex Lightf1f10492015-10-07 16:08:36 -07004654 // We had a hard failure while verifying this interface. Just return immediately.
4655 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004656 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004657 } else if (UNLIKELY(!iface->IsVerified())) {
4658 // We softly failed to verify the iface. Stop checking and clean up.
4659 // Put the iface into the supertype handle so we know what caused us to fail.
4660 supertype.Assign(iface.Get());
4661 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004662 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004663 }
4664 }
4665
Alex Lightf1f10492015-10-07 16:08:36 -07004666 // At this point if verification failed, then supertype is the "first" supertype that failed
4667 // verification (without a specific order). If verification succeeded, then supertype is either
4668 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004669 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004670 supertype.Get() == klass->GetSuperClass() ||
4671 !supertype->IsVerified());
4672
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004673 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004674 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004675 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004676 bool preverified = VerifyClassUsingOatFile(self, dex_file, klass, oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004677
4678 VLOG(class_linker) << "Class preverified status for class "
4679 << klass->PrettyDescriptor()
4680 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4681 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004682 << preverified
4683 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004684
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004685 // If the oat file says the class had an error, re-run the verifier. That way we will either:
4686 // 1) Be successful at runtime, or
4687 // 2) Get a precise error message.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004688 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004689
Ian Rogers62d6c772013-02-27 08:32:07 -08004690 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004691 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004692 if (!preverified) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004693 verifier_failure = PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004694 } else if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks) {
4695 verifier_failure = verifier::FailureKind::kAccessChecksFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004696 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004697
4698 // Verification is done, grab the lock again.
4699 ObjectLock<mirror::Class> lock(self, klass);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004700 self->AssertNoPendingException();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004701
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004702 if (verifier_failure == verifier::FailureKind::kHardFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004703 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004704 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4705 << " because: " << error_msg;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004706 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004707 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004708 return verifier_failure;
jeffhao5cfd6fb2011-09-27 13:54:29 -07004709 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004710
4711 // Make sure all classes referenced by catch blocks are resolved.
4712 ResolveClassExceptionHandlerTypes(klass);
4713
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004714 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004715 if (supertype != nullptr && supertype->ShouldVerifyAtRuntime()) {
4716 // Regardless of our own verification result, we need to verify the class
4717 // at runtime if the super class is not verified. This is required in case
4718 // we generate an app/boot image.
4719 verifier_failure = verifier::FailureKind::kSoftFailure;
4720 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4721 } else if (verifier_failure == verifier::FailureKind::kNoFailure) {
4722 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4723 } else if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4724 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
4725 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4726 } else {
4727 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4728 }
4729 // Notify the compiler about the verification status, in case the class
4730 // was verified implicitly (eg super class of a compiled class). When the
4731 // compiler unloads dex file after compilation, we still want to keep
4732 // verification states.
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004733 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4734 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004735 } else {
4736 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004737 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004738
4739 UpdateClassAfterVerification(klass, image_pointer_size_, verifier_failure);
Nicolas Geoffray08025182016-10-25 17:20:18 +01004740 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004741}
4742
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004743verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004744 verifier::VerifierDeps* verifier_deps,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004745 Handle<mirror::Class> klass,
4746 verifier::HardFailLogMode log_level,
4747 std::string* error_msg) {
4748 Runtime* const runtime = Runtime::Current();
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004749 StackHandleScope<2> hs(self);
4750 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4751 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004752 return verifier::ClassVerifier::VerifyClass(self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004753 verifier_deps,
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004754 dex_cache->GetDexFile(),
4755 klass,
4756 dex_cache,
4757 class_loader,
4758 *klass->GetClassDef(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004759 runtime->GetCompilerCallbacks(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004760 log_level,
4761 Runtime::Current()->GetTargetSdkVersion(),
4762 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004763}
4764
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004765bool ClassLinker::VerifyClassUsingOatFile(Thread* self,
4766 const DexFile& dex_file,
4767 Handle<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004768 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004769 // If we're compiling, we can only verify the class using the oat file if
4770 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004771 // the compilation unit (app - dependencies). We will let the compiler callback
4772 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004773 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004774 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004775 // We are compiling an app (not the image).
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004776 if (!callbacks->CanUseOatStatusForVerification(klass.Get())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004777 return false;
4778 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004779 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004780
Andreas Gampeb40d3612018-06-26 15:49:42 -07004781 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004782 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004783 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004784 return false;
4785 }
4786
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004787 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004788 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004789 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004790 return true;
4791 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004792 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4793 // We return that the clas has already been verified, and the caller should
4794 // check the class status to ensure we run with access checks.
4795 return true;
4796 }
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004797
4798 // Check the class status with the vdex file.
4799 const OatFile* oat_file = oat_dex_file->GetOatFile();
4800 if (oat_file != nullptr) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004801 ClassStatus vdex_status = oat_file->GetVdexFile()->ComputeClassStatus(self, klass);
4802 if (vdex_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
Nicolas Geoffray327cfcf2021-10-12 14:13:25 +01004803 VLOG(verifier) << "Vdex verification success for " << klass->PrettyClass();
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004804 oat_file_class_status = vdex_status;
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004805 return true;
4806 }
4807 }
4808
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004809 // If we only verified a subset of the classes at compile time, we can end up with classes that
4810 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004811 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004812 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004813 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004814 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4815 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4816 << klass->PrettyClass() << " " << dex_file.GetLocation();
4817
Vladimir Marko72ab6842017-01-20 19:32:50 +00004818 if (mirror::Class::IsErroneous(oat_file_class_status)) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004819 // Compile time verification failed with a hard error. We'll re-run
4820 // verification, which might be successful at runtime.
jeffhao1ac29442012-03-26 11:37:32 -07004821 return false;
4822 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004823 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004824 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4825 // not loading the class.
4826 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4827 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004828 return false;
4829 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004830 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004831 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004832 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004833 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004834 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004835}
4836
Alex Light5a559862016-01-29 12:24:48 -08004837void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004838 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004839 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004840 }
4841}
4842
Alex Light5a559862016-01-29 12:24:48 -08004843void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004844 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004845 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004846 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004847 return; // native or abstract method
4848 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004849 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004850 return; // nothing to process
4851 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004852 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004853 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004854 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4855 CatchHandlerIterator iterator(handlers_ptr);
4856 for (; iterator.HasNext(); iterator.Next()) {
4857 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4858 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004859 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004860 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004861 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004862 DCHECK(Thread::Current()->IsExceptionPending());
4863 Thread::Current()->ClearException();
4864 }
4865 }
4866 }
4867 handlers_ptr = iterator.EndDataPointer();
4868 }
4869}
4870
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004871ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4872 jstring name,
4873 jobjectArray interfaces,
4874 jobject loader,
4875 jobjectArray methods,
4876 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004877 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004878
4879 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4880 // code to be executed. We put it up here so we can avoid all the allocations associated with
4881 // creating the class. This can happen with (eg) jit-threads.
4882 if (!self->CanLoadClasses()) {
4883 // Make sure we don't try to load anything, potentially causing an infinite loop.
4884 ObjPtr<mirror::Throwable> pre_allocated =
4885 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4886 self->SetException(pre_allocated);
4887 return nullptr;
4888 }
4889
Alex Light133987d2020-03-26 19:22:12 +00004890 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004891 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004892 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004893 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004894 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004895 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004896 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004897 DCHECK(temp_klass->GetClass() != nullptr);
4898 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004899 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4900 // the methods.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004901 temp_klass->SetAccessFlagsDuringLinking(kAccClassIsProxy | kAccPublic | kAccFinal);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004902 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4903 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4904 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004905 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004906 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004907 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004908 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004909 std::string storage;
4910 const char* descriptor = temp_klass->GetDescriptor(&storage);
4911 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004912
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004913 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004914 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004915
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004916 // Insert the class before loading the fields as the field roots
4917 // (ArtField::declaring_class_) are only visited from the class
4918 // table. There can't be any suspend points between inserting the
4919 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004920 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004921 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004922
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004923 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004924 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004925 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004926 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004927
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004928 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4929 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004930 ArtField& interfaces_sfield = sfields->At(0);
4931 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004932 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004933 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004934
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004935 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004936 ArtField& throws_sfield = sfields->At(1);
4937 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004938 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004939 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004940
Ian Rogers466bb252011-10-14 03:29:56 -07004941 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004942 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004943
Alex Light133987d2020-03-26 19:22:12 +00004944 // The array we get passed contains all methods, including private and static
4945 // ones that aren't proxied. We need to filter those out since only interface
4946 // methods (non-private & virtual) are actually proxied.
4947 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4948 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004949 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004950 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004951 // List of the actual virtual methods this class will have.
4952 std::vector<ArtMethod*> proxied_methods;
4953 std::vector<size_t> proxied_throws_idx;
4954 proxied_methods.reserve(h_methods->GetLength());
4955 proxied_throws_idx.reserve(h_methods->GetLength());
4956 // Filter out to only the non-private virtual methods.
4957 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4958 ArtMethod* m = mirror->GetArtMethod();
4959 if (!m->IsPrivate() && !m->IsStatic()) {
4960 proxied_methods.push_back(m);
4961 proxied_throws_idx.push_back(idx);
4962 }
4963 }
4964 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004965 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4966 // contains an array of all the classes each function is declared to throw.
4967 // This is used to wrap unexpected exceptions in a
4968 // UndeclaredThrowableException exception. This array is in the same order as
4969 // the methods array and like the methods array must be filtered to remove any
4970 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004971 const bool has_filtered_methods =
4972 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4973 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4974 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4975 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4976 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4977 (has_filtered_methods)
4978 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4979 self, original_proxied_throws->GetClass(), num_virtual_methods)
4980 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004981 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4982 self->AssertPendingOOMException();
4983 return nullptr;
4984 }
Alex Light133987d2020-03-26 19:22:12 +00004985 if (has_filtered_methods) {
4986 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
4987 DCHECK_LE(new_idx, orig_idx);
4988 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
4989 }
4990 }
Alex Lighte64300b2015-12-15 15:02:47 -08004991
4992 // Create the methods array.
4993 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4994 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004995 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4996 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004997 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004998 self->AssertPendingOOMException();
4999 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005000 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005001 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005002
5003 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005004 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005005
5006 // Create virtual method using specified prototypes.
5007 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005008 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005009 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005010 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005011 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005012 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5013 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005014 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005015
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005016 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005017 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005018 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005019 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005020 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005021
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005022 // At this point the class is loaded. Publish a ClassLoad event.
5023 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5024 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5025
5026 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005027 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005028 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005029 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005030 // Link the fields and virtual methods, creating vtable and iftables.
5031 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005032 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005033 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005034 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Markoa4d28dd2021-06-30 11:28:06 +01005035 if (!temp_klass->IsErroneous()) {
5036 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
5037 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005038 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005039 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005040 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005041 CHECK(temp_klass->IsRetired());
5042 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005043
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005044 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005045 interfaces_sfield.SetObject<false>(
5046 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005047 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005048 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5049 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005050 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00005051 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005052
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005053 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5054
Vladimir Marko305c38b2018-02-14 11:50:07 +00005055 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5056 // See also ClassLinker::EnsureInitialized().
5057 if (kBitstringSubtypeCheckEnabled) {
5058 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5059 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5060 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5061 }
5062
Vladimir Markobf121912019-06-04 13:49:05 +01005063 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005064 {
5065 // Lock on klass is released. Lock new class object.
5066 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Markobf121912019-06-04 13:49:05 +01005067 // Conservatively go through the ClassStatus::kInitialized state.
5068 callback = MarkClassInitialized(self, klass);
5069 }
5070 if (callback != nullptr) {
5071 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005072 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005073
David Srbecky346fd962020-07-27 16:51:00 +01005074 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07005075 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005076 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005077 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5078
Ian Rogersc2b44472011-12-14 21:17:17 -08005079 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005080 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005081 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08005082 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005083
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005084 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005085 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005086 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005087 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005088 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005089
5090 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005091 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005092 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005093
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005094 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005095 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005096 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005097 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005098 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005099 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005100}
5101
Mathieu Chartiere401d142015-04-22 13:56:20 -07005102void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5103 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005104 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5105 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005106
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005107 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5108 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005109 ArtMethod* proxy_constructor =
5110 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005111 DCHECK(proxy_constructor != nullptr)
5112 << "Could not find <init> method in java.lang.reflect.Proxy";
5113
Jeff Haodb8a6642014-08-14 17:18:52 -07005114 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5115 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005116 DCHECK(out != nullptr);
5117 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005118 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005119 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005120 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005121 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5122 kAccPublic |
5123 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005124 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005125
5126 // Set the original constructor method.
5127 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005128}
5129
Mathieu Chartiere401d142015-04-22 13:56:20 -07005130void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005131 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005132 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5133 CHECK_STREQ(np->GetName(), "<init>");
5134 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005135 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005136}
5137
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005138void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005139 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005140 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005141 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005142 DCHECK(out != nullptr);
5143 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005144
Alex Lighte9dd04f2016-03-16 16:09:45 -07005145 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005146 out->SetDeclaringClass(klass.Get());
Vladimir Markode0d0de2021-03-18 14:12:35 +00005147 // Clear the abstract and default flags to ensure that defaults aren't picked in
Alex Lighte9dd04f2016-03-16 16:09:45 -07005148 // preference to the invocation handler.
Vladimir Markode0d0de2021-03-18 14:12:35 +00005149 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005150 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005151 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5152 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005153 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5154
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005155 // Set the original interface method.
5156 out->SetDataPtrSize(prototype, image_pointer_size_);
5157
Ian Rogers466bb252011-10-14 03:29:56 -07005158 // At runtime the method looks like a reference and argument saving method, clone the code
5159 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005160 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005161}
Jesse Wilson95caa792011-10-12 18:14:17 -04005162
Mathieu Chartiere401d142015-04-22 13:56:20 -07005163void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005164 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005165 CHECK(!prototype->IsFinal());
5166 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005167 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005168
5169 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5170 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005171 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005172 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005173}
5174
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005175bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005176 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005177 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005178 return true;
5179 }
5180 if (!can_init_statics) {
5181 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005182 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005183 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005184 return false;
5185 }
5186 // Check if there are encoded static values needing initialization.
5187 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005188 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005189 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005190 if (dex_class_def->static_values_off_ != 0) {
5191 return false;
5192 }
5193 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005194 }
5195 // If we are a class we need to initialize all interfaces with default methods when we are
5196 // initialized. Check all of them.
5197 if (!klass->IsInterface()) {
5198 size_t num_interfaces = klass->GetIfTableCount();
5199 for (size_t i = 0; i < num_interfaces; i++) {
5200 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5201 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5202 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005203 return false;
5204 }
5205 }
5206 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005207 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005208 if (klass->IsInterface() || !klass->HasSuperClass()) {
5209 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005210 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005211 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005212 if (super_class->IsInitialized()) {
5213 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005214 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005215 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005216}
5217
Mathieu Chartier23369542020-03-04 08:24:11 -08005218bool ClassLinker::InitializeClass(Thread* self,
5219 Handle<mirror::Class> klass,
5220 bool can_init_statics,
5221 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005222 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5223
5224 // Are we already initialized and therefore done?
5225 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5226 // an initialized class will never change its state.
5227 if (klass->IsInitialized()) {
5228 return true;
5229 }
5230
5231 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005232 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005233 return false;
5234 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005235
Ian Rogers7b078e82014-09-10 14:44:24 -07005236 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005237 Runtime* const runtime = Runtime::Current();
5238 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005239 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005240 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005241 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005242
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005243 // Re-check under the lock in case another thread initialized ahead of us.
5244 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005245 return true;
5246 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005247
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005248 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005249 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005250 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005251 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005252 return false;
5253 }
5254
Vladimir Marko72ab6842017-01-20 19:32:50 +00005255 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5256 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005257
5258 if (!klass->IsVerified()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00005259 VerifyClass(self, /*verifier_deps= */ nullptr, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005260 if (!klass->IsVerified()) {
5261 // We failed to verify, expect either the klass to be erroneous or verification failed at
5262 // compile time.
5263 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005264 // The class is erroneous. This may be a verifier error, or another thread attempted
5265 // verification and/or initialization and failed. We can distinguish those cases by
5266 // whether an exception is already pending.
5267 if (self->IsExceptionPending()) {
5268 // Check that it's a VerifyError.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +01005269 DCHECK(IsVerifyError(self->GetException()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005270 } else {
5271 // Check that another thread attempted initialization.
5272 DCHECK_NE(0, klass->GetClinitThreadId());
5273 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5274 // Need to rethrow the previous failure now.
5275 ThrowEarlierClassFailure(klass.Get(), true);
5276 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005277 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005278 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005279 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005280 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005281 self->AssertNoPendingException();
5282 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005283 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005284 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005285 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005286 } else {
5287 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005288 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005289
5290 // A separate thread could have moved us all the way to initialized. A "simple" example
5291 // involves a subclass of the current class being initialized at the same time (which
5292 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005293 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005294 if (klass->IsInitialized()) {
5295 return true;
5296 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005297 }
5298
Vladimir Marko2c64a832018-01-04 11:31:56 +00005299 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005300 // initializing higher up the stack or another thread has beat us
5301 // to initializing and we need to wait. Either way, this
5302 // invocation of InitializeClass will not be responsible for
5303 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005304 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005305 // Could have got an exception during verification.
5306 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005307 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005308 return false;
5309 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005310 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005311 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005312 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005313 return true;
5314 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005315 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005316 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005317 }
5318
Jeff Haoe2e40342017-07-19 10:45:18 -07005319 // Try to get the oat class's status for this class if the oat file is present. The compiler
5320 // tries to validate superclass descriptors, and writes the result into the oat file.
5321 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5322 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5323 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005324 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005325 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5326 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5327 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005328 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005329 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005330 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005331 return false;
5332 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005333 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005334
Vladimir Marko2c64a832018-01-04 11:31:56 +00005335 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005336 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005337
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005338 // From here out other threads may observe that we're initializing and so changes of state
5339 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005340 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005341 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005342
Mathieu Chartier23369542020-03-04 08:24:11 -08005343 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005344 }
5345
Andreas Gampeaf864702019-07-23 14:05:35 -07005346 uint64_t t_sub = 0;
5347
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005348 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005349 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005350 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005351 if (!super_class->IsInitialized()) {
5352 CHECK(!super_class->IsInterface());
5353 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005354 StackHandleScope<1> hs(self);
5355 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005356 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005357 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005358 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005359 if (!super_initialized) {
5360 // The super class was verified ahead of entering initializing, we should only be here if
5361 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005362 // For the case of aot compiler, the super class might also be initializing but we don't
5363 // want to process circular dependencies in pre-compile.
5364 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005365 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005366 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005367 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005368 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005369 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005370 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005371 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005372 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005373 return false;
5374 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005375 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005376 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005377 }
5378
Alex Lighteb7c1442015-08-31 13:17:42 -07005379 if (!klass->IsInterface()) {
5380 // Initialize interfaces with default methods for the JLS.
5381 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005382 // Only setup the (expensive) handle scope if we actually need to.
5383 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005384 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005385 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5386 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005387 handle_scope_iface.Assign(klass->GetDirectInterface(i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005388 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005389 CHECK(handle_scope_iface->IsInterface());
5390 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5391 // We have already done this for this interface. Skip it.
5392 continue;
5393 }
5394 // We cannot just call initialize class directly because we need to ensure that ALL
5395 // interfaces with default methods are initialized. Non-default interface initialization
5396 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005397 // This is not very precise, misses all walking.
5398 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005399 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5400 handle_scope_iface,
5401 can_init_statics,
5402 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005403 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005404 if (!iface_initialized) {
5405 ObjectLock<mirror::Class> lock(self, klass);
5406 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005407 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005408 return false;
5409 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005410 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005411 }
5412 }
5413 }
5414
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005415 const size_t num_static_fields = klass->NumStaticFields();
5416 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005417 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005418 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005419 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005420 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005421 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005422
5423 // Eagerly fill in static fields so that the we don't have to do as many expensive
5424 // Class::FindStaticField in ResolveField.
5425 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005426 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005427 const uint32_t field_idx = field->GetDexFieldIndex();
David Srbecky5de5efe2021-02-15 21:23:00 +00005428 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005429 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005430 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005431 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5432 field,
5433 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5434 hiddenapi::AccessMethod::kNone));
David Srbecky5de5efe2021-02-15 21:23:00 +00005435 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005436 } else {
5437 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005438 }
5439 }
5440
Vladimir Markoe11dd502017-12-08 14:09:45 +00005441 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5442 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005443 this,
5444 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005445 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005446
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005447 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005448 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005449 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005450 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5451 if (!value_it.HasNext()) {
5452 break;
5453 }
5454 ArtField* art_field = ResolveField(field.GetIndex(),
5455 dex_cache,
5456 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005457 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005458 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005459 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005460 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005461 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005462 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005463 if (self->IsExceptionPending()) {
5464 break;
5465 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005466 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005467 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005468 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005469 }
5470 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005471
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005472
Mathieu Chartierda595be2016-08-10 13:57:39 -07005473 if (!self->IsExceptionPending()) {
5474 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5475 if (clinit != nullptr) {
5476 CHECK(can_init_statics);
5477 JValue result;
5478 clinit->Invoke(self, nullptr, 0, &result, "V");
5479 }
5480 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005481 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005482 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005483
Vladimir Markobf121912019-06-04 13:49:05 +01005484 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005485 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005486 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005487 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005488
5489 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005490 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005491 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005492 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005493 } else if (Runtime::Current()->IsTransactionAborted()) {
5494 // The exception thrown when the transaction aborted has been caught and cleared
5495 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005496 VLOG(compiler) << "Return from class initializer of "
5497 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005498 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005499 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005500 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005501 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005502 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005503 if (stats_enabled) {
5504 RuntimeStats* global_stats = runtime->GetStats();
5505 RuntimeStats* thread_stats = self->GetStats();
5506 ++global_stats->class_init_count;
5507 ++thread_stats->class_init_count;
5508 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5509 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5510 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005511 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005512 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005513 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005514 std::string temp;
5515 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005516 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005517 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005518 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005519 }
Vladimir Markobf121912019-06-04 13:49:05 +01005520 if (callback != nullptr) {
5521 callback->MakeVisible(self);
5522 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005523 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005524}
5525
Alex Lighteb7c1442015-08-31 13:17:42 -07005526// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5527// and perform the initialization only on those interfaces that contain default methods.
5528bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5529 Handle<mirror::Class> iface,
5530 bool can_init_statics,
5531 bool can_init_parents) {
5532 CHECK(iface->IsInterface());
5533 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005534 // Only create the (expensive) handle scope if we need it.
5535 if (UNLIKELY(num_direct_ifaces > 0)) {
5536 StackHandleScope<1> hs(self);
5537 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5538 // First we initialize all of iface's super-interfaces recursively.
5539 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005540 ObjPtr<mirror::Class> super_iface = iface->GetDirectInterface(i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005541 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005542 if (!super_iface->HasBeenRecursivelyInitialized()) {
5543 // Recursive step
5544 handle_super_iface.Assign(super_iface);
5545 if (!InitializeDefaultInterfaceRecursive(self,
5546 handle_super_iface,
5547 can_init_statics,
5548 can_init_parents)) {
5549 return false;
5550 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005551 }
5552 }
5553 }
5554
5555 bool result = true;
5556 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5557 // initialize if we don't have default methods.
5558 if (iface->HasDefaultMethods()) {
5559 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5560 }
5561
5562 // Mark that this interface has undergone recursive default interface initialization so we know we
5563 // can skip it on any later class initializations. We do this even if we are not a default
5564 // interface since we can still avoid the traversal. This is purely a performance optimization.
5565 if (result) {
5566 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005567 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5568 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5569 // initialization is a performance optimization (to avoid another idempotent visit
5570 // for other implementing classes/interfaces), and can be revisited later.
5571 ObjectTryLock<mirror::Class> lock(self, iface);
5572 if (lock.Acquired()) {
5573 iface->SetRecursivelyInitialized();
5574 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005575 }
5576 return result;
5577}
5578
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005579bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5580 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005581 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005582 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005583 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005584 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005585 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005586 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005587
5588 // When we wake up, repeat the test for init-in-progress. If
5589 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005590 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005591 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005592 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005593 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005594 return false;
5595 }
5596 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005597 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005598 continue;
5599 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005600 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005601 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005602 // Compile time initialization failed.
5603 return false;
5604 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005605 if (klass->IsErroneous()) {
5606 // The caller wants an exception, but it was thrown in a
5607 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005608 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005609 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005610 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005611 return false;
5612 }
5613 if (klass->IsInitialized()) {
5614 return true;
5615 }
David Sehr709b0702016-10-13 09:12:37 -07005616 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005617 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005618 }
Ian Rogers07140832014-09-30 15:43:59 -07005619 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005620}
5621
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005622static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5623 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005624 ArtMethod* method,
5625 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005626 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005627 DCHECK(Thread::Current()->IsExceptionPending());
5628 DCHECK(!m->IsProxyMethod());
5629 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005630 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5631 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005632 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005633 std::string return_type = dex_file->PrettyType(return_type_idx);
5634 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005635 ThrowWrappedLinkageError(klass.Get(),
5636 "While checking class %s method %s signature against %s %s: "
5637 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005638 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5639 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005640 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005641 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005642 return_type.c_str(), class_loader.c_str());
5643}
5644
5645static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5646 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005647 ArtMethod* method,
5648 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005649 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005650 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005651 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005652 DCHECK(Thread::Current()->IsExceptionPending());
5653 DCHECK(!m->IsProxyMethod());
5654 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005655 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5656 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005657 ThrowWrappedLinkageError(klass.Get(),
5658 "While checking class %s method %s signature against %s %s: "
5659 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005660 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5661 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005662 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005663 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005664 index, arg_type.c_str(), class_loader.c_str());
5665}
5666
5667static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5668 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005669 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005670 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005671 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005672 ThrowLinkageError(klass.Get(),
5673 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005674 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5675 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005676 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005677 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005678 error_msg.c_str());
5679}
5680
Ian Rogersb5fb2072014-12-02 17:22:02 -08005681static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005682 Handle<mirror::Class> klass,
5683 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005684 ArtMethod* method1,
5685 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005686 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005687 {
5688 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005689 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005690 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005691 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005692 return false;
5693 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005694 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005695 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005696 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005697 return false;
5698 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005699 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005700 ThrowSignatureMismatch(klass, super_klass, method1,
5701 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005702 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005703 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005704 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005705 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005706 return false;
5707 }
5708 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005709 const dex::TypeList* types1 = method1->GetParameterTypeList();
5710 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005711 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005712 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005713 ThrowSignatureMismatch(klass, super_klass, method1,
5714 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005715 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005716 return false;
5717 }
5718 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005719 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005720 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005721 ThrowSignatureMismatch(klass, super_klass, method1,
5722 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005723 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005724 return false;
5725 }
5726 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005727 }
5728 uint32_t num_types = types1->Size();
5729 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005730 ThrowSignatureMismatch(klass, super_klass, method1,
5731 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005732 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005733 return false;
5734 }
5735 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005736 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005737 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005738 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005739 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005740 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005741 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005742 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005743 return false;
5744 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005745 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005746 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005747 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005748 if (UNLIKELY(other_param_type == nullptr)) {
5749 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005750 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005751 return false;
5752 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005753 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005754 ThrowSignatureMismatch(klass, super_klass, method1,
5755 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5756 i,
David Sehr709b0702016-10-13 09:12:37 -07005757 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005758 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005759 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005760 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005761 return false;
5762 }
5763 }
5764 return true;
5765}
5766
5767
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005768bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005769 if (klass->IsInterface()) {
5770 return true;
5771 }
Ian Rogers151f2212014-05-06 11:27:27 -07005772 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005773 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005774 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005775 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005776 if (klass->HasSuperClass() &&
5777 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005778 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005779 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005780 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5781 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5782 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005783 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5784 klass,
5785 super_klass,
5786 m,
5787 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005788 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005789 return false;
5790 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005791 }
5792 }
5793 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005794 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005795 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5796 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5797 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005798 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005799 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5800 j, image_pointer_size_);
5801 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5802 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005803 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5804 klass,
5805 super_klass,
5806 m,
5807 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005808 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005809 return false;
5810 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005811 }
5812 }
5813 }
5814 }
5815 return true;
5816}
5817
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005818bool ClassLinker::EnsureInitialized(Thread* self,
5819 Handle<mirror::Class> c,
5820 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005821 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005822 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005823
Mathieu Chartier524507a2014-08-27 15:28:28 -07005824 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005825 // If we've seen an initialized but not visibly initialized class
5826 // many times, request visible initialization.
5827 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5828 // Thanks to the x86 memory model classes skip the initialized status.
5829 DCHECK(c->IsVisiblyInitialized());
5830 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5831 if (self->IncrementMakeVisiblyInitializedCounter()) {
5832 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5833 }
5834 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07005835 return true;
5836 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005837 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5838 //
5839 // Ensure the bitstring is initialized before any of the class initialization
5840 // logic occurs. Once a class initializer starts running, objects can
5841 // escape into the heap and use the subtype checking code.
5842 //
5843 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5844 // can be used as a source for the IsSubClass check, and that all ancestors
5845 // of the class are Assigned (can be used as a target for IsSubClass check)
5846 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005847 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005848 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005849 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005850 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5851 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005852 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005853 if (!success) {
5854 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005855 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Vladimir Markoac576912021-03-31 11:16:22 +01005856 } else {
5857 // There may or may not be an exception pending. If there is, clear it.
5858 // We propagate the exception only if we can initialize fields and parents.
5859 self->ClearException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005860 }
5861 } else {
5862 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005863 }
5864 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005865}
5866
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005867void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5868 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005869 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005870 for (ArtField& field : new_class->GetIFields()) {
5871 if (field.GetDeclaringClass() == temp_class) {
5872 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005873 }
5874 }
5875
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005876 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005877 for (ArtField& field : new_class->GetSFields()) {
5878 if (field.GetDeclaringClass() == temp_class) {
5879 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005880 }
5881 }
5882
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005883 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005884 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005885 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005886 if (method.GetDeclaringClass() == temp_class) {
5887 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005888 }
5889 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005890
5891 // Make sure the remembered set and mod-union tables know that we updated some of the native
5892 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005893 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005894}
5895
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005896void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005897 CHECK(class_loader->GetAllocator() == nullptr);
5898 CHECK(class_loader->GetClassTable() == nullptr);
5899 Thread* const self = Thread::Current();
5900 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005901 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005902 // Create and set the class table.
5903 data.class_table = new ClassTable;
5904 class_loader->SetClassTable(data.class_table);
5905 // Create and set the linear allocator.
5906 data.allocator = Runtime::Current()->CreateLinearAlloc();
5907 class_loader->SetAllocator(data.allocator);
5908 // Add to the list so that we know to free the data later.
5909 class_loaders_.push_back(data);
5910}
5911
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005912ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005913 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005914 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005915 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005916 ClassTable* class_table = class_loader->GetClassTable();
5917 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005918 RegisterClassLoader(class_loader);
5919 class_table = class_loader->GetClassTable();
5920 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005921 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005922 return class_table;
5923}
5924
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005925ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005926 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005927}
5928
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005929static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005930 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005931 while (klass->HasSuperClass()) {
5932 klass = klass->GetSuperClass();
5933 if (klass->ShouldHaveImt()) {
5934 return klass->GetImt(pointer_size);
5935 }
5936 }
5937 return nullptr;
5938}
5939
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005940bool ClassLinker::LinkClass(Thread* self,
5941 const char* descriptor,
5942 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005943 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005944 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005945 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005946
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005947 if (!LinkSuperClass(klass)) {
5948 return false;
5949 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005950 ArtMethod* imt_data[ImTable::kSize];
5951 // If there are any new conflicts compared to super class.
5952 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005953 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005954 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005955 return false;
5956 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005957 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005958 return false;
5959 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005960 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005961 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005962 return false;
5963 }
5964 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005965 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005966
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005967 ImTable* imt = nullptr;
5968 if (klass->ShouldHaveImt()) {
5969 // If there are any new conflicts compared to the super class we can not make a copy. There
5970 // can be cases where both will have a conflict method at the same slot without having the same
5971 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5972 // will possibly create a table that is incorrect for either of the classes.
5973 // Same IMT with new_conflict does not happen very often.
5974 if (!new_conflict) {
5975 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5976 if (super_imt != nullptr) {
5977 bool imt_equals = true;
5978 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5979 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5980 }
5981 if (imt_equals) {
5982 imt = super_imt;
5983 }
5984 }
5985 }
5986 if (imt == nullptr) {
5987 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5988 imt = reinterpret_cast<ImTable*>(
5989 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5990 if (imt == nullptr) {
5991 return false;
5992 }
5993 imt->Populate(imt_data, image_pointer_size_);
5994 }
5995 }
5996
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005997 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5998 // We don't need to retire this class as it has no embedded tables or it was created the
5999 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006000 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006001
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006002 if (klass->ShouldHaveEmbeddedVTable()) {
6003 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006004 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006005 if (klass->ShouldHaveImt()) {
6006 klass->SetImt(imt, image_pointer_size_);
6007 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006008
6009 // Update CHA info based on whether we override methods.
6010 // Have to do this before setting the class as resolved which allows
6011 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006012 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006013 cha_->UpdateAfterLoadingOf(klass);
6014 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006015
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006016 // This will notify waiters on klass that saw the not yet resolved
6017 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006018 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006019 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006020 } else {
6021 CHECK(!klass->IsResolved());
6022 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006023 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006024 Handle<mirror::Class> h_new_class =
6025 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006026 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6027 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6028 // may not see any references to the target space and clean the card for a class if another
6029 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006030 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006031 klass->SetSFieldsPtrUnchecked(nullptr);
6032 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006033 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006034 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006035 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006036 return false;
6037 }
6038
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006039 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6040 ObjectLock<mirror::Class> lock(self, h_new_class);
6041 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006042
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006043 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006044 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006045 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006046 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006047 const ObjPtr<mirror::Class> existing =
6048 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006049 if (class_loader != nullptr) {
6050 // We updated the class in the class table, perform the write barrier so that the GC knows
6051 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006052 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006053 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006054 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006055 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006056 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6057 }
6058 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006059
Mingyao Yang063fc772016-08-02 11:02:54 -07006060 // Update CHA info based on whether we override methods.
6061 // Have to do this before setting the class as resolved which allows
6062 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006063 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006064 cha_->UpdateAfterLoadingOf(h_new_class);
6065 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006066
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006067 // This will notify waiters on temp class that saw the not yet resolved class in the
6068 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006069 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006070
Vladimir Marko2c64a832018-01-04 11:31:56 +00006071 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006072 // This will notify waiters on new_class that saw the not yet resolved
6073 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006074 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006075 // Return the new class.
6076 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006077 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006078 return true;
6079}
6080
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006081bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006082 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006083 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006084 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6085 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006086 // Check that a class does not inherit from itself directly.
6087 //
6088 // TODO: This is a cheap check to detect the straightforward case
6089 // of a class extending itself (b/28685551), but we should do a
6090 // proper cycle detection on loaded classes, to detect all cases
6091 // of class circularity errors (b/28830038).
6092 if (super_class_idx == class_def.class_idx_) {
6093 ThrowClassCircularityError(klass.Get(),
6094 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006095 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006096 return false;
6097 }
6098
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006099 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006100 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006101 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006102 return false;
6103 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006104 // Verify
6105 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006106 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006107 super_class->PrettyDescriptor().c_str(),
6108 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006109 return false;
6110 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006111 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006112 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006113 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006114 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006115 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006116 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006117 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006118 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006119 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006120 DCHECK(Thread::Current()->IsExceptionPending());
6121 return false;
6122 }
6123 // Verify
6124 if (!klass->CanAccess(interface)) {
6125 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006126 ThrowIllegalAccessError(klass.Get(),
6127 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006128 interface->PrettyDescriptor().c_str(),
6129 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006130 return false;
6131 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006132 }
6133 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006134 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006135 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006136 return true;
6137}
6138
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006139bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006140 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006141 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006142 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6143 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006144 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006145 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006146 return false;
6147 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006148 return true;
6149 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006150 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006151 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006152 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006153 return false;
6154 }
6155 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006156 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006157 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6158 return false;
6159 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006160 if (super->IsFinal()) {
6161 ThrowVerifyError(klass.Get(),
6162 "Superclass %s of %s is declared final",
6163 super->PrettyDescriptor().c_str(),
6164 klass->PrettyDescriptor().c_str());
6165 return false;
6166 }
6167 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006168 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006169 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006170 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006171 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006172 return false;
6173 }
6174 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006175 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006176 super->PrettyDescriptor().c_str(),
6177 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006178 return false;
6179 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006180
Brian Carlstromf3632832014-05-20 15:36:53 -07006181 // Inherit kAccClassIsFinalizable from the superclass in case this
6182 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006183 if (super->IsFinalizable()) {
6184 klass->SetFinalizable();
6185 }
6186
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006187 // Inherit class loader flag form super class.
6188 if (super->IsClassLoaderClass()) {
6189 klass->SetClassLoaderClass();
6190 }
6191
Elliott Hughes2da50362011-10-10 16:57:08 -07006192 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006193 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006194 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006195 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006196 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006197 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006198 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006199 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006200 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006201 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006202 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006203 return false;
6204 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006205
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006206 if (kIsDebugBuild) {
6207 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006208 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006209 CHECK(super->IsResolved());
6210 super = super->GetSuperClass();
6211 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006212 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006213 return true;
6214}
6215
Vladimir Marko782fb712020-12-23 12:47:31 +00006216// A wrapper class representing the result of a method translation used for linking methods and
6217// updating superclass default methods. For each method in a classes vtable there are 4 states it
6218// could be in:
6219// 1) No translation is necessary. In this case there is no MethodTranslation object for it. This
6220// is the standard case and is true when the method is not overridable by a default method,
6221// the class defines a concrete implementation of the method, the default method implementation
6222// remains the same, or an abstract method stayed abstract.
6223// 2) The method must be translated to a different default method. We note this with
6224// CreateTranslatedMethod.
6225// 3) The method must be replaced with a conflict method. This happens when a superclass
6226// implements an interface with a default method and this class implements an unrelated
6227// interface that also defines that default method. We note this with CreateConflictingMethod.
6228// 4) The method must be replaced with an abstract miranda method. This happens when a superclass
6229// implements an interface with a default method and this class implements a subinterface of
6230// the superclass's interface which declares the default method abstract. We note this with
6231// CreateAbstractMethod.
6232//
6233// When a method translation is unnecessary (case #1), we don't put it into the
6234// default_translation maps. So an instance of MethodTranslation must be in one of #2-#4.
6235class ClassLinker::MethodTranslation {
6236 public:
6237 MethodTranslation() : translation_(nullptr), type_(Type::kInvalid) {}
6238
6239 // This slot must become a default conflict method.
6240 static MethodTranslation CreateConflictingMethod() {
6241 return MethodTranslation(Type::kConflict, /*translation=*/nullptr);
6242 }
6243
6244 // This slot must become an abstract method.
6245 static MethodTranslation CreateAbstractMethod() {
6246 return MethodTranslation(Type::kAbstract, /*translation=*/nullptr);
6247 }
6248
6249 // Use the given method as the current value for this vtable slot during translation.
6250 static MethodTranslation CreateTranslatedMethod(ArtMethod* new_method) {
6251 return MethodTranslation(Type::kTranslation, new_method);
6252 }
6253
6254 // Returns true if this is a method that must become a conflict method.
6255 bool IsInConflict() const {
6256 return type_ == Type::kConflict;
6257 }
6258
6259 // Returns true if this is a method that must become an abstract method.
6260 bool IsAbstract() const {
6261 return type_ == Type::kAbstract;
6262 }
6263
6264 // Returns true if this is a method that must become a different method.
6265 bool IsTranslation() const {
6266 return type_ == Type::kTranslation;
6267 }
6268
6269 // Get the translated version of this method.
6270 ArtMethod* GetTranslation() const {
6271 DCHECK(IsTranslation());
6272 DCHECK(translation_ != nullptr);
6273 return translation_;
6274 }
6275
6276 private:
6277 enum class Type {
6278 kInvalid,
6279 kTranslation,
6280 kConflict,
6281 kAbstract,
6282 };
6283
6284 MethodTranslation(Type type, ArtMethod* translation)
6285 : translation_(translation), type_(type) {}
6286
6287 ArtMethod* translation_;
6288 Type type_;
6289};
6290
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006291// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6292// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6293// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006294class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006295 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006296 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006297 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006298 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006299 name_view_() {
David Sehr709b0702016-10-13 09:12:37 -07006300 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006301 }
6302
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006303 ALWAYS_INLINE std::string_view GetNameView() {
6304 if (name_view_.empty()) {
6305 name_view_ = dex_file_->StringViewByIdx(mid_->name_idx_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006306 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006307 return name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006308 }
6309
Mathieu Chartiere401d142015-04-22 13:56:20 -07006310 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006311 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006312 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006313 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006314 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006315 if (dex_file_ == other_dex_file) {
6316 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6317 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006318 return GetNameView() == other_dex_file->StringViewByIdx(other_mid.name_idx_) &&
6319 dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006320 }
6321
6322 private:
6323 // Dex file for the method to compare against.
6324 const DexFile* const dex_file_;
6325 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006326 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006327 // Lazily computed name from the dex file's strings.
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006328 std::string_view name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006329};
6330
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006331class LinkVirtualHashTable {
6332 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006333 LinkVirtualHashTable(Handle<mirror::Class> klass,
6334 size_t hash_size,
6335 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006336 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006337 : klass_(klass),
6338 hash_size_(hash_size),
6339 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006340 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006341 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6342 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006343
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006344 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006345 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6346 virtual_method_index, image_pointer_size_);
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006347 std::string_view name_view =
6348 local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetNameView();
6349 uint32_t hash = ComputeModifiedUtf8Hash(name_view);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006350 uint32_t index = hash % hash_size_;
6351 // Linear probe until we have an empty slot.
6352 while (hash_table_[index] != invalid_index_) {
6353 if (++index == hash_size_) {
6354 index = 0;
6355 }
6356 }
6357 hash_table_[index] = virtual_method_index;
6358 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006359
Vladimir Marko43354742021-02-03 15:37:01 +00006360 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator, uint32_t hash)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006361 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006362 DCHECK_EQ(hash, ComputeModifiedUtf8Hash(comparator->GetNameView()));
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006363 size_t index = hash % hash_size_;
6364 while (true) {
6365 const uint32_t value = hash_table_[index];
6366 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6367 // the block and can safely assume not found.
6368 if (value == invalid_index_) {
6369 break;
6370 }
6371 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006372 ArtMethod* virtual_method =
6373 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6374 if (comparator->HasSameNameAndSignature(
6375 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006376 hash_table_[index] = removed_index_;
6377 return value;
6378 }
6379 }
6380 if (++index == hash_size_) {
6381 index = 0;
6382 }
6383 }
6384 return GetNotFoundIndex();
6385 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006386
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006387 static uint32_t GetNotFoundIndex() {
6388 return invalid_index_;
6389 }
6390
6391 private:
6392 static const uint32_t invalid_index_;
6393 static const uint32_t removed_index_;
6394
6395 Handle<mirror::Class> klass_;
6396 const size_t hash_size_;
6397 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006398 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006399};
6400
6401const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6402const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6403
Alex Light9139e002015-10-09 15:59:48 -07006404// Determine if the given iface has any subinterface in the given list that declares the method
6405// specified by 'target'.
6406//
6407// Arguments
6408// - self: The thread we are running on
6409// - target: A comparator that will match any method that overrides the method we are checking for
6410// - iftable: The iftable we are searching for an overriding method on.
6411// - ifstart: The index of the interface we are checking to see if anything overrides
6412// - iface: The interface we are checking to see if anything overrides.
6413// - image_pointer_size:
6414// The image pointer size.
6415//
6416// Returns
6417// - True: There is some method that matches the target comparator defined in an interface that
6418// is a subtype of iface.
6419// - False: There is no method that matches the target comparator in any interface that is a subtype
6420// of iface.
6421static bool ContainsOverridingMethodOf(Thread* self,
6422 MethodNameAndSignatureComparator& target,
6423 Handle<mirror::IfTable> iftable,
6424 size_t ifstart,
6425 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006426 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006427 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006428 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006429 DCHECK(iface != nullptr);
6430 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006431 DCHECK_GE(ifstart, 0u);
6432 DCHECK_LT(ifstart, iftable->Count());
6433 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6434 DCHECK(iface->IsInterface());
6435
6436 size_t iftable_count = iftable->Count();
6437 StackHandleScope<1> hs(self);
6438 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6439 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6440 // Skip ifstart since our current interface obviously cannot override itself.
6441 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006442 // Iterate through every method on this interface. The order does not matter.
6443 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006444 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006445 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006446 // Check if the i'th interface is a subtype of this one.
6447 if (iface->IsAssignableFrom(current_iface.Get())) {
6448 return true;
6449 }
6450 break;
6451 }
6452 }
6453 }
6454 return false;
6455}
6456
Alex Lighteb7c1442015-08-31 13:17:42 -07006457// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006458// out_default_method and returns kDefaultFound on success. If no default method was found return
6459// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6460// default_method conflict) it will return kDefaultConflict.
6461ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6462 Thread* self,
6463 ArtMethod* target_method,
6464 Handle<mirror::Class> klass,
6465 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006466 DCHECK(self != nullptr);
6467 DCHECK(target_method != nullptr);
6468 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006469
6470 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006471
6472 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6473 // table. This lets us walk the table backwards when searching for default methods. The first one
6474 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6475 // track of it and then continue checking all other interfaces, since we need to throw an error if
6476 // we encounter conflicting default method implementations (one is not a subtype of the other).
6477 //
6478 // The order of unrelated interfaces does not matter and is not defined.
6479 size_t iftable_count = klass->GetIfTableCount();
6480 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006481 // No interfaces. We have already reset out to null so just return kAbstractFound.
6482 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006483 }
6484
Alex Light9139e002015-10-09 15:59:48 -07006485 StackHandleScope<3> hs(self);
6486 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006487 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006488 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006489 MethodNameAndSignatureComparator target_name_comparator(
6490 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6491 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006492 for (size_t k = iftable_count; k != 0; ) {
6493 --k;
6494
Alex Lighteb7c1442015-08-31 13:17:42 -07006495 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006496
6497 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006498 // Iterate through every declared method on this interface. The order does not matter.
6499 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6500 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006501 // Skip abstract methods and methods with different names.
6502 if (current_method->IsAbstract() ||
6503 !target_name_comparator.HasSameNameAndSignature(
6504 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6505 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006506 } else if (!current_method->IsPublic()) {
6507 // The verifier should have caught the non-public method for dex version 37. Just warn and
6508 // skip it since this is from before default-methods so we don't really need to care that it
6509 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006510 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6511 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006512 << "This will be a fatal error in subsequent versions of android. "
6513 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006514 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006515 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006516 // We have multiple default impls of the same method. This is a potential default conflict.
6517 // We need to check if this possibly conflicting method is either a superclass of the chosen
6518 // default implementation or is overridden by a non-default interface method. In either case
6519 // there is no conflict.
6520 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6521 !ContainsOverridingMethodOf(self,
6522 target_name_comparator,
6523 iftable,
6524 k,
6525 iface,
6526 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006527 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006528 << current_method->PrettyMethod() << " and "
6529 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6530 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006531 *out_default_method = nullptr;
6532 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006533 } else {
6534 break; // Continue checking at the next interface.
6535 }
6536 } else {
Alex Light9139e002015-10-09 15:59:48 -07006537 // chosen_iface == null
6538 if (!ContainsOverridingMethodOf(self,
6539 target_name_comparator,
6540 iftable,
6541 k,
6542 iface,
6543 image_pointer_size_)) {
6544 // Don't set this as the chosen interface if something else is overriding it (because that
6545 // other interface would be potentially chosen instead if it was default). If the other
6546 // interface was abstract then we wouldn't select this interface as chosen anyway since
6547 // the abstract method masks it.
6548 *out_default_method = current_method;
6549 chosen_iface.Assign(iface.Get());
6550 // We should now finish traversing the graph to find if we have default methods that
6551 // conflict.
6552 } else {
David Sehr709b0702016-10-13 09:12:37 -07006553 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6554 << "' was "
6555 << "skipped because it was overridden by an abstract method in a "
6556 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006557 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006558 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006559 break;
6560 }
6561 }
Alex Light9139e002015-10-09 15:59:48 -07006562 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006563 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6564 << "' selected "
6565 << "as the implementation for '" << target_method->PrettyMethod()
6566 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006567 return DefaultMethodSearchResult::kDefaultFound;
6568 } else {
6569 return DefaultMethodSearchResult::kAbstractFound;
6570 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006571}
6572
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006573ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006574 ArtMethod* conflict_method,
6575 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006576 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006577 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006578 Runtime* const runtime = Runtime::Current();
6579 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006580
6581 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006582 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006583 ? runtime->CreateImtConflictMethod(linear_alloc)
6584 : conflict_method;
6585
6586 // Allocate a new table. Note that we will leak this table at the next conflict,
6587 // but that's a tradeoff compared to making the table fixed size.
6588 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006589 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6590 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006591 if (data == nullptr) {
6592 LOG(ERROR) << "Failed to allocate conflict table";
6593 return conflict_method;
6594 }
6595 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6596 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006597 method,
6598 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006599
6600 // Do a fence to ensure threads see the data in the table before it is assigned
6601 // to the conflict method.
6602 // Note that there is a race in the presence of multiple threads and we may leak
6603 // memory from the LinearAlloc, but that's a tradeoff compared to using
6604 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006605 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006606 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006607 return new_conflict_method;
6608}
6609
Vladimir Marko921094a2017-01-12 18:37:06 +00006610bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6611 Handle<mirror::Class> klass,
6612 Handle<mirror::IfTable> iftable) {
6613 DCHECK(!klass->IsInterface());
6614 const bool has_superclass = klass->HasSuperClass();
6615 const bool extend_super_iftable = has_superclass;
6616 const size_t ifcount = klass->GetIfTableCount();
6617 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6618 for (size_t i = 0; i < ifcount; ++i) {
6619 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6620 if (num_methods > 0) {
6621 const bool is_super = i < super_ifcount;
6622 // This is an interface implemented by a super-class. Therefore we can just copy the method
6623 // array from the superclass.
6624 const bool super_interface = is_super && extend_super_iftable;
6625 ObjPtr<mirror::PointerArray> method_array;
6626 if (super_interface) {
6627 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6628 DCHECK(if_table != nullptr);
6629 DCHECK(if_table->GetMethodArray(i) != nullptr);
6630 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006631 StackHandleScope<1u> hs(self);
6632 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6633 method_array =
6634 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006635 } else {
6636 method_array = AllocPointerArray(self, num_methods);
6637 }
6638 if (UNLIKELY(method_array == nullptr)) {
6639 self->AssertPendingOOMException();
6640 return false;
6641 }
6642 iftable->SetMethodArray(i, method_array);
6643 }
6644 }
6645 return true;
6646}
6647
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006648void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6649 ArtMethod* imt_conflict_method,
6650 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006651 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006652 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006653 // Place method in imt if entry is empty, place conflict otherwise.
6654 if (*imt_ref == unimplemented_method) {
6655 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006656 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006657 // If we are not a conflict and we have the same signature and name as the imt
6658 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006659 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6660 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006661 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006662 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006663 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006664 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006665 *imt_ref = current_method;
6666 } else {
Alex Light9139e002015-10-09 15:59:48 -07006667 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006668 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006669 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006670 } else {
6671 // Place the default conflict method. Note that there may be an existing conflict
6672 // method in the IMT, but it could be one tailored to the super class, with a
6673 // specific ImtConflictTable.
6674 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006675 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006676 }
6677}
6678
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006679void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006680 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6681 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006682 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006683 Runtime* const runtime = Runtime::Current();
6684 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6685 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006686 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006687 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006688 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006689 FillIMTFromIfTable(klass->GetIfTable(),
6690 unimplemented_method,
6691 conflict_method,
6692 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006693 /*create_conflict_tables=*/true,
6694 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006695 &new_conflict,
6696 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006697 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006698 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6699 // we can just use the same pointer.
6700 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006701 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006702 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6703 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6704 bool same = true;
6705 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6706 ArtMethod* method = imt_data[i];
6707 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6708 if (method != super_method) {
6709 bool is_conflict_table = method->IsRuntimeMethod() &&
6710 method != unimplemented_method &&
6711 method != conflict_method;
6712 // Verify conflict contents.
6713 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6714 super_method != unimplemented_method &&
6715 super_method != conflict_method;
6716 if (!is_conflict_table || !super_conflict_table) {
6717 same = false;
6718 } else {
6719 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6720 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6721 same = same && table1->Equals(table2, image_pointer_size_);
6722 }
6723 }
6724 }
6725 if (same) {
6726 imt = super_imt;
6727 }
6728 }
6729 if (imt == nullptr) {
6730 imt = klass->GetImt(image_pointer_size_);
6731 DCHECK(imt != nullptr);
6732 imt->Populate(imt_data, image_pointer_size_);
6733 } else {
6734 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006735 }
6736}
6737
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006738ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6739 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006740 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006741 void* data = linear_alloc->Alloc(Thread::Current(),
6742 ImtConflictTable::ComputeSize(count,
6743 image_pointer_size));
6744 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6745}
6746
6747ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6748 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6749}
6750
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006751void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006752 ArtMethod* unimplemented_method,
6753 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006754 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006755 bool create_conflict_tables,
6756 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006757 /*out*/bool* new_conflict,
6758 /*out*/ArtMethod** imt) {
6759 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006760 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006761 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006762 const size_t num_virtuals = interface->NumVirtualMethods();
6763 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6764 // Virtual methods can be larger than the if table methods if there are default methods.
6765 DCHECK_GE(num_virtuals, method_array_count);
6766 if (kIsDebugBuild) {
6767 if (klass->IsInterface()) {
6768 DCHECK_EQ(method_array_count, 0u);
6769 } else {
6770 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6771 }
6772 }
6773 if (method_array_count == 0) {
6774 continue;
6775 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006776 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006777 for (size_t j = 0; j < method_array_count; ++j) {
6778 ArtMethod* implementation_method =
6779 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6780 if (ignore_copied_methods && implementation_method->IsCopied()) {
6781 continue;
6782 }
6783 DCHECK(implementation_method != nullptr);
6784 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6785 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6786 // or interface methods in the IMT here they will not create extra conflicts since we compare
6787 // names and signatures in SetIMTRef.
6788 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006789 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006790
6791 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6792 // the same implementation method, keep track of this to avoid creating a conflict table in
6793 // this case.
6794
6795 // Conflict table size for each IMT slot.
6796 ++conflict_counts[imt_index];
6797
6798 SetIMTRef(unimplemented_method,
6799 imt_conflict_method,
6800 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006801 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006802 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006803 }
6804 }
6805
6806 if (create_conflict_tables) {
6807 // Create the conflict tables.
6808 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006809 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006810 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006811 if (imt[i] == imt_conflict_method) {
6812 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6813 if (new_table != nullptr) {
6814 ArtMethod* new_conflict_method =
6815 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6816 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6817 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006818 } else {
6819 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006820 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006821 }
6822 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006823 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006824 }
6825 }
6826
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006827 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006828 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006829 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6830 // Virtual methods can be larger than the if table methods if there are default methods.
6831 if (method_array_count == 0) {
6832 continue;
6833 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006834 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006835 for (size_t j = 0; j < method_array_count; ++j) {
6836 ArtMethod* implementation_method =
6837 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6838 if (ignore_copied_methods && implementation_method->IsCopied()) {
6839 continue;
6840 }
6841 DCHECK(implementation_method != nullptr);
6842 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006843 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006844 if (!imt[imt_index]->IsRuntimeMethod() ||
6845 imt[imt_index] == unimplemented_method ||
6846 imt[imt_index] == imt_conflict_method) {
6847 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006848 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006849 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6850 const size_t num_entries = table->NumEntries(image_pointer_size_);
6851 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6852 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006853 }
6854 }
6855 }
6856}
6857
Alex Lighteb7c1442015-08-31 13:17:42 -07006858// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6859// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006860static bool NotSubinterfaceOfAny(
Vladimir Marko782fb712020-12-23 12:47:31 +00006861 const HashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006862 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006863 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006864 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006865 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006866 for (ObjPtr<mirror::Class> c : classes) {
6867 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006868 return false;
6869 }
6870 }
6871 return true;
6872}
6873
6874// Fills in and flattens the interface inheritance hierarchy.
6875//
6876// By the end of this function all interfaces in the transitive closure of to_process are added to
6877// the iftable and every interface precedes all of its sub-interfaces in this list.
6878//
6879// all I, J: Interface | I <: J implies J precedes I
6880//
6881// (note A <: B means that A is a subtype of B)
6882//
6883// This returns the total number of items in the iftable. The iftable might be resized down after
6884// this call.
6885//
6886// We order this backwards so that we do not need to reorder superclass interfaces when new
6887// interfaces are added in subclass's interface tables.
6888//
6889// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6890// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6891// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6892// iftable must be large enough to hold all interfaces without changing its size.
Vladimir Markob10668c2021-06-10 09:52:53 +01006893static size_t FillIfTable(ObjPtr<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00006894 ObjPtr<mirror::ObjectArray<mirror::Class>> interfaces,
6895 ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006896 size_t super_ifcount,
Vladimir Marko782fb712020-12-23 12:47:31 +00006897 size_t num_interfaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006898 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00006899 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
6900 // This is the set of all classes already in the iftable. Used to make checking
6901 // if a class has already been added quicker.
6902 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
6903 mirror::Class* buffer[kBufferSize];
6904 HashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07006905 // The first super_ifcount elements are from the superclass. We note that they are already added.
6906 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006907 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006908 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00006909 classes_in_iftable.insert(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07006910 }
6911 size_t filled_ifcount = super_ifcount;
Vladimir Marko782fb712020-12-23 12:47:31 +00006912 const bool have_interfaces = interfaces != nullptr;
6913 for (size_t i = 0; i != num_interfaces; ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +01006914 ObjPtr<mirror::Class> interface =
6915 have_interfaces ? interfaces->Get(i) : klass->GetDirectInterface(i);
Vladimir Marko782fb712020-12-23 12:47:31 +00006916
Alex Lighteb7c1442015-08-31 13:17:42 -07006917 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6918 // At this point in the loop current-iface-list has the invariant that:
6919 // for every pair of interfaces I,J within it:
6920 // if index_of(I) < index_of(J) then I is not a subtype of J
6921
6922 // If we have already seen this element then all of its super-interfaces must already be in the
6923 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00006924 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006925 // We haven't seen this interface so add all of its super-interfaces onto the
6926 // current-iface-list, skipping those already on it.
6927 int32_t ifcount = interface->GetIfTableCount();
6928 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006929 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006930 if (!ContainsElement(classes_in_iftable, super_interface)) {
6931 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00006932 classes_in_iftable.insert(super_interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07006933 iftable->SetInterface(filled_ifcount, super_interface);
6934 filled_ifcount++;
6935 }
6936 }
6937 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6938 // Place this interface onto the current-iface-list after all of its super-interfaces.
Vladimir Marko782fb712020-12-23 12:47:31 +00006939 classes_in_iftable.insert(interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07006940 iftable->SetInterface(filled_ifcount, interface);
6941 filled_ifcount++;
6942 } else if (kIsDebugBuild) {
6943 // Check all super-interfaces are already in the list.
6944 int32_t ifcount = interface->GetIfTableCount();
6945 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006946 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006947 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006948 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6949 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006950 }
6951 }
6952 }
6953 if (kIsDebugBuild) {
6954 // Check that the iftable is ordered correctly.
6955 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006956 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006957 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006958 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006959 // !(if_a <: if_b)
6960 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006961 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6962 << ") extends "
6963 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006964 << "interface list.";
6965 }
6966 }
6967 }
6968 return filled_ifcount;
6969}
6970
Vladimir Marko782fb712020-12-23 12:47:31 +00006971bool ClassLinker::SetupInterfaceLookupTable(Thread* self,
6972 Handle<mirror::Class> klass,
Alex Lighteb7c1442015-08-31 13:17:42 -07006973 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6974 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006975 const bool has_superclass = klass->HasSuperClass();
6976 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006977 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006978 const size_t num_interfaces =
6979 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006980 if (num_interfaces == 0) {
6981 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006982 if (LIKELY(has_superclass)) {
6983 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6984 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006985 // Class implements no interfaces.
6986 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006987 return true;
6988 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006989 // Class implements same interfaces as parent, are any of these not marker interfaces?
6990 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006991 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006992 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006993 if (super_iftable->GetMethodArrayCount(i) > 0) {
6994 has_non_marker_interface = true;
6995 break;
6996 }
6997 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006998 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006999 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007000 klass->SetIfTable(super_iftable);
7001 return true;
7002 }
7003 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007004 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007005 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007006 for (size_t i = 0; i < num_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01007007 ObjPtr<mirror::Class> interface =
7008 have_interfaces ? interfaces->GetWithoutChecks(i) : klass->GetDirectInterface(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007009 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007010 if (UNLIKELY(!interface->IsInterface())) {
7011 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007012 ThrowIncompatibleClassChangeError(klass.Get(),
7013 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007014 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007015 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7016 return false;
7017 }
7018 ifcount += interface->GetIfTableCount();
7019 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007020 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007021 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007022 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007023 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007024 return false;
7025 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007026 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007027 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007028 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007029 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007030 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007031 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007032 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007033 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007034
7035 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7036 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7037 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007038 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007039
Vladimir Markob10668c2021-06-10 09:52:53 +01007040 const size_t new_ifcount =
7041 FillIfTable(klass.Get(), interfaces.Get(), iftable.Get(), super_ifcount, num_interfaces);
Alex Lighteb7c1442015-08-31 13:17:42 -07007042
Ian Rogers7b078e82014-09-10 14:44:24 -07007043 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007044
Ian Rogersb52b01a2012-01-12 17:01:38 -08007045 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007046 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007047 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007048 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007049 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007050 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007051 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007052 return false;
7053 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007054 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007055 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007056 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007057 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007058 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007059 return true;
7060}
7061
Alex Light1f3925d2016-09-07 12:04:20 -07007062// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7063// of methods must be unique.
7064static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7065 return nullptr;
7066}
7067
7068template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007069static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007070 const ScopedArenaVector<ArtMethod*>& list,
7071 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007072 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007073 for (ArtMethod* method : list) {
7074 if (cmp.HasSameNameAndSignature(method)) {
7075 return method;
7076 }
7077 }
Alex Light1f3925d2016-09-07 12:04:20 -07007078 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007079}
7080
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007081namespace {
7082
Alex Light1f3925d2016-09-07 12:04:20 -07007083// Check that all vtable entries are present in this class's virtuals or are the same as a
7084// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007085void CheckClassOwnsVTableEntries(Thread* self,
7086 Handle<mirror::Class> klass,
7087 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007088 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007089 StackHandleScope<2> hs(self);
7090 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007091 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007092 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007093 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007094 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7095 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7096 CHECK(m != nullptr);
7097
Alex Lighta41a30782017-03-29 11:33:19 -07007098 if (m->GetMethodIndexDuringLinking() != i) {
7099 LOG(WARNING) << m->PrettyMethod()
7100 << " has an unexpected method index for its spot in the vtable for class"
7101 << klass->PrettyClass();
7102 }
Alex Lighte64300b2015-12-15 15:02:47 -08007103 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7104 auto is_same_method = [m] (const ArtMethod& meth) {
7105 return &meth == m;
7106 };
Alex Light3f980532017-03-17 15:10:32 -07007107 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7108 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7109 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7110 << klass->PrettyClass() << " or any of its superclasses!";
7111 }
Alex Lighte64300b2015-12-15 15:02:47 -08007112 }
7113}
7114
Alex Light1f3925d2016-09-07 12:04:20 -07007115// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7116// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007117template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007118void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007119 REQUIRES_SHARED(Locks::mutator_lock_) {
7120 StackHandleScope<1> hs(self);
7121 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7122 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007123
7124 // Observations:
7125 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7126 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7127 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7128 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7129 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7130 // * The single-pass algorithm will trade memory for speed, but that is OK.
7131
7132 CHECK_GT(num_entries, 0);
7133
7134 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7135 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7136 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7137 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7138 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7139 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7140 << m2->PrettyMethod() << " (0x" << std::hex
7141 << reinterpret_cast<uintptr_t>(m2) << ")";
7142 };
7143 struct BaseHashType {
7144 static size_t HashCombine(size_t seed, size_t val) {
7145 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7146 }
7147 };
7148
7149 // Check assuming all entries come from the same dex file.
7150 {
7151 // Find the first interesting method and its dex file.
7152 int32_t start = 0;
7153 for (; start < num_entries; ++start) {
7154 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7155 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7156 // maybe).
7157 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7158 vtable_entry->GetAccessFlags())) {
7159 continue;
7160 }
7161 break;
7162 }
7163 if (start == num_entries) {
7164 return;
7165 }
7166 const DexFile* dex_file =
7167 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7168 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7169
7170 // Helper function to avoid logging if we have to run the cross-file checks.
7171 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7172 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7173 using PairType = std::pair<uint32_t, uint16_t>;
7174 struct PairHash : BaseHashType {
7175 size_t operator()(const PairType& key) const {
7176 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7177 }
7178 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007179 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007180 seen.reserve(2 * num_entries);
7181 bool need_slow_path = false;
7182 bool found_dup = false;
7183 for (int i = start; i < num_entries; ++i) {
7184 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7185 // wrt/ kPointerSize.
7186 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7187 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7188 vtable_entry->GetAccessFlags())) {
7189 continue;
7190 }
7191 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7192 if (dex_file != m->GetDexFile()) {
7193 need_slow_path = true;
7194 break;
7195 }
7196 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7197 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7198 auto it = seen.find(pair);
7199 if (it != seen.end()) {
7200 found_dup = true;
7201 if (log_warn) {
7202 log_fn(it->second, i);
7203 }
7204 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007205 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007206 }
7207 }
7208 return std::make_pair(need_slow_path, found_dup);
7209 };
7210 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7211 if (!result.first) {
7212 if (result.second) {
7213 check_fn(/* log_warn= */ true);
7214 }
7215 return;
7216 }
7217 }
7218
7219 // Need to check across dex files.
7220 struct Entry {
7221 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00007222 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007223 const char* name = nullptr;
7224 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007225
Vladimir Marko782fb712020-12-23 12:47:31 +00007226 Entry() = default;
7227 Entry(const Entry& other) = default;
7228 Entry& operator=(const Entry& other) = default;
7229
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007230 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00007231 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
7232 // This call writes `name_len` and it is therefore necessary that the
7233 // initializer for `name_len` comes before it, otherwise the value
7234 // from the call would be overwritten by that initializer.
7235 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007236 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00007237 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
7238 if (name[name_len] != 0) {
7239 name_len += strlen(name + name_len);
7240 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007241 }
7242
7243 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00007244 return name_len == other.name_len &&
7245 memcmp(name, other.name, name_len) == 0 &&
7246 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007247 }
7248 };
7249 struct EntryHash {
7250 size_t operator()(const Entry& key) const {
7251 return key.cached_hash;
7252 }
7253 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007254 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007255 for (int32_t i = 0; i < num_entries; ++i) {
7256 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7257 // wrt/ kPointerSize.
7258 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7259 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7260 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007261 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7262 vtable_entry->GetAccessFlags())) {
7263 continue;
7264 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007265 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7266 const DexFile* dex_file = m->GetDexFile();
7267 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7268
7269 Entry e(dex_file, mid);
7270
7271 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7272 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7273 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7274 sig_hash);
7275
7276 auto it = map.find(e);
7277 if (it != map.end()) {
7278 log_fn(it->second, i);
7279 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007280 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07007281 }
7282 }
7283}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007284
7285void CheckVTableHasNoDuplicates(Thread* self,
7286 Handle<mirror::Class> klass,
7287 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007288 REQUIRES_SHARED(Locks::mutator_lock_) {
7289 switch (pointer_size) {
7290 case PointerSize::k64:
7291 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7292 break;
7293 case PointerSize::k32:
7294 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7295 break;
7296 }
7297}
Alex Light1f3925d2016-09-07 12:04:20 -07007298
Orion Hodson5880c772020-07-28 20:12:08 +01007299static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07007300 REQUIRES_SHARED(Locks::mutator_lock_) {
7301 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7302 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7303}
7304
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007305} // namespace
7306
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007307void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7308 ArtMethod* unimplemented_method,
7309 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007310 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007311 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007312 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007313 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007314 if (super_class->ShouldHaveImt()) {
7315 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7316 for (size_t i = 0; i < ImTable::kSize; ++i) {
7317 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007318 }
7319 } else {
7320 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007321 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007322 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007323 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007324 FillIMTFromIfTable(if_table,
7325 unimplemented_method,
7326 imt_conflict_method,
7327 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007328 /*create_conflict_tables=*/false,
7329 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007330 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007331 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007332 }
7333 }
7334}
7335
Vladimir Markobc893672021-11-10 15:25:46 +00007336class ClassLinker::LinkMethodsHelper {
Vladimir Marko921094a2017-01-12 18:37:06 +00007337 public:
Vladimir Markobc893672021-11-10 15:25:46 +00007338 LinkMethodsHelper(ClassLinker* class_linker,
7339 Handle<mirror::Class> klass,
7340 Thread* self,
7341 Runtime* runtime)
Vladimir Marko921094a2017-01-12 18:37:06 +00007342 : class_linker_(class_linker),
7343 klass_(klass),
7344 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7345 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7346 self_(self),
7347 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7348 allocator_(&stack_),
Vladimir Markobc893672021-11-10 15:25:46 +00007349 default_translations_(default_translations_initial_buffer_,
7350 kDefaultTranslationsInitialBufferSize,
7351 allocator_.Adapter()),
Vladimir Marko921094a2017-01-12 18:37:06 +00007352 default_conflict_methods_(allocator_.Adapter()),
7353 overriding_default_conflict_methods_(allocator_.Adapter()),
7354 miranda_methods_(allocator_.Adapter()),
7355 default_methods_(allocator_.Adapter()),
7356 overriding_default_methods_(allocator_.Adapter()),
7357 move_table_(allocator_.Adapter()) {
7358 }
7359
Vladimir Markobc893672021-11-10 15:25:46 +00007360 // Links the virtual methods for the given class and records any default methods
7361 // that will need to be updated later.
7362 //
7363 // Arguments:
7364 // * self - The current thread.
7365 // * klass - class, whose vtable will be filled in.
7366 bool LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass)
7367 REQUIRES_SHARED(Locks::mutator_lock_);
7368
7369 // Sets the imt entries and fixes up the vtable for the given class by linking
7370 // all the interface methods.
7371 bool LinkInterfaceMethods(
7372 Thread* self,
7373 Handle<mirror::Class> klass,
7374 Runtime* runtime,
7375 bool* out_new_conflict,
7376 ArtMethod** out_imt)
7377 REQUIRES_SHARED(Locks::mutator_lock_);
7378
7379 private:
7380 ArtMethod* FindOrCreateImplementationMethod(
7381 ArtMethod* interface_method,
7382 MethodNameAndSignatureComparator& interface_name_comparator,
7383 ArtMethod* vtable_impl)
Vladimir Marko921094a2017-01-12 18:37:06 +00007384 REQUIRES_SHARED(Locks::mutator_lock_);
7385
7386 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7387 MethodNameAndSignatureComparator& interface_name_comparator)
7388 REQUIRES_SHARED(Locks::mutator_lock_);
7389
7390 bool HasNewVirtuals() const {
7391 return !(miranda_methods_.empty() &&
7392 default_methods_.empty() &&
7393 overriding_default_methods_.empty() &&
7394 overriding_default_conflict_methods_.empty() &&
7395 default_conflict_methods_.empty());
7396 }
7397
7398 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7399
Vladimir Markobc893672021-11-10 15:25:46 +00007400 ObjPtr<mirror::PointerArray> UpdateVtable(Handle<mirror::PointerArray> old_vtable)
7401 REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007402
7403 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7404
7405 void UpdateIMT(ArtMethod** out_imt);
7406
7407 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7408 if (kIsDebugBuild) {
7409 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7410 // Check that there are no stale methods are in the dex cache array.
David Srbecky33df0e32021-09-30 14:36:32 +00007411 ObjPtr<mirror::DexCache> dex_cache = klass_->GetDexCache();
7412 auto* resolved_methods = dex_cache->GetResolvedMethods();
7413 size_t num_methods = dex_cache->NumResolvedMethods();
7414 for (size_t i = 0; resolved_methods != nullptr && i < num_methods; ++i) {
David Srbecky5de5efe2021-02-15 21:23:00 +00007415 auto pair = mirror::DexCache::GetNativePair(resolved_methods, i);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007416 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007417 CHECK(move_table_.find(m) == move_table_.end() ||
7418 // The original versions of copied methods will still be present so allow those too.
7419 // Note that if the first check passes this might fail to GetDeclaringClass().
7420 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7421 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7422 [m] (ArtMethod& meth) {
7423 return &meth == m;
7424 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7425 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7426 }
7427 }
7428 }
7429
7430 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7431 LengthPrefixedArray<ArtMethod>* methods) {
7432 if (kIsDebugBuild) {
7433 CHECK(methods != nullptr);
7434 // Put some random garbage in old methods to help find stale pointers.
7435 if (methods != old_methods && old_methods != nullptr) {
7436 // Need to make sure the GC is not running since it could be scanning the methods we are
7437 // about to overwrite.
7438 ScopedThreadStateChange tsc(self_, kSuspended);
7439 gc::ScopedGCCriticalSection gcs(self_,
7440 gc::kGcCauseClassLinker,
7441 gc::kCollectorTypeClassLinker);
7442 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7443 method_size_,
7444 method_alignment_);
7445 memset(old_methods, 0xFEu, old_size);
7446 }
7447 }
7448 }
7449
Vladimir Marko921094a2017-01-12 18:37:06 +00007450 size_t NumberOfNewVirtuals() const {
7451 return miranda_methods_.size() +
7452 default_methods_.size() +
7453 overriding_default_conflict_methods_.size() +
7454 overriding_default_methods_.size() +
7455 default_conflict_methods_.size();
7456 }
7457
7458 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7459 return !klass_->IsInterface();
7460 }
7461
7462 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7463 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7464 << "Interfaces should only have default-conflict methods appended to them.";
7465 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7466 << miranda_methods_.size()
7467 << " default_methods=" << default_methods_.size()
7468 << " overriding_default_methods=" << overriding_default_methods_.size()
7469 << " default_conflict_methods=" << default_conflict_methods_.size()
7470 << " overriding_default_conflict_methods="
7471 << overriding_default_conflict_methods_.size();
7472 }
7473
7474 ClassLinker* class_linker_;
7475 Handle<mirror::Class> klass_;
7476 size_t method_alignment_;
7477 size_t method_size_;
7478 Thread* const self_;
7479
7480 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7481 // the virtual methods array.
7482 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7483 // during cross compilation.
7484 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7485 ArenaStack stack_;
7486 ScopedArenaAllocator allocator_;
7487
Vladimir Markobc893672021-11-10 15:25:46 +00007488 // A map from vtable indexes to the method they need to be updated to point to. Used because we
7489 // need to have default methods be in the virtuals array of each class but we don't set that up
7490 // until LinkInterfaceMethods.
7491 // The default_translations map is keyed on the vtable index that needs to be updated. We use
7492 // this map because if we override a default method with another default method we need to
7493 // update the vtable to point to the new method. Unfortunately since we copy the ArtMethod* we
7494 // cannot just do a simple scan, we therefore store the vtable index's that might need to be
7495 // updated with the method they will turn into.
7496 // TODO This whole default_translations thing is very dirty. There should be a better way.
7497 using DefaultTranslationsHashMap = ScopedArenaHashMap<size_t, ClassLinker::MethodTranslation>;
7498 // Avoid large allocation for a few translations.
7499 // Keep the initial buffer on the stack to avoid arena allocations
7500 // if there are no special cases (the first arena allocation is costly).
7501 static constexpr size_t kDefaultTranslationsInitialBufferSize = 8;
7502 DefaultTranslationsHashMap::value_type default_translations_initial_buffer_[
7503 kDefaultTranslationsInitialBufferSize];
7504 DefaultTranslationsHashMap default_translations_;
7505
Vladimir Marko921094a2017-01-12 18:37:06 +00007506 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7507 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7508 ScopedArenaVector<ArtMethod*> miranda_methods_;
7509 ScopedArenaVector<ArtMethod*> default_methods_;
7510 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7511
7512 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7513};
7514
Vladimir Markobc893672021-11-10 15:25:46 +00007515ArtMethod* ClassLinker::LinkMethodsHelper::FindOrCreateImplementationMethod(
Vladimir Marko921094a2017-01-12 18:37:06 +00007516 ArtMethod* interface_method,
7517 MethodNameAndSignatureComparator& interface_name_comparator,
7518 ArtMethod* vtable_impl) {
7519 ArtMethod* current_method = nullptr;
7520 switch (class_linker_->FindDefaultMethodImplementation(self_,
7521 interface_method,
7522 klass_,
7523 /*out*/&current_method)) {
7524 case DefaultMethodSearchResult::kDefaultConflict: {
7525 // Default method conflict.
7526 DCHECK(current_method == nullptr);
7527 ArtMethod* default_conflict_method = nullptr;
7528 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7529 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7530 default_conflict_method = vtable_impl;
7531 } else {
7532 // See if we already have a conflict method for this method.
7533 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7534 interface_name_comparator,
7535 default_conflict_methods_,
7536 overriding_default_conflict_methods_);
7537 if (LIKELY(preexisting_conflict != nullptr)) {
7538 // We already have another conflict we can reuse.
7539 default_conflict_method = preexisting_conflict;
7540 } else {
7541 // Note that we do this even if we are an interface since we need to create this and
7542 // cannot reuse another classes.
7543 // Create a new conflict method for this to use.
7544 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7545 new(default_conflict_method) ArtMethod(interface_method,
7546 class_linker_->GetImagePointerSize());
7547 if (vtable_impl == nullptr) {
7548 // Save the conflict method. We need to add it to the vtable.
7549 default_conflict_methods_.push_back(default_conflict_method);
7550 } else {
7551 // Save the conflict method but it is already in the vtable.
7552 overriding_default_conflict_methods_.push_back(default_conflict_method);
7553 }
7554 }
7555 }
7556 current_method = default_conflict_method;
7557 break;
7558 } // case kDefaultConflict
7559 case DefaultMethodSearchResult::kDefaultFound: {
7560 DCHECK(current_method != nullptr);
7561 // Found a default method.
7562 if (vtable_impl != nullptr &&
7563 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7564 // We found a default method but it was the same one we already have from our
7565 // superclass. Don't bother adding it to our vtable again.
7566 current_method = vtable_impl;
7567 } else if (LIKELY(FillTables())) {
7568 // Interfaces don't need to copy default methods since they don't have vtables.
7569 // Only record this default method if it is new to save space.
7570 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7571 // would make lookup for interface super much faster. (We would only need to scan
7572 // the iftable to find if there is a NSME or AME.)
7573 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7574 default_methods_,
7575 overriding_default_methods_);
7576 if (old == nullptr) {
7577 // We found a default method implementation and there were no conflicts.
7578 if (vtable_impl == nullptr) {
7579 // Save the default method. We need to add it to the vtable.
7580 default_methods_.push_back(current_method);
7581 } else {
7582 // Save the default method but it is already in the vtable.
7583 overriding_default_methods_.push_back(current_method);
7584 }
7585 } else {
7586 CHECK(old == current_method) << "Multiple default implementations selected!";
7587 }
7588 }
7589 break;
7590 } // case kDefaultFound
7591 case DefaultMethodSearchResult::kAbstractFound: {
7592 DCHECK(current_method == nullptr);
7593 // Abstract method masks all defaults.
7594 if (vtable_impl != nullptr &&
7595 vtable_impl->IsAbstract() &&
7596 !vtable_impl->IsDefaultConflicting()) {
7597 // We need to make this an abstract method but the version in the vtable already is so
7598 // don't do anything.
7599 current_method = vtable_impl;
7600 }
7601 break;
7602 } // case kAbstractFound
7603 }
7604 return current_method;
7605}
7606
Vladimir Markobc893672021-11-10 15:25:46 +00007607ArtMethod* ClassLinker::LinkMethodsHelper::GetOrCreateMirandaMethod(
Vladimir Marko921094a2017-01-12 18:37:06 +00007608 ArtMethod* interface_method,
7609 MethodNameAndSignatureComparator& interface_name_comparator) {
7610 // Find out if there is already a miranda method we can use.
7611 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7612 miranda_methods_);
7613 if (miranda_method == nullptr) {
7614 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7615 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7616 CHECK(miranda_method != nullptr);
7617 // Point the interface table at a phantom slot.
7618 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7619 miranda_methods_.push_back(miranda_method);
7620 }
7621 return miranda_method;
7622}
7623
Vladimir Markobc893672021-11-10 15:25:46 +00007624void ClassLinker::LinkMethodsHelper::ReallocMethods() {
Vladimir Marko921094a2017-01-12 18:37:06 +00007625 LogNewVirtuals();
7626
7627 const size_t old_method_count = klass_->NumMethods();
7628 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7629 DCHECK_NE(old_method_count, new_method_count);
7630
7631 // Attempt to realloc to save RAM if possible.
7632 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7633 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7634 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7635 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7636 // CopyFrom has internal read barriers.
7637 //
7638 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7639 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7640 method_size_,
7641 method_alignment_);
7642 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7643 method_size_,
7644 method_alignment_);
7645 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7646 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007647 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007648 self_, old_methods, old_methods_ptr_size, new_size));
7649 CHECK(methods != nullptr); // Native allocation failure aborts.
7650
7651 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7652 if (methods != old_methods) {
7653 // Maps from heap allocated miranda method to linear alloc miranda method.
7654 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7655 // Copy over the old methods.
7656 for (auto& m : klass_->GetMethods(pointer_size)) {
7657 move_table_.emplace(&m, &*out);
7658 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7659 // barriers when it copies.
7660 out->CopyFrom(&m, pointer_size);
7661 ++out;
7662 }
7663 }
7664 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7665 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7666 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007667 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7668 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007669 ArtMethod& new_method = *out;
7670 new_method.CopyFrom(mir_method, pointer_size);
Vladimir Markode0d0de2021-03-18 14:12:35 +00007671 uint32_t access_flags = new_method.GetAccessFlags();
7672 DCHECK_EQ(access_flags & kAccIntrinsic, 0u) << "Miranda method should not be an intrinsic!";
7673 DCHECK_EQ(access_flags & kAccDefault, 0u) << "Miranda method should not be a default method!";
7674 DCHECK_NE(access_flags & kAccAbstract, 0u) << "Miranda method should be abstract!";
7675 new_method.SetAccessFlags(access_flags | kAccCopied);
Vladimir Marko921094a2017-01-12 18:37:06 +00007676 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007677 // Update the entry in the method array, as the array will be used for future lookups,
7678 // where thread suspension is allowed.
7679 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7680 // would not see them.
7681 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007682 ++out;
7683 }
7684 // We need to copy the default methods into our own method table since the runtime requires that
7685 // every method on a class's vtable be in that respective class's virtual method table.
7686 // NOTE This means that two classes might have the same implementation of a method from the same
7687 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7688 // default method found on a class with one found on the declaring interface directly and must
7689 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007690 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7691 &overriding_default_methods_}) {
7692 for (size_t i = 0; i < methods_vec->size(); ++i) {
7693 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007694 ArtMethod& new_method = *out;
7695 new_method.CopyFrom(def_method, pointer_size);
7696 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7697 // verified yet it shouldn't have methods that are skipping access checks.
7698 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7699 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007700 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007701 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7702 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7703 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7704 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007705 // Update the entry in the method array, as the array will be used for future lookups,
7706 // where thread suspension is allowed.
7707 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7708 // would not see them.
7709 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007710 ++out;
7711 }
7712 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007713 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7714 &overriding_default_conflict_methods_}) {
7715 for (size_t i = 0; i < methods_vec->size(); ++i) {
7716 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007717 ArtMethod& new_method = *out;
7718 new_method.CopyFrom(conf_method, pointer_size);
7719 // This is a type of default method (there are default method impls, just a conflict) so
Vladimir Markode0d0de2021-03-18 14:12:35 +00007720 // mark this as a default. We use the `kAccAbstract` flag to distinguish it from invokable
7721 // copied default method without using a separate access flag but the default conflicting
7722 // method is technically not abstract and ArtMethod::IsAbstract() shall return false.
7723 // Also clear the kAccSkipAccessChecks bit since this class hasn't been verified yet it
7724 // shouldn't have methods that are skipping access checks. Also clear potential
7725 // kAccSingleImplementation to avoid CHA trying to inline the default method.
7726 uint32_t access_flags = new_method.GetAccessFlags();
7727 DCHECK_EQ(access_flags & kAccNative, 0u);
7728 DCHECK_EQ(access_flags & kAccIntrinsic, 0u);
7729 constexpr uint32_t kSetFlags = kAccDefault | kAccAbstract | kAccCopied;
7730 constexpr uint32_t kMaskFlags = ~(kAccSkipAccessChecks | kAccSingleImplementation);
7731 new_method.SetAccessFlags((access_flags | kSetFlags) & kMaskFlags);
Vladimir Marko921094a2017-01-12 18:37:06 +00007732 DCHECK(new_method.IsDefaultConflicting());
Vladimir Markode0d0de2021-03-18 14:12:35 +00007733 DCHECK(!new_method.IsAbstract());
Vladimir Marko921094a2017-01-12 18:37:06 +00007734 // The actual method might or might not be marked abstract since we just copied it from a
7735 // (possibly default) interface method. We need to set it entry point to be the bridge so
7736 // that the compiler will not invoke the implementation of whatever method we copied from.
7737 EnsureThrowsInvocationError(class_linker_, &new_method);
7738 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007739 // Update the entry in the method array, as the array will be used for future lookups,
7740 // where thread suspension is allowed.
7741 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7742 // would not see them.
7743 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007744 ++out;
7745 }
7746 }
7747 methods->SetSize(new_method_count);
7748 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7749}
7750
Vladimir Markobc893672021-11-10 15:25:46 +00007751ObjPtr<mirror::PointerArray> ClassLinker::LinkMethodsHelper::UpdateVtable(
Vladimir Marko3068d582019-05-28 16:39:29 +01007752 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007753 // Update the vtable to the new method structures. We can skip this for interfaces since they
7754 // do not have vtables.
7755 const size_t old_vtable_count = old_vtable->GetLength();
7756 const size_t new_vtable_count = old_vtable_count +
7757 miranda_methods_.size() +
7758 default_methods_.size() +
7759 default_conflict_methods_.size();
7760
Vladimir Marko3068d582019-05-28 16:39:29 +01007761 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
7762 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007763 if (UNLIKELY(vtable == nullptr)) {
7764 self_->AssertPendingOOMException();
7765 return nullptr;
7766 }
7767
7768 size_t vtable_pos = old_vtable_count;
7769 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7770 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7771 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7772 default_conflict_methods_,
7773 miranda_methods_}) {
7774 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007775 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007776 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7777 // fields are references into the dex file the method was defined in. Since the ArtMethod
7778 // does not store that information it uses declaring_class_->dex_cache_.
7779 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7780 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7781 ++vtable_pos;
7782 }
7783 }
7784 DCHECK_EQ(vtable_pos, new_vtable_count);
7785
Vladimir Markobc893672021-11-10 15:25:46 +00007786 // Update old vtable methods. We use the `default_translations_` map to figure out what each
Vladimir Marko921094a2017-01-12 18:37:06 +00007787 // vtable entry should be updated to, if they need to be at all.
7788 for (size_t i = 0; i < old_vtable_count; ++i) {
7789 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7790 // Try and find what we need to change this method to.
Vladimir Markobc893672021-11-10 15:25:46 +00007791 auto translation_it = default_translations_.find(i);
7792 if (translation_it != default_translations_.end()) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007793 if (translation_it->second.IsInConflict()) {
7794 // Find which conflict method we are to use for this method.
7795 MethodNameAndSignatureComparator old_method_comparator(
7796 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7797 // We only need to look through overriding_default_conflict_methods since this is an
7798 // overridden method we are fixing up here.
7799 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7800 old_method_comparator, overriding_default_conflict_methods_);
7801 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7802 translated_method = new_conflict_method;
7803 } else if (translation_it->second.IsAbstract()) {
7804 // Find which miranda method we are to use for this method.
7805 MethodNameAndSignatureComparator old_method_comparator(
7806 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7807 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7808 miranda_methods_);
7809 DCHECK(miranda_method != nullptr);
7810 translated_method = miranda_method;
7811 } else {
7812 // Normal default method (changed from an older default or abstract interface method).
7813 DCHECK(translation_it->second.IsTranslation());
7814 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007815 auto it = move_table_.find(translated_method);
7816 DCHECK(it != move_table_.end());
7817 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007818 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007819 } else {
7820 auto it = move_table_.find(translated_method);
7821 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007822 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007823
7824 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007825 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007826 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007827 if (kIsDebugBuild) {
7828 auto* methods = klass_->GetMethodsPtr();
7829 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007830 reinterpret_cast<uintptr_t>(translated_method));
7831 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007832 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7833 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007834 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007835 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007836 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007837 }
7838 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007839 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007840 return vtable;
7841}
7842
Vladimir Markobc893672021-11-10 15:25:46 +00007843void ClassLinker::LinkMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007844 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7845 const size_t ifcount = klass_->GetIfTableCount();
7846 // Go fix up all the stale iftable pointers.
7847 for (size_t i = 0; i < ifcount; ++i) {
7848 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00007849 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
7850 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007851 DCHECK(m != nullptr) << klass_->PrettyClass();
7852 auto it = move_table_.find(m);
7853 if (it != move_table_.end()) {
7854 auto* new_m = it->second;
7855 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7856 method_array->SetElementPtrSize(j, new_m, pointer_size);
7857 }
7858 }
7859 }
7860}
7861
Vladimir Markobc893672021-11-10 15:25:46 +00007862void ClassLinker::LinkMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007863 // Fix up IMT next.
7864 for (size_t i = 0; i < ImTable::kSize; ++i) {
7865 auto it = move_table_.find(out_imt[i]);
7866 if (it != move_table_.end()) {
7867 out_imt[i] = it->second;
7868 }
7869 }
7870}
7871
Vladimir Markobc893672021-11-10 15:25:46 +00007872bool ClassLinker::LinkMethodsHelper::LinkVirtualMethods(
7873 Thread* self,
7874 Handle<mirror::Class> klass) {
7875 const PointerSize image_pointer_size = class_linker_->GetImagePointerSize();
7876 const size_t num_virtual_methods = klass->NumVirtualMethods();
7877 if (klass->IsInterface()) {
7878 // No vtable.
7879 if (!IsUint<16>(num_virtual_methods)) {
7880 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
7881 return false;
7882 }
7883 bool has_defaults = false;
7884 // Assign each method an IMT index and set the default flag.
7885 for (size_t i = 0; i < num_virtual_methods; ++i) {
7886 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size);
7887 m->SetMethodIndex(i);
7888 if (!m->IsAbstract()) {
7889 // If the dex file does not support default methods, throw ClassFormatError.
7890 // This check is necessary to protect from odd cases, such as native default
7891 // methods, that the dex file verifier permits for old dex file versions. b/157170505
7892 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
7893 // currently running CTS tests for default methods with dex file version 035 which
7894 // does not support default methods. So, we limit this to native methods. b/157718952
7895 if (m->IsNative()) {
7896 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
7897 ThrowClassFormatError(klass.Get(),
7898 "Dex file does not support default method '%s'",
7899 m->PrettyMethod().c_str());
7900 return false;
7901 }
7902 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
7903 has_defaults = true;
7904 }
7905 }
7906 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
7907 // during initialization. This is a performance optimization. We could simply traverse the
7908 // virtual_methods_ array again during initialization.
7909 if (has_defaults) {
7910 klass->SetHasDefaultMethods();
7911 }
7912 return true;
7913 } else if (klass->HasSuperClass()) {
7914 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
7915 const size_t max_count = num_virtual_methods + super_vtable_length;
7916 StackHandleScope<3> hs(self);
7917 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
7918 MutableHandle<mirror::PointerArray> vtable;
7919 if (super_class->ShouldHaveEmbeddedVTable()) {
7920 vtable = hs.NewHandle(class_linker_->AllocPointerArray(self, max_count));
7921 if (UNLIKELY(vtable == nullptr)) {
7922 self->AssertPendingOOMException();
7923 return false;
7924 }
7925 for (size_t i = 0; i < super_vtable_length; i++) {
7926 vtable->SetElementPtrSize(
7927 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size), image_pointer_size);
7928 }
7929 // We might need to change vtable if we have new virtual methods or new interfaces (since that
7930 // might give us new default methods). If no new interfaces then we can skip the rest since
7931 // the class cannot override any of the super-class's methods. This is required for
7932 // correctness since without it we might not update overridden default method vtable entries
7933 // correctly.
7934 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
7935 klass->SetVTable(vtable.Get());
7936 return true;
7937 }
7938 } else {
7939 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
7940 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
7941 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
7942 // We might need to change vtable if we have new virtual methods or new interfaces (since that
7943 // might give us new default methods). See comment above.
7944 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
7945 klass->SetVTable(super_vtable.Get());
7946 return true;
7947 }
7948 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
7949 mirror::Array::CopyOf(super_vtable, self, max_count)));
7950 if (UNLIKELY(vtable == nullptr)) {
7951 self->AssertPendingOOMException();
7952 return false;
7953 }
7954 }
7955 // How the algorithm works:
7956 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
7957 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
7958 // method which has not been matched to a vtable method, and j if the virtual method at the
7959 // index overrode the super virtual method at index j.
7960 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
7961 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
7962 // the need for the initial vtable which we later shrink back down).
7963 // 3. Add non overridden methods to the end of the vtable.
7964 static constexpr size_t kMaxStackHash = 250;
7965 // + 1 so that even if we only have new default methods we will still be able to use this hash
7966 // table (i.e. it will never have 0 size).
7967 const size_t hash_table_size = num_virtual_methods * 3 + 1;
7968 uint32_t* hash_table_ptr;
7969 std::unique_ptr<uint32_t[]> hash_heap_storage;
7970 if (hash_table_size <= kMaxStackHash) {
7971 hash_table_ptr = reinterpret_cast<uint32_t*>(
7972 alloca(hash_table_size * sizeof(*hash_table_ptr)));
7973 } else {
7974 hash_heap_storage.reset(new uint32_t[hash_table_size]);
7975 hash_table_ptr = hash_heap_storage.get();
7976 }
7977 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size);
7978 // Add virtual methods to the hash table.
7979 for (size_t i = 0; i < num_virtual_methods; ++i) {
7980 DCHECK(klass->GetVirtualMethodDuringLinking(
7981 i, image_pointer_size)->GetDeclaringClass() != nullptr);
7982 hash_table.Add(i);
7983 }
7984 // Loop through each super vtable method and see if they are overridden by a method we added to
7985 // the hash table.
7986 for (size_t j = 0; j < super_vtable_length; ++j) {
7987 // Search the hash table to see if we are overridden by any method.
7988 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size);
7989 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
7990 super_method->GetAccessFlags())) {
7991 // Continue on to the next method since this one is package private
7992 // and cannot be overridden. Before Android 4.1, the package-private
7993 // method super_method might have been incorrectly overridden.
7994 continue;
7995 }
7996 MethodNameAndSignatureComparator super_method_name_comparator(
7997 super_method->GetInterfaceMethodIfProxy(image_pointer_size));
7998 // We remove the method so that subsequent lookups will be faster by making the hash-map
7999 // smaller as we go on.
8000 uint32_t hash = (j < mirror::Object::kVTableLength)
8001 ? class_linker_->object_virtual_method_hashes_[j]
8002 : ComputeModifiedUtf8Hash(super_method_name_comparator.GetNameView());
8003 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator, hash);
8004 if (hash_index != hash_table.GetNotFoundIndex()) {
8005 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
8006 hash_index, image_pointer_size);
8007 if (super_method->IsFinal()) {
8008 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
8009 virtual_method->PrettyMethod().c_str(),
8010 super_method->GetDeclaringClassDescriptor());
8011 return false;
8012 }
8013 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size);
8014 virtual_method->SetMethodIndex(j);
8015 } else if (super_method->IsOverridableByDefaultMethod()) {
8016 // We didn't directly override this method but we might through default methods...
8017 // Check for default method update.
8018 ArtMethod* default_method = nullptr;
8019 switch (class_linker_->FindDefaultMethodImplementation(self,
8020 super_method,
8021 klass,
8022 /*out*/&default_method)) {
8023 case DefaultMethodSearchResult::kDefaultConflict: {
8024 // A conflict was found looking for default methods. Note this (assuming it wasn't
8025 // pre-existing) in the translations map.
8026 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
8027 // Don't generate another conflict method to reduce memory use as an optimization.
8028 default_translations_.insert(
8029 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
8030 }
8031 break;
8032 }
8033 case DefaultMethodSearchResult::kAbstractFound: {
8034 // No conflict but method is abstract.
8035 // We note that this vtable entry must be made abstract.
8036 if (UNLIKELY(!super_method->IsAbstract())) {
8037 default_translations_.insert(
8038 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
8039 }
8040 break;
8041 }
8042 case DefaultMethodSearchResult::kDefaultFound: {
8043 if (UNLIKELY(super_method->IsDefaultConflicting() ||
8044 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
8045 // Found a default method implementation that is new.
8046 // TODO Refactor this add default methods to virtuals here and not in
8047 // LinkInterfaceMethods maybe.
8048 // The problem is default methods might override previously present
8049 // default-method or miranda-method vtable entries from the superclass.
8050 // Unfortunately we need these to be entries in this class's virtuals. We do not
8051 // give these entries there until LinkInterfaceMethods so we pass this map around
8052 // to let it know which vtable entries need to be updated.
8053 // Make a note that vtable entry j must be updated, store what it needs to be updated
8054 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
8055 // then.
8056 default_translations_.insert(
8057 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
8058 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
8059 << " overridden by default "
8060 << default_method->PrettyMethod()
8061 << " in " << mirror::Class::PrettyClass(klass.Get());
8062 }
8063 break;
8064 }
8065 }
8066 }
8067 }
8068 size_t actual_count = super_vtable_length;
8069 // Add the non-overridden methods at the end.
8070 for (size_t i = 0; i < num_virtual_methods; ++i) {
8071 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size);
8072 size_t method_idx = local_method->GetMethodIndexDuringLinking();
8073 if (method_idx < super_vtable_length &&
8074 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size)) {
8075 continue;
8076 }
8077 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size);
8078 local_method->SetMethodIndex(actual_count);
8079 ++actual_count;
8080 }
8081 if (!IsUint<16>(actual_count)) {
8082 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
8083 return false;
8084 }
8085 // Shrink vtable if possible
8086 CHECK_LE(actual_count, max_count);
8087 if (actual_count < max_count) {
8088 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
8089 mirror::Array::CopyOf(vtable, self, actual_count)));
8090 if (UNLIKELY(vtable == nullptr)) {
8091 self->AssertPendingOOMException();
8092 return false;
8093 }
8094 }
8095 klass->SetVTable(vtable.Get());
8096 } else {
8097 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(class_linker_));
8098 if (!IsUint<16>(num_virtual_methods)) {
8099 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
8100 static_cast<int>(num_virtual_methods));
8101 return false;
8102 }
8103 ObjPtr<mirror::PointerArray> vtable =
8104 class_linker_->AllocPointerArray(self, num_virtual_methods);
8105 if (UNLIKELY(vtable == nullptr)) {
8106 self->AssertPendingOOMException();
8107 return false;
8108 }
8109 for (size_t i = 0; i < num_virtual_methods; ++i) {
8110 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size);
8111 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size);
8112 virtual_method->SetMethodIndex(i & 0xFFFF);
8113 }
8114 klass->SetVTable(vtable);
8115 InitializeObjectVirtualMethodHashes(
8116 klass.Get(),
8117 image_pointer_size,
8118 ArrayRef<uint32_t>(class_linker_->object_virtual_method_hashes_));
8119 }
8120 return true;
8121}
8122
Alex Light705ad492015-09-21 11:36:30 -07008123// TODO This method needs to be split up into several smaller methods.
Vladimir Markobc893672021-11-10 15:25:46 +00008124bool ClassLinker::LinkMethodsHelper::LinkInterfaceMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07008125 Thread* self,
8126 Handle<mirror::Class> klass,
Vladimir Markobc893672021-11-10 15:25:46 +00008127 Runtime* runtime,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008128 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008129 ArtMethod** out_imt) {
Vladimir Markobc893672021-11-10 15:25:46 +00008130 const PointerSize image_pointer_size = class_linker_->GetImagePointerSize();
Alex Lighteb7c1442015-08-31 13:17:42 -07008131 StackHandleScope<3> hs(self);
Alex Light705ad492015-09-21 11:36:30 -07008132
8133 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008134 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008135 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008136 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008137 const size_t ifcount = klass->GetIfTableCount();
8138
Vladimir Marko921094a2017-01-12 18:37:06 +00008139 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008140
8141 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8142 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008143 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008144 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008145 const bool extend_super_iftable = has_superclass;
8146 if (has_superclass && fill_tables) {
Vladimir Markobc893672021-11-10 15:25:46 +00008147 class_linker_->FillImtFromSuperClass(klass,
8148 unimplemented_method,
8149 imt_conflict_method,
8150 out_new_conflict,
8151 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008152 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008153 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8154 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008155 if (fill_tables) {
Vladimir Markobc893672021-11-10 15:25:46 +00008156 if (!class_linker_->AllocateIfTableMethodArrays(self, klass, iftable)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008157 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008158 }
8159 }
8160
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008161 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008162 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008163 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8164 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8165 // they will already be null. This has the additional benefit that the declarer of a miranda
8166 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008167 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008168 --i;
Alex Light9139e002015-10-09 15:59:48 -07008169 DCHECK_LT(i, ifcount);
8170
Alex Light705ad492015-09-21 11:36:30 -07008171 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008172 if (num_methods > 0) {
8173 StackHandleScope<2> hs2(self);
8174 const bool is_super = i < super_ifcount;
8175 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008176 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8177 // conflict methods. Just set this as nullptr in those cases.
8178 Handle<mirror::PointerArray> method_array(fill_tables
8179 ? hs2.NewHandle(iftable->GetMethodArray(i))
8180 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008181
Alex Lighte64300b2015-12-15 15:02:47 -08008182 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008183 ScopedNullHandle<mirror::PointerArray> null_handle;
8184 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008185 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008186
Alex Light9139e002015-10-09 15:59:48 -07008187 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8188 // and confusing. Default methods should always look through all the superclasses
8189 // because they are the last choice of an implementation. We get around this by looking
8190 // at the super-classes iftable methods (copied into method_array previously) when we are
8191 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008192 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008193 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008194 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008195 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008196 using_virtuals = true;
Vladimir Markobc893672021-11-10 15:25:46 +00008197 input_virtual_methods = klass->GetDeclaredVirtualMethodsSlice(image_pointer_size);
Alex Lighte64300b2015-12-15 15:02:47 -08008198 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008199 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008200 // For a new interface, however, we need the whole vtable in case a new
8201 // interface method is implemented in the whole superclass.
8202 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008203 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008204 input_vtable_array = vtable;
8205 input_array_length = input_vtable_array->GetLength();
8206 }
Alex Lighte64300b2015-12-15 15:02:47 -08008207
Alex Lighteb7c1442015-08-31 13:17:42 -07008208 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008209 for (size_t j = 0; j < num_methods; ++j) {
Vladimir Markobc893672021-11-10 15:25:46 +00008210 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008211 MethodNameAndSignatureComparator interface_name_comparator(
Vladimir Markobc893672021-11-10 15:25:46 +00008212 interface_method->GetInterfaceMethodIfProxy(image_pointer_size));
David Srbeckye36e7f22018-11-14 14:21:23 +00008213 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008214 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008215 // For each method listed in the interface's method list, find the
8216 // matching method in our class's method list. We want to favor the
8217 // subclass over the superclass, which just requires walking
8218 // back from the end of the vtable. (This only matters if the
8219 // superclass defines a private method and this class redefines
8220 // it -- otherwise it would use the same vtable slot. In .dex files
8221 // those don't end up in the virtual method table, so it shouldn't
8222 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008223 //
8224 // To find defaults we need to do the same but also go over interfaces.
8225 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008226 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008227 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008228 ArtMethod* vtable_method = using_virtuals ?
8229 &input_virtual_methods[k] :
Vladimir Markobc893672021-11-10 15:25:46 +00008230 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008231 ArtMethod* vtable_method_for_name_comparison =
Vladimir Markobc893672021-11-10 15:25:46 +00008232 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size);
Alex Lighta467a6e2020-03-23 16:07:29 -07008233 DCHECK(!vtable_method->IsStatic()) << vtable_method->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008234 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008235 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008236 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008237 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8238 // allocations.
8239 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008240 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008241 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008242 vtable_method->PrettyMethod().c_str(),
8243 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008244 return false;
Alex Light9139e002015-10-09 15:59:48 -07008245 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008246 // We might have a newer, better, default method for this, so we just skip it. If we
8247 // are still using this we will select it again when scanning for default methods. To
8248 // obviate the need to copy the method again we will make a note that we already found
8249 // a default here.
8250 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008251 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008252 break;
8253 } else {
8254 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008255 if (LIKELY(fill_tables)) {
Vladimir Markobc893672021-11-10 15:25:46 +00008256 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size);
Alex Light705ad492015-09-21 11:36:30 -07008257 // Place method in imt if entry is empty, place conflict otherwise.
Vladimir Markobc893672021-11-10 15:25:46 +00008258 class_linker_->SetIMTRef(unimplemented_method,
8259 imt_conflict_method,
8260 vtable_method,
8261 /*out*/out_new_conflict,
8262 /*out*/imt_ptr);
Alex Light705ad492015-09-21 11:36:30 -07008263 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008264 break;
8265 }
8266 }
Alex Light9139e002015-10-09 15:59:48 -07008267 }
8268 // Continue on to the next method if we are done.
8269 if (LIKELY(found_impl)) {
8270 continue;
8271 } else if (LIKELY(super_interface)) {
8272 // Don't look for a default implementation when the super-method is implemented directly
8273 // by the class.
8274 //
8275 // See if we can use the superclasses method and skip searching everything else.
8276 // Note: !found_impl && super_interface
8277 CHECK(extend_super_iftable);
8278 // If this is a super_interface method it is possible we shouldn't override it because a
8279 // superclass could have implemented it directly. We get the method the superclass used
8280 // to implement this to know if we can override it with a default method. Doing this is
8281 // safe since we know that the super_iftable is filled in so we can simply pull it from
8282 // there. We don't bother if this is not a super-classes interface since in that case we
8283 // have scanned the entire vtable anyway and would have found it.
8284 // TODO This is rather dirty but it is faster than searching through the entire vtable
8285 // every time.
8286 ArtMethod* supers_method =
Vladimir Markobc893672021-11-10 15:25:46 +00008287 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size);
Alex Light9139e002015-10-09 15:59:48 -07008288 DCHECK(supers_method != nullptr);
8289 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008290 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008291 // The method is not overridable by a default method (i.e. it is directly implemented
8292 // in some class). Therefore move onto the next interface method.
8293 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008294 } else {
8295 // If the super-classes method is override-able by a default method we need to keep
8296 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8297 // If it turns out not to be overridden and we did not keep track of it we might add it
Alex Light66630be2016-05-04 09:23:09 -07008298 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8299 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8300 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008301 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008302 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8303 << " and not 'nullptr' or "
8304 << supers_method->PrettyMethod()
8305 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008306 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008307 }
8308 }
8309 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Markobc893672021-11-10 15:25:46 +00008310 ArtMethod* current_method = FindOrCreateImplementationMethod(
8311 interface_method, interface_name_comparator, vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008312 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008313 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008314 // We could not find an implementation for this method and since it is a brand new
8315 // interface we searched the entire vtable (and all default methods) for an
8316 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Markobc893672021-11-10 15:25:46 +00008317 current_method = GetOrCreateMirandaMethod(interface_method,
8318 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008319 }
8320
8321 if (current_method != nullptr) {
8322 // We found a default method implementation. Record it in the iftable and IMT.
Vladimir Markobc893672021-11-10 15:25:46 +00008323 method_array->SetElementPtrSize(j, current_method, image_pointer_size);
8324 class_linker_->SetIMTRef(unimplemented_method,
8325 imt_conflict_method,
8326 current_method,
8327 /*out*/out_new_conflict,
8328 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008329 }
8330 }
Alex Light705ad492015-09-21 11:36:30 -07008331 } // For each method in interface end.
8332 } // if (num_methods > 0)
8333 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008334 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Markobc893672021-11-10 15:25:46 +00008335 if (HasNewVirtuals()) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008336 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
Vladimir Markobc893672021-11-10 15:25:46 +00008337 ReallocMethods(); // No return value to check. Native allocation failure aborts.
Vladimir Marko921094a2017-01-12 18:37:06 +00008338 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8339
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008340 // Done copying methods, they are all roots in the class now, so we can end the no thread
Mathieu Chartiere401d142015-04-22 13:56:20 -07008341 // suspension assert.
8342 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008343
Alex Light705ad492015-09-21 11:36:30 -07008344 if (fill_tables) {
Vladimir Markobc893672021-11-10 15:25:46 +00008345 vtable.Assign(UpdateVtable(vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008346 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008347 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008348 return false;
8349 }
Vladimir Markobc893672021-11-10 15:25:46 +00008350 UpdateIfTable(iftable);
8351 UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008352 }
Alex Light705ad492015-09-21 11:36:30 -07008353
Vladimir Markobc893672021-11-10 15:25:46 +00008354 CheckNoStaleMethodsInDexCache();
8355 ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008356 } else {
8357 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008358 }
Alex Light705ad492015-09-21 11:36:30 -07008359 if (kIsDebugBuild && !is_interface) {
Vladimir Markobc893672021-11-10 15:25:46 +00008360 CheckVTable(self, klass, image_pointer_size);
Elliott Hughes4681c802011-09-25 18:04:37 -07008361 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008362 return true;
8363}
8364
Vladimir Markobc893672021-11-10 15:25:46 +00008365// Populate the class vtable and itable. Compute return type indices.
8366bool ClassLinker::LinkMethods(Thread* self,
8367 Handle<mirror::Class> klass,
8368 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
8369 bool* out_new_conflict,
8370 ArtMethod** out_imt) {
8371 self->AllowThreadSuspension();
8372 // We set up the interface lookup table first because we need it to determine if we need
8373 // to update any vtable entries with new default method implementations.
8374 if (!SetupInterfaceLookupTable(self, klass, interfaces)) {
8375 return false;
8376 }
8377 // Link virtual methods then interface methods.
8378 Runtime* const runtime = Runtime::Current();
8379 LinkMethodsHelper helper(this, klass, self, runtime);
8380 return helper.LinkVirtualMethods(self, klass) &&
8381 helper.LinkInterfaceMethods(self, klass, runtime, out_new_conflict, out_imt);
8382}
8383
Vladimir Marko42bee502021-01-28 14:58:35 +00008384class ClassLinker::LinkFieldsHelper {
8385 public:
8386 static bool LinkFields(ClassLinker* class_linker,
8387 Thread* self,
8388 Handle<mirror::Class> klass,
8389 bool is_static,
8390 size_t* class_size)
8391 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008392
Vladimir Marko42bee502021-01-28 14:58:35 +00008393 private:
8394 enum class FieldTypeOrder : uint16_t;
8395 class FieldGaps;
8396
8397 struct FieldTypeOrderAndIndex {
8398 FieldTypeOrder field_type_order;
8399 uint16_t field_index;
8400 };
8401
8402 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8403
8404 template <size_t kSize>
8405 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8406 REQUIRES_SHARED(Locks::mutator_lock_);
8407};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008408
Vladimir Markoc7993d52021-01-27 15:20:56 +00008409// We use the following order of field types for assigning offsets.
8410// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008411enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008412 kReference = 0u,
8413 kLong,
8414 kDouble,
8415 kInt,
8416 kFloat,
8417 kChar,
8418 kShort,
8419 kBoolean,
8420 kByte,
8421
8422 kLast64BitType = kDouble,
8423 kLast32BitType = kFloat,
8424 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008425};
8426
Vladimir Markoc7993d52021-01-27 15:20:56 +00008427ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008428ClassLinker::LinkFieldsHelper::FieldTypeOrder
8429ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008430 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008431 case 'J':
8432 return FieldTypeOrder::kLong;
8433 case 'D':
8434 return FieldTypeOrder::kDouble;
8435 case 'I':
8436 return FieldTypeOrder::kInt;
8437 case 'F':
8438 return FieldTypeOrder::kFloat;
8439 case 'C':
8440 return FieldTypeOrder::kChar;
8441 case 'S':
8442 return FieldTypeOrder::kShort;
8443 case 'Z':
8444 return FieldTypeOrder::kBoolean;
8445 case 'B':
8446 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008447 default:
8448 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8449 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008450 }
8451}
8452
8453// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008454class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008455 public:
8456 template <uint32_t kSize>
8457 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8458 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8459 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8460 uint32_t gap_start = field_offset.Uint32Value();
8461 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8462 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8463 }
8464 return field_offset;
8465 }
8466
8467 template <uint32_t kSize>
8468 bool HasGap() const {
8469 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8470 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8471 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8472 gap4_offset_ != kNoOffset;
8473 }
8474
8475 template <uint32_t kSize>
8476 MemberOffset ReleaseGap() {
8477 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8478 uint32_t result;
8479 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8480 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8481 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8482 result = gap1_offset_;
8483 gap1_offset_ = kNoOffset;
8484 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8485 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8486 result = gap2_offset_;
8487 gap2_offset_ = kNoOffset;
8488 if (kSize < 2u) {
8489 AddGaps<1u>(result + kSize, result + 2u);
8490 }
8491 } else {
8492 DCHECK_NE(gap4_offset_, kNoOffset);
8493 result = gap4_offset_;
8494 gap4_offset_ = kNoOffset;
8495 if (kSize < 4u) {
8496 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8497 }
8498 }
8499 return MemberOffset(result);
8500 }
8501
8502 private:
8503 template <uint32_t kGapsToCheck>
8504 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8505 if ((kGapsToCheck & 1u) != 0u) {
8506 DCHECK_LT(gap_start, gap_end);
8507 DCHECK_ALIGNED(gap_end, 2u);
8508 if ((gap_start & 1u) != 0u) {
8509 DCHECK_EQ(gap1_offset_, kNoOffset);
8510 gap1_offset_ = gap_start;
8511 gap_start += 1u;
8512 if (kGapsToCheck == 1u || gap_start == gap_end) {
8513 DCHECK_EQ(gap_start, gap_end);
8514 return;
8515 }
8516 }
8517 }
8518
8519 if ((kGapsToCheck & 2u) != 0u) {
8520 DCHECK_LT(gap_start, gap_end);
8521 DCHECK_ALIGNED(gap_start, 2u);
8522 DCHECK_ALIGNED(gap_end, 4u);
8523 if ((gap_start & 2u) != 0u) {
8524 DCHECK_EQ(gap2_offset_, kNoOffset);
8525 gap2_offset_ = gap_start;
8526 gap_start += 2u;
8527 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8528 DCHECK_EQ(gap_start, gap_end);
8529 return;
8530 }
8531 }
8532 }
8533
8534 if ((kGapsToCheck & 4u) != 0u) {
8535 DCHECK_LT(gap_start, gap_end);
8536 DCHECK_ALIGNED(gap_start, 4u);
8537 DCHECK_ALIGNED(gap_end, 8u);
8538 DCHECK_EQ(gap_start + 4u, gap_end);
8539 DCHECK_EQ(gap4_offset_, kNoOffset);
8540 gap4_offset_ = gap_start;
8541 return;
8542 }
8543
8544 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8545 << " after checking " << kGapsToCheck;
8546 }
8547
8548 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8549
8550 uint32_t gap4_offset_ = kNoOffset;
8551 uint32_t gap2_offset_ = kNoOffset;
8552 uint32_t gap1_offset_ = kNoOffset;
8553};
8554
8555template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008556ALWAYS_INLINE
8557MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8558 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008559 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8560 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8561 field->SetOffset(field_offset);
8562 return MemberOffset(field_offset.Uint32Value() + kSize);
8563}
8564
Vladimir Marko42bee502021-01-28 14:58:35 +00008565bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8566 Thread* self,
8567 Handle<mirror::Class> klass,
8568 bool is_static,
8569 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008570 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008571 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008572 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8573 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008574
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008575 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008576 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008577 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008578 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8579 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008580 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008581 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008582 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008583 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008584 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008585 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008586 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008587 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008588
David Sehr709b0702016-10-13 09:12:37 -07008589 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008590
Brian Carlstromdbc05252011-09-09 01:59:59 -07008591 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008592 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008593 //
8594 // The overall sort order order is:
8595 // 1) All object reference fields, sorted alphabetically.
8596 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8597 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8598 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8599 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8600 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8601 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8602 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8603 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8604 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008605 // (References are first to increase the chance of reference visiting
8606 // being able to take a fast path using a bitmap of references at the
8607 // start of the object, see `Class::reference_instance_offsets_`.)
8608 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008609 // Once the fields are sorted in this order we will attempt to fill any gaps
8610 // that might be present in the memory layout of the structure.
8611 // Note that we shall not fill gaps between the superclass fields.
8612
8613 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008614 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008615 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008616 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8617 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8618 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8619 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008620 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008621 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008622 } else {
8623 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008624 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008625 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008626 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008627 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008628 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008629 for (size_t i = 0; i != num_fields; ++i) {
8630 ArtField* field = &fields->At(i);
8631 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008632 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8633 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008634 // Insert references to the start, other fields to the end.
8635 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008636 if (field_type_order == FieldTypeOrder::kReference) {
8637 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008638 ++num_reference_fields;
8639 } else {
8640 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008641 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008642 }
8643 }
8644 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008645
Vladimir Marko42bee502021-01-28 14:58:35 +00008646 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008647 DCHECK(std::is_sorted(
8648 sorted_fields.begin(),
8649 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008650 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8651 ArtField* lhs_field = &fields->At(lhs.field_index);
8652 ArtField* rhs_field = &fields->At(rhs.field_index);
8653 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8654 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8655 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8656 lhs.field_index < rhs.field_index);
8657 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008658 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008659 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008660 DCHECK(std::is_sorted(
8661 sorted_fields.begin() + primitive_fields_start,
8662 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008663 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8664 ArtField* lhs_field = &fields->At(lhs.field_index);
8665 ArtField* rhs_field = &fields->At(rhs.field_index);
8666 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8667 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8668 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8669 lhs.field_index > rhs.field_index);
8670 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008671 }));
8672 // Sort the primitive fields by the field type order, then field index.
8673 std::sort(sorted_fields.begin() + primitive_fields_start,
8674 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008675 [](const auto& lhs, const auto& rhs) {
8676 if (lhs.field_type_order != rhs.field_type_order) {
8677 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008678 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008679 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008680 }
8681 });
8682 // Primitive fields are now sorted by field size (descending), then type, then field index.
8683 DCHECK(std::is_sorted(
8684 sorted_fields.begin() + primitive_fields_start,
8685 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008686 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8687 ArtField* lhs_field = &fields->At(lhs.field_index);
8688 ArtField* rhs_field = &fields->At(rhs.field_index);
8689 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008690 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008691 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008692 CHECK_NE(rhs_type, Primitive::kPrimNot);
8693 if (lhs_type != rhs_type) {
8694 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8695 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8696 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8697 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008698 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008699 }
8700 }));
8701
8702 // Process reference fields.
8703 FieldGaps field_gaps;
8704 size_t index = 0u;
8705 if (num_reference_fields != 0u) {
8706 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8707 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8708 for (; index != num_reference_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008709 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008710 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008711 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008712 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008713 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008714 if (index != num_fields &&
8715 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008716 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008717 while (index != num_fields &&
8718 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8719 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008720 field_offset = AssignFieldOffset<8u>(field, field_offset);
8721 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008722 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008723 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008724 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008725 if (index != num_fields &&
8726 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008727 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8728 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008729 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008730 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8731 ++index;
8732 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8733 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008734 while (index != num_fields &&
8735 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8736 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008737 field_offset = AssignFieldOffset<4u>(field, field_offset);
8738 ++index;
8739 }
8740 }
8741 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008742 if (index != num_fields &&
8743 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008744 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8745 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008746 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008747 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008748 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008749 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8750 ++index;
8751 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008752 while (index != num_fields &&
8753 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8754 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008755 field_offset = AssignFieldOffset<2u>(field, field_offset);
8756 ++index;
8757 }
8758 }
8759 // Process 8-bit fields.
8760 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008761 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008762 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8763 }
8764 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008765 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008766 field_offset = AssignFieldOffset<1u>(field, field_offset);
8767 }
8768
Ian Rogers7b078e82014-09-10 14:44:24 -07008769 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008770
Elliott Hughesadb460d2011-10-05 17:02:34 -07008771 // 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 +00008772 DCHECK(!class_linker->init_done_ || !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
8773 if (!is_static &&
8774 UNLIKELY(!class_linker->init_done_) &&
8775 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008776 // We know there are no non-reference fields in the Reference classes, and we know
8777 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008778 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008779 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008780 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008781 --num_reference_fields;
8782 }
8783
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008784 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008785 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008786 if (is_static) {
8787 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008788 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008789 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008790 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008791 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008792 if (num_reference_fields == 0 || super_class == nullptr) {
8793 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008794 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008795 if (super_class == nullptr ||
8796 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8797 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008798 }
8799 }
8800 if (kIsDebugBuild) {
8801 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8802 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008803 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008804 while (cur_super != nullptr) {
8805 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8806 cur_super = cur_super->GetSuperClass();
8807 }
8808 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008809 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008810 } else {
8811 // Check that there is at least num_reference_fields other than Object.class.
8812 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008813 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008814 }
8815 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008816 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008817 std::string temp;
8818 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8819 size_t previous_size = klass->GetObjectSize();
8820 if (previous_size != 0) {
8821 // Make sure that we didn't originally have an incorrect size.
8822 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008823 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008824 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008825 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008826 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008827
8828 if (kIsDebugBuild) {
8829 // Make sure that the fields array is ordered by name but all reference
8830 // offsets are at the beginning as far as alignment allows.
8831 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00008832 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008833 : klass->GetFirstReferenceInstanceFieldOffset();
8834 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8835 num_reference_fields *
8836 sizeof(mirror::HeapReference<mirror::Object>));
8837 MemberOffset current_ref_offset = start_ref_offset;
8838 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008839 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008840 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008841 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8842 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008843 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008844 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008845 // NOTE: The field names can be the same. This is not possible in the Java language
8846 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008847 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008848 }
8849 Primitive::Type type = field->GetTypeAsPrimitiveType();
8850 bool is_primitive = type != Primitive::kPrimNot;
8851 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8852 strcmp("referent", field->GetName()) == 0) {
8853 is_primitive = true; // We lied above, so we have to expect a lie here.
8854 }
8855 MemberOffset offset = field->GetOffsetDuringLinking();
8856 if (is_primitive) {
8857 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8858 // Shuffled before references.
8859 size_t type_size = Primitive::ComponentSize(type);
8860 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8861 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8862 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8863 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8864 }
8865 } else {
8866 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8867 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8868 sizeof(mirror::HeapReference<mirror::Object>));
8869 }
8870 }
8871 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8872 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008873 return true;
8874}
8875
Vladimir Marko42bee502021-01-28 14:58:35 +00008876bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
8877 CHECK(klass != nullptr);
8878 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
8879}
8880
8881bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
8882 CHECK(klass != nullptr);
8883 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
8884}
8885
Vladimir Marko76649e82014-11-10 18:32:59 +00008886// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008887void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008888 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008889 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008890 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008891 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008892 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008893 // Compute reference offsets unless our superclass overflowed.
8894 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8895 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008896 if (num_reference_fields != 0u) {
8897 // All of the fields that contain object references are guaranteed be grouped in memory
8898 // starting at an appropriately aligned address after super class object data.
8899 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8900 sizeof(mirror::HeapReference<mirror::Object>));
8901 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008902 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008903 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008904 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008905 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008906 reference_offsets |= (0xffffffffu << start_bit) &
8907 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008908 }
8909 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008910 }
8911 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008912 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008913}
8914
Vladimir Marko18090d12018-06-01 16:53:12 +01008915ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8916 ObjPtr<mirror::DexCache> dex_cache) {
8917 StackHandleScope<1> hs(Thread::Current());
8918 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8919 return DoResolveString(string_idx, h_dex_cache);
8920}
8921
8922ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8923 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008924 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008925 uint32_t utf16_length;
8926 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008927 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008928 if (string != nullptr) {
8929 dex_cache->SetResolvedString(string_idx, string);
8930 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008931 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008932}
8933
Vladimir Marko18090d12018-06-01 16:53:12 +01008934ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8935 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008936 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008937 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008938 uint32_t utf16_length;
8939 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008940 ObjPtr<mirror::String> string =
8941 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008942 if (string != nullptr) {
8943 dex_cache->SetResolvedString(string_idx, string);
8944 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008945 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008946}
8947
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008948ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008949 ObjPtr<mirror::Class> referrer) {
8950 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8951}
8952
8953ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008954 ObjPtr<mirror::DexCache> dex_cache,
8955 ObjPtr<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01008956 DCHECK(dex_cache->GetClassLoader() == class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008957 const DexFile& dex_file = *dex_cache->GetDexFile();
8958 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Vladimir Markoc63d9672021-03-31 15:50:39 +01008959 ObjPtr<mirror::Class> type = LookupResolvedType(descriptor, class_loader);
8960 if (type != nullptr) {
8961 DCHECK(type->IsResolved());
8962 dex_cache->SetResolvedType(type_idx, type);
8963 }
8964 return type;
8965}
8966
8967ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const char* descriptor,
8968 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008969 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8970 ObjPtr<mirror::Class> type = nullptr;
8971 if (descriptor[1] == '\0') {
8972 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8973 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008974 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008975 } else {
8976 Thread* const self = Thread::Current();
8977 DCHECK(self != nullptr);
8978 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8979 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008980 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008981 }
Vladimir Markoc63d9672021-03-31 15:50:39 +01008982 return (type != nullptr && type->IsResolved()) ? type : nullptr;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008983}
8984
Andreas Gampeb0625e02019-05-01 12:43:31 -07008985template <typename RefType>
8986ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008987 StackHandleScope<2> hs(Thread::Current());
8988 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8989 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8990 return DoResolveType(type_idx, dex_cache, class_loader);
8991}
8992
Andreas Gampe4835d212018-11-21 14:55:10 -08008993// Instantiate the above.
8994template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8995 ArtField* referrer);
8996template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8997 ArtMethod* referrer);
8998template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8999 ObjPtr<mirror::Class> referrer);
9000
Vladimir Marko09c5ca42018-05-31 15:15:31 +01009001ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009002 Handle<mirror::DexCache> dex_cache,
9003 Handle<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009004 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009005 Thread* self = Thread::Current();
9006 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
9007 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
9008 if (resolved != nullptr) {
9009 // TODO: we used to throw here if resolved's class loader was not the
9010 // boot class loader. This was to permit different classes with the
9011 // same name to be loaded simultaneously by different loaders
9012 dex_cache->SetResolvedType(type_idx, resolved);
9013 } else {
9014 CHECK(self->IsExceptionPending())
9015 << "Expected pending exception for failed resolution of: " << descriptor;
9016 // Convert a ClassNotFoundException to a NoClassDefFoundError.
9017 StackHandleScope<1> hs(self);
9018 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009019 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009020 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
9021 self->ClearException();
9022 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
9023 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009024 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009025 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00009026 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07009027 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00009028 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009029}
9030
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009031ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
9032 ObjPtr<mirror::DexCache> dex_cache,
9033 ObjPtr<mirror::ClassLoader> class_loader,
9034 uint32_t method_idx) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009035 DCHECK(dex_cache->GetClassLoader() == class_loader);
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009036 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
9037 // functions can optimize the search if the dex_cache is the same as the DexCache
9038 // of the class, with fall-back to name and signature search otherwise.
9039 ArtMethod* resolved = nullptr;
9040 if (klass->IsInterface()) {
9041 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9042 } else {
9043 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9044 }
9045 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009046 if (resolved != nullptr &&
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009047 // We pass AccessMethod::kNone instead of kLinking to not warn yet on the
9048 // access, as we'll be looking if the method can be accessed through an
9049 // interface.
David Brazdilf50ac102018-10-17 18:00:06 +01009050 hiddenapi::ShouldDenyAccessToMember(resolved,
9051 hiddenapi::AccessContext(class_loader, dex_cache),
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009052 hiddenapi::AccessMethod::kNone)) {
9053 // The resolved method that we have found cannot be accessed due to
9054 // hiddenapi (typically it is declared up the hierarchy and is not an SDK
9055 // method). Try to find an interface method from the implemented interfaces which is
Nicolas Geoffrayaf61f502021-03-31 16:03:50 +00009056 // part of the SDK.
9057 ArtMethod* itf_method = klass->FindAccessibleInterfaceMethod(resolved, image_pointer_size_);
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009058 if (itf_method == nullptr) {
9059 // No interface method. Call ShouldDenyAccessToMember again but this time
9060 // with AccessMethod::kLinking to ensure that an appropriate warning is
9061 // logged.
9062 hiddenapi::ShouldDenyAccessToMember(resolved,
9063 hiddenapi::AccessContext(class_loader, dex_cache),
9064 hiddenapi::AccessMethod::kLinking);
9065 resolved = nullptr;
9066 } else {
9067 // We found an interface method that is accessible, continue with the resolved method.
9068 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009069 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009070 if (resolved != nullptr) {
9071 // In case of jmvti, the dex file gets verified before being registered, so first
9072 // check if it's registered before checking class tables.
9073 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009074 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
9075 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009076 << "DexFile referrer: " << dex_file.GetLocation()
9077 << " ClassLoader: " << DescribeLoaders(class_loader, "");
9078 // Be a good citizen and update the dex cache to speed subsequent calls.
David Srbecky5de5efe2021-02-15 21:23:00 +00009079 dex_cache->SetResolvedMethod(method_idx, resolved);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009080 // Disable the following invariant check as the verifier breaks it. b/73760543
9081 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
9082 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
9083 // << "Method: " << resolved->PrettyMethod() << ", "
9084 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
9085 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009086 }
9087 return resolved;
9088}
9089
David Brazdil4525e0b2018-04-05 16:57:32 +01009090// Returns true if `method` is either null or hidden.
9091// Does not print any warnings if it is hidden.
9092static bool CheckNoSuchMethod(ArtMethod* method,
9093 ObjPtr<mirror::DexCache> dex_cache,
9094 ObjPtr<mirror::ClassLoader> class_loader)
9095 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009096 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
David Brazdil4525e0b2018-04-05 16:57:32 +01009097 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01009098 hiddenapi::ShouldDenyAccessToMember(method,
9099 hiddenapi::AccessContext(class_loader, dex_cache),
9100 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01009101}
9102
9103ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
9104 ObjPtr<mirror::DexCache> dex_cache,
9105 ObjPtr<mirror::ClassLoader> class_loader,
9106 uint32_t method_idx) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009107 DCHECK(dex_cache->GetClassLoader() == class_loader);
David Brazdil4525e0b2018-04-05 16:57:32 +01009108 if (klass->IsInterface()) {
9109 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9110 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
9111 } else {
9112 // If there was an interface method with the same signature, we would have
9113 // found it in the "copied" methods. Only DCHECK that the interface method
9114 // really does not exist.
9115 if (kIsDebugBuild) {
9116 ArtMethod* method =
9117 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9118 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
9119 }
9120 return nullptr;
9121 }
9122}
9123
Vladimir Marko89011192017-12-11 13:45:05 +00009124ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009125 Handle<mirror::DexCache> dex_cache,
9126 Handle<mirror::ClassLoader> class_loader) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009127 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
David Srbecky5de5efe2021-02-15 21:23:00 +00009128 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009129 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009130 if (resolved != nullptr) {
9131 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009132 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9133 return resolved;
9134 }
9135 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009136 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009137 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009138 if (klass == nullptr) {
9139 Thread::Current()->AssertPendingException();
9140 return nullptr;
9141 }
9142 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009143 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9144 } else {
9145 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009146 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009147 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009148 hiddenapi::ShouldDenyAccessToMember(
9149 resolved,
9150 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9151 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009152 resolved = nullptr;
9153 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009154 return resolved;
9155}
9156
Vladimir Markof44d36c2017-03-14 14:18:46 +00009157ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9158 ObjPtr<mirror::DexCache> dex_cache,
9159 ObjPtr<mirror::ClassLoader> class_loader,
9160 bool is_static) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009161 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009162 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009163 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009164 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9165 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009166 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009167 }
9168 if (klass == nullptr) {
9169 // The class has not been resolved yet, so the field is also unresolved.
9170 return nullptr;
9171 }
9172 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009173
David Brazdil1ab0fa82018-05-04 11:28:03 +01009174 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009175}
9176
Vladimir Markoe11dd502017-12-08 14:09:45 +00009177ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009178 Handle<mirror::DexCache> dex_cache,
9179 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009180 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009181 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
David Srbecky5de5efe2021-02-15 21:23:00 +00009182 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009183 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009184 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009185 return resolved;
9186 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009187 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009188 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009189 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009190 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009191 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009192 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009193 }
9194
David Brazdil1ab0fa82018-05-04 11:28:03 +01009195 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9196 if (resolved == nullptr) {
9197 const char* name = dex_file.GetFieldName(field_id);
9198 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009199 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009200 }
9201 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009202}
9203
David Brazdil1ab0fa82018-05-04 11:28:03 +01009204ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9205 ObjPtr<mirror::DexCache> dex_cache,
9206 ObjPtr<mirror::ClassLoader> class_loader,
9207 uint32_t field_idx,
9208 bool is_static) {
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009209 DCHECK(dex_cache->GetClassLoader() == class_loader);
Vladimir Markob10668c2021-06-10 09:52:53 +01009210 ArtField* resolved = is_static ? klass->FindStaticField(dex_cache, field_idx)
9211 : klass->FindInstanceField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009212 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009213 hiddenapi::ShouldDenyAccessToMember(resolved,
9214 hiddenapi::AccessContext(class_loader, dex_cache),
9215 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009216 resolved = nullptr;
9217 }
9218
9219 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009220 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009221 }
9222
9223 return resolved;
9224}
9225
9226ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9227 ObjPtr<mirror::DexCache> dex_cache,
9228 ObjPtr<mirror::ClassLoader> class_loader,
9229 uint32_t field_idx) {
Nicolas Geoffrayc07f4882021-09-13 09:20:33 +01009230 DCHECK(dex_cache->GetClassLoader().Ptr() == class_loader.Ptr());
Vladimir Markob10668c2021-06-10 09:52:53 +01009231 ArtField* resolved = klass->FindField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009232
9233 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009234 hiddenapi::ShouldDenyAccessToMember(resolved,
9235 hiddenapi::AccessContext(class_loader, dex_cache),
9236 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009237 resolved = nullptr;
9238 }
9239
9240 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009241 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009242 }
9243
9244 return resolved;
9245}
9246
Vladimir Markoaf940202017-12-08 15:01:18 +00009247ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9248 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009249 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009250 Handle<mirror::DexCache> dex_cache,
9251 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009252 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009253 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayab91eef2021-09-14 09:48:51 +01009254 DCHECK(dex_cache->GetClassLoader() == class_loader.Get());
Narayan Kamath25352fc2016-08-03 12:46:58 +01009255
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009256 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009257 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009258 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009259 }
9260
Narayan Kamath25352fc2016-08-03 12:46:58 +01009261 StackHandleScope<4> hs(self);
9262
9263 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009264 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009265 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009266 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009267 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009268 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009269 DCHECK(self->IsExceptionPending());
9270 return nullptr;
9271 }
9272
9273 // Then resolve the argument types.
9274 //
9275 // TODO: Is there a better way to figure out the number of method arguments
9276 // other than by looking at the shorty ?
9277 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9278
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009279 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009280 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9281 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009282 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009283 DCHECK(self->IsExceptionPending());
9284 return nullptr;
9285 }
9286
9287 DexFileParameterIterator it(dex_file, proto_id);
9288 int32_t i = 0;
9289 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9290 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009291 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009292 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009293 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009294 DCHECK(self->IsExceptionPending());
9295 return nullptr;
9296 }
9297
9298 method_params->Set(i++, param_class.Get());
9299 }
9300
9301 DCHECK(!it.HasNext());
9302
9303 Handle<mirror::MethodType> type = hs.NewHandle(
9304 mirror::MethodType::Create(self, return_type, method_params));
Nicolas Geoffray4aebd582021-07-23 15:27:31 +01009305 if (type != nullptr) {
9306 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9307 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01009308
9309 return type.Get();
9310}
9311
Vladimir Markoaf940202017-12-08 15:01:18 +00009312ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009313 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009314 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009315 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009316 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9317 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009318 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009319}
9320
Vladimir Marko5aead702019-03-27 11:00:36 +00009321ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009322 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009323 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009324 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009325 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009326 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9327 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009328 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009329 bool is_static;
9330 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009331 switch (handle_type) {
9332 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009333 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009334 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009335 is_static = true;
9336 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009337 break;
9338 }
9339 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009340 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009341 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009342 is_static = true;
9343 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009344 break;
9345 }
9346 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009347 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009348 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009349 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009350 num_params = 2;
9351 break;
9352 }
9353 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009354 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009355 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009356 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009357 num_params = 1;
9358 break;
9359 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009360 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009361 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009362 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009363 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009364 case DexFile::MethodHandleType::kInvokeInterface:
9365 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009366 }
9367
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009368 ArtField* target_field =
9369 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9370 if (LIKELY(target_field != nullptr)) {
9371 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9372 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9373 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9374 ThrowIllegalAccessErrorField(referring_class, target_field);
9375 return nullptr;
9376 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009377 if (UNLIKELY(is_put && target_field->IsFinal())) {
9378 ThrowIllegalAccessErrorField(referring_class, target_field);
9379 return nullptr;
9380 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009381 } else {
9382 DCHECK(Thread::Current()->IsExceptionPending());
9383 return nullptr;
9384 }
9385
9386 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009387 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009388 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9389 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009390 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009391 DCHECK(self->IsExceptionPending());
9392 return nullptr;
9393 }
9394
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009395 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009396 Handle<mirror::Class> return_type;
9397 switch (handle_type) {
9398 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009399 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009400 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009401 break;
9402 }
9403 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009404 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009405 break;
9406 }
9407 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009408 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009409 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009410 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009411 break;
9412 }
9413 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009414 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009415 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009416 break;
9417 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009418 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009419 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009420 case DexFile::MethodHandleType::kInvokeConstructor:
9421 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009422 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009423 UNREACHABLE();
9424 }
9425
9426 for (int32_t i = 0; i < num_params; ++i) {
9427 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9428 DCHECK(self->IsExceptionPending());
9429 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009430 }
9431 }
9432
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009433 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009434 DCHECK(self->IsExceptionPending());
9435 return nullptr;
9436 }
9437
9438 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009439 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9440 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009441 DCHECK(self->IsExceptionPending());
9442 return nullptr;
9443 }
Orion Hodson631827d2017-04-10 14:53:47 +01009444
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009445 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9446 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9447}
9448
Vladimir Marko5aead702019-03-27 11:00:36 +00009449ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009450 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009451 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009452 ArtMethod* referrer) {
9453 DexFile::MethodHandleType handle_type =
9454 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9455 mirror::MethodHandle::Kind kind;
9456 uint32_t receiver_count = 0;
9457 ArtMethod* target_method = nullptr;
9458 switch (handle_type) {
9459 case DexFile::MethodHandleType::kStaticPut:
9460 case DexFile::MethodHandleType::kStaticGet:
9461 case DexFile::MethodHandleType::kInstancePut:
9462 case DexFile::MethodHandleType::kInstanceGet:
9463 UNREACHABLE();
9464 case DexFile::MethodHandleType::kInvokeStatic: {
9465 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9466 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009467 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9468 method_handle.field_or_method_idx_,
9469 referrer,
9470 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009471 break;
9472 }
9473 case DexFile::MethodHandleType::kInvokeInstance: {
9474 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9475 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009476 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9477 method_handle.field_or_method_idx_,
9478 referrer,
9479 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009480 break;
9481 }
9482 case DexFile::MethodHandleType::kInvokeConstructor: {
9483 // Constructors are currently implemented as a transform. They
9484 // are special cased later in this method.
9485 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9486 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009487 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9488 method_handle.field_or_method_idx_,
9489 referrer,
9490 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009491 break;
9492 }
9493 case DexFile::MethodHandleType::kInvokeDirect: {
9494 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9495 receiver_count = 1;
9496 StackHandleScope<2> hs(self);
9497 // A constant method handle with type kInvokeDirect can refer to
9498 // a method that is private or to a method in a super class. To
9499 // disambiguate the two options, we resolve the method ignoring
9500 // the invocation type to determine if the method is private. We
9501 // then resolve again specifying the intended invocation type to
9502 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009503 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009504 hs.NewHandle(referrer->GetDexCache()),
9505 hs.NewHandle(referrer->GetClassLoader()));
9506 if (UNLIKELY(target_method == nullptr)) {
9507 break;
9508 }
9509
9510 if (target_method->IsPrivate()) {
9511 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009512 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9513 method_handle.field_or_method_idx_,
9514 referrer,
9515 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009516 } else {
9517 kind = mirror::MethodHandle::Kind::kInvokeSuper;
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::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009522 if (UNLIKELY(target_method == nullptr)) {
9523 break;
9524 }
9525 // Find the method specified in the parent in referring class
9526 // so invoke-super invokes the method in the parent of the
9527 // referrer.
9528 target_method =
9529 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9530 kRuntimePointerSize);
9531 }
9532 break;
9533 }
9534 case DexFile::MethodHandleType::kInvokeInterface: {
9535 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9536 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009537 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9538 method_handle.field_or_method_idx_,
9539 referrer,
9540 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009541 break;
9542 }
Orion Hodson631827d2017-04-10 14:53:47 +01009543 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009544
9545 if (UNLIKELY(target_method == nullptr)) {
9546 DCHECK(Thread::Current()->IsExceptionPending());
9547 return nullptr;
9548 }
9549
9550 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9551 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9552 uint32_t access_flags = target_method->GetAccessFlags();
9553 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9554 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9555 return nullptr;
9556 }
9557
9558 // Calculate the number of parameters from the method shorty. We add the
9559 // receiver count (0 or 1) and deduct one for the return value.
9560 uint32_t shorty_length;
9561 target_method->GetShorty(&shorty_length);
9562 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9563
Orion Hodsonecd58562018-09-24 11:27:33 +01009564 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009565 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009566 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9567 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9568 if (method_params.Get() == nullptr) {
9569 DCHECK(self->IsExceptionPending());
9570 return nullptr;
9571 }
9572
Orion Hodsonecd58562018-09-24 11:27:33 +01009573 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009574 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009575 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009576 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009577 // Insert receiver. Use the class identified in the method handle rather than the declaring
9578 // class of the resolved method which may be super class or default interface method
9579 // (b/115964401).
9580 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9581 // receiver_class should have been resolved when resolving the target method.
9582 DCHECK(receiver_class != nullptr);
9583 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009584 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009585
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009586 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009587 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009588 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009589 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009590 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009591 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009592 if (nullptr == klass) {
9593 DCHECK(self->IsExceptionPending());
9594 return nullptr;
9595 }
9596 method_params->Set(index++, klass);
9597 it.Next();
9598 }
9599
Orion Hodsonecd58562018-09-24 11:27:33 +01009600 Handle<mirror::Class> return_type =
9601 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009602 if (UNLIKELY(return_type.IsNull())) {
9603 DCHECK(self->IsExceptionPending());
9604 return nullptr;
9605 }
9606
9607 Handle<mirror::MethodType>
9608 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9609 if (UNLIKELY(method_type.IsNull())) {
9610 DCHECK(self->IsExceptionPending());
9611 return nullptr;
9612 }
9613
9614 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9615 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9616 Handle<mirror::MethodHandlesLookup> lookup =
9617 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9618 return lookup->FindConstructor(self, constructor_class, method_type);
9619 }
9620
9621 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9622 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9623}
9624
Vladimir Markoaf940202017-12-08 15:01:18 +00009625ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9626 uint32_t method_handle_idx,
9627 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009628 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009629 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009630 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009631 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9632 case DexFile::MethodHandleType::kStaticPut:
9633 case DexFile::MethodHandleType::kStaticGet:
9634 case DexFile::MethodHandleType::kInstancePut:
9635 case DexFile::MethodHandleType::kInstanceGet:
9636 return ResolveMethodHandleForField(self, method_handle, referrer);
9637 case DexFile::MethodHandleType::kInvokeStatic:
9638 case DexFile::MethodHandleType::kInvokeInstance:
9639 case DexFile::MethodHandleType::kInvokeConstructor:
9640 case DexFile::MethodHandleType::kInvokeDirect:
9641 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009642 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009643 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009644}
9645
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009646bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9647 return (entry_point == GetQuickResolutionStub()) ||
9648 (quick_resolution_trampoline_ == entry_point);
9649}
9650
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009651bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9652 return (entry_point == GetQuickToInterpreterBridge()) ||
9653 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9654}
9655
9656bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9657 return (entry_point == GetQuickGenericJniStub()) ||
9658 (quick_generic_jni_trampoline_ == entry_point);
9659}
9660
David Sehra49e0532017-08-25 08:05:29 -07009661bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009662 return entry_point == GetJniDlsymLookupStub() ||
9663 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009664}
9665
Vladimir Markofa458ac2020-02-12 14:08:07 +00009666bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9667 return entry_point == GetJniDlsymLookupCriticalStub() ||
9668 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9669}
9670
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009671const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9672 return GetQuickGenericJniStub();
9673}
9674
Mathieu Chartiere401d142015-04-22 13:56:20 -07009675void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009676 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009677 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9678 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009679 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009680 }
9681}
9682
Alex Lightdb01a092017-04-03 15:39:55 -07009683void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9684 DCHECK(method->IsObsolete());
9685 // We cannot mess with the entrypoints of native methods because they are used to determine how
9686 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9687 if (!method->IsNative()) {
9688 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9689 }
9690}
9691
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009692void ClassLinker::DumpForSigQuit(std::ostream& os) {
Hans Boehmfb3ad722021-08-16 16:53:17 +00009693 ScopedObjectAccess soa(Thread::Current());
9694 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009695 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9696 << NumNonZygoteClasses() << "\n";
Hans Boehmfb3ad722021-08-16 16:53:17 +00009697 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009698 os << "Dumping registered class loaders\n";
9699 size_t class_loader_index = 0;
9700 for (const ClassLoaderData& class_loader : class_loaders_) {
9701 ObjPtr<mirror::ClassLoader> loader =
Hans Boehmfb3ad722021-08-16 16:53:17 +00009702 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009703 if (loader != nullptr) {
9704 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9705 bool saw_one_dex_file = false;
David Srbecky6fbcc292021-02-23 01:05:32 +00009706 for (const auto& entry : dex_caches_) {
9707 const DexCacheData& dex_cache = entry.second;
9708 if (dex_cache.class_table == class_loader.class_table) {
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009709 if (saw_one_dex_file) {
9710 os << ":";
9711 }
9712 saw_one_dex_file = true;
David Srbecky6fbcc292021-02-23 01:05:32 +00009713 os << entry.first->GetLocation();
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009714 }
9715 }
9716 os << "]";
9717 bool found_parent = false;
9718 if (loader->GetParent() != nullptr) {
9719 size_t parent_index = 0;
9720 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9721 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
Hans Boehmfb3ad722021-08-16 16:53:17 +00009722 soa.Self()->DecodeJObject(class_loader2.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009723 if (loader2 == loader->GetParent()) {
9724 os << ", parent #" << parent_index;
9725 found_parent = true;
9726 break;
9727 }
9728 parent_index++;
9729 }
9730 if (!found_parent) {
9731 os << ", unregistered parent of type "
9732 << loader->GetParent()->GetClass()->PrettyDescriptor();
9733 }
9734 } else {
9735 os << ", no parent";
9736 }
9737 os << "\n";
9738 }
9739 }
9740 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009741 Runtime* runtime = Runtime::Current();
9742 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9743 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009744}
9745
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009746class CountClassesVisitor : public ClassLoaderVisitor {
9747 public:
9748 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9749
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009750 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009751 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009752 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009753 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009754 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9755 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009756 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009757 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009758
9759 size_t num_zygote_classes;
9760 size_t num_non_zygote_classes;
9761};
9762
9763size_t ClassLinker::NumZygoteClasses() const {
9764 CountClassesVisitor visitor;
9765 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009766 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009767}
9768
9769size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009770 CountClassesVisitor visitor;
9771 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009772 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009773}
9774
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009775size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009776 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009777 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009778 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009779}
9780
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009781pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009782 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009783}
9784
9785pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009786 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009787}
9788
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009789void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009790 DCHECK(!init_done_);
9791
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009792 DCHECK(klass != nullptr);
9793 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009794
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009795 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009796 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009797 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9798 int32_t index = static_cast<int32_t>(class_root);
9799 DCHECK(class_roots->Get(index) == nullptr);
9800 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009801}
9802
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009803ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9804 Thread* self,
9805 const std::vector<const DexFile*>& dex_files,
9806 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009807 Handle<mirror::ClassLoader> parent_loader,
Brad Stenning9c924e82021-10-11 19:09:00 -07009808 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries,
9809 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries_after) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009810
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009811 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009812
Mathieu Chartierc7853442015-03-27 14:35:38 -07009813 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009814 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009815
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009816 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009817 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009818 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009819 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009820 mirror::ObjectArray<mirror::Object>::Alloc(self,
9821 dex_elements_class.Get(),
9822 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009823 Handle<mirror::Class> h_dex_element_class =
9824 hs.NewHandle(dex_elements_class->GetComponentType());
9825
Mathieu Chartierc7853442015-03-27 14:35:38 -07009826 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009827 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009828 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009829
Andreas Gampe08883de2016-11-08 13:20:52 -08009830 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009831 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009832
Andreas Gampe08883de2016-11-08 13:20:52 -08009833 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009834 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009835
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009836 // Fill the elements array.
9837 int32_t index = 0;
9838 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009839 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009840
Calin Juravle7865ac72017-06-28 11:03:12 -07009841 // CreateWellKnownClassLoader is only used by gtests and compiler.
9842 // 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 -07009843 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9844 self,
9845 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009846 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009847 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009848
Mathieu Chartier3738e982017-05-12 16:07:28 -07009849 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9850 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009851 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009852 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009853 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009854 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009855
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009856 Handle<mirror::String> h_file_name = hs2.NewHandle(
9857 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009858 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009859 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9860
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009861 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009862 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009863 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009864
9865 h_dex_elements->Set(index, h_element.Get());
9866 index++;
9867 }
9868 DCHECK_EQ(index, h_dex_elements->GetLength());
9869
9870 // Create DexPathList.
9871 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009872 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009873 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009874 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009875 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009876 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9877 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9878 // elements.
9879 {
9880 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9881 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9882 DCHECK(native_lib_dirs != nullptr);
9883 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9884 DCHECK(list_class != nullptr);
9885 {
9886 StackHandleScope<1> h_list_scope(self);
9887 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9888 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9889 DCHECK(list_init);
9890 list_class = h_list_class.Get();
9891 }
9892 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9893 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9894 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9895 // normally never null), as long as one does not try to add elements, this will still
9896 // work.
9897 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9898 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009899
Calin Juravle7865ac72017-06-28 11:03:12 -07009900 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009901 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9902 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009903 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009904 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009905 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009906 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009907 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009908 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009909
9910 // Make a pretend boot-classpath.
9911 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009912 ArtField* const parent_field =
Vladimir Markoe300c4e2021-06-08 16:00:05 +01009913 jni::DecodeArtField(WellKnownClasses::java_lang_ClassLoader_parent);
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009914 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009915 if (parent_loader.Get() == nullptr) {
9916 ScopedObjectAccessUnchecked soa(self);
9917 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9918 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9919 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9920 } else {
9921 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9922 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009923
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009924 ArtField* shared_libraries_field =
9925 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9926 DCHECK(shared_libraries_field != nullptr);
9927 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9928
Brad Stenning9c924e82021-10-11 19:09:00 -07009929 ArtField* shared_libraries_after_field =
9930 jni::DecodeArtField(
9931 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
9932 DCHECK(shared_libraries_after_field != nullptr);
9933 shared_libraries_after_field->SetObject<false>(h_class_loader.Get(),
9934 shared_libraries_after.Get());
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009935 return h_class_loader.Get();
9936}
9937
9938jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9939 const std::vector<const DexFile*>& dex_files,
9940 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009941 jobject parent_loader,
Brad Stenning9c924e82021-10-11 19:09:00 -07009942 jobject shared_libraries,
9943 jobject shared_libraries_after) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009944 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9945 WellKnownClasses::dalvik_system_PathClassLoader) ||
9946 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009947 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9948 self->GetJniEnv()->IsSameObject(loader_class,
9949 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009950
9951 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9952 // We could move the jobject to the callers, but all call-sites do this...
9953 ScopedObjectAccessUnchecked soa(self);
9954
9955 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Brad Stenning9c924e82021-10-11 19:09:00 -07009956 StackHandleScope<5> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009957
9958 Handle<mirror::Class> h_loader_class =
9959 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009960 Handle<mirror::ClassLoader> h_parent =
9961 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9962 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9963 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Brad Stenning9c924e82021-10-11 19:09:00 -07009964 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries_after =
9965 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries_after));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009966
9967 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9968 self,
9969 dex_files,
9970 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009971 h_parent,
Brad Stenning9c924e82021-10-11 19:09:00 -07009972 h_shared_libraries,
9973 h_shared_libraries_after);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009974
9975 // Make it a global ref and return.
9976 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009977 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009978 return soa.Env()->NewGlobalRef(local_ref.get());
9979}
9980
Calin Juravle7865ac72017-06-28 11:03:12 -07009981jobject ClassLinker::CreatePathClassLoader(Thread* self,
9982 const std::vector<const DexFile*>& dex_files) {
9983 return CreateWellKnownClassLoader(self,
9984 dex_files,
9985 WellKnownClasses::dalvik_system_PathClassLoader,
9986 nullptr);
9987}
9988
Andreas Gampe8ac75952015-06-02 21:01:45 -07009989void ClassLinker::DropFindArrayClassCache() {
9990 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9991 find_array_class_cache_next_victim_ = 0;
9992}
9993
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009994void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009995 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009996 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009997 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009998 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9999 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010000 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +010010001 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010002 }
10003 }
10004}
10005
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010006void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10007 for (const ClassLoaderData& data : class_loaders_) {
10008 LinearAlloc* alloc = data.allocator;
10009 if (alloc != nullptr && !visitor->Visit(alloc)) {
10010 break;
10011 }
10012 }
10013}
10014
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010015void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10016 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010017 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010018 Thread* const self = Thread::Current();
10019 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010020 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010021 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010022 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010023 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10024 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010025 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010026 }
10027}
10028
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010029void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010030 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010031 std::vector<ClassLoaderData> to_delete;
10032 // Do the delete outside the lock to avoid lock violation in jit code cache.
10033 {
10034 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10035 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10036 const ClassLoaderData& data = *it;
10037 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010038 ObjPtr<mirror::ClassLoader> class_loader =
10039 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010040 if (class_loader != nullptr) {
10041 ++it;
10042 } else {
10043 VLOG(class_linker) << "Freeing class loader";
10044 to_delete.push_back(data);
10045 it = class_loaders_.erase(it);
10046 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010047 }
10048 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010049 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010050 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010051 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010052 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010053}
10054
Mathieu Chartier65975772016-08-05 10:46:36 -070010055class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10056 public:
10057 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10058 : method_(method),
10059 pointer_size_(pointer_size) {}
10060
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010061 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010062 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10063 holder_ = klass;
10064 }
10065 // Return false to stop searching if holder_ is not null.
10066 return holder_ == nullptr;
10067 }
10068
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010069 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010070 const ArtMethod* const method_;
10071 const PointerSize pointer_size_;
10072};
10073
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010074ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010075 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10076 CHECK(method->IsCopied());
10077 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10078 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010079 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010080}
10081
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010082ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
10083 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010084 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +010010085 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010086 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010087}
10088
Calin Juravle33787682019-07-26 14:27:18 -070010089bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10090 REQUIRES_SHARED(Locks::mutator_lock_) {
10091 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10092 LOG(FATAL) << "UNREACHABLE";
10093 UNREACHABLE();
10094}
10095
10096bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10097 REQUIRES_SHARED(Locks::mutator_lock_) {
10098 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10099 LOG(FATAL) << "UNREACHABLE";
10100 UNREACHABLE();
10101}
10102
10103bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10104 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10105 LOG(FATAL) << "UNREACHABLE";
10106 UNREACHABLE();
10107}
10108
Calin Juravle2c2724c2021-01-14 19:54:23 -080010109void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10110 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10111 LOG(FATAL) << "UNREACHABLE";
10112 UNREACHABLE();
10113}
10114
Roland Levillain0e840272018-08-23 19:55:30 +010010115// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010116template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010117 Thread* self,
10118 ObjPtr<mirror::Class> java_lang_Class,
10119 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010120template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010121 Thread* self,
10122 ObjPtr<mirror::Class> java_lang_Class,
10123 uint32_t class_size);
10124
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010125} // namespace art