blob: 5e6ae1ab3cc34b45d5c42870e1154ea76cff4a8d [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_) {
1283 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1284 }
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
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001908 LinearAlloc* linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader.Get());
1909 DCHECK(linear_alloc != nullptr);
1910 DCHECK_EQ(linear_alloc == Runtime::Current()->GetLinearAlloc(), !app_image);
David Srbecky86d6cd52020-12-02 18:13:10 +00001911 {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001912 // Native fields are all null. Initialize them and allocate native memory.
David Srbecky86d6cd52020-12-02 18:13:10 +00001913 WriterMutexLock mu(self, *Locks::dex_lock_);
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001914 dex_cache->InitializeNativeFields(dex_file.get(), linear_alloc);
David Srbecky86d6cd52020-12-02 18:13:10 +00001915 }
1916 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001917 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001918 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001919 }
1920 out_dex_files->push_back(std::move(dex_file));
1921 }
1922
1923 if (app_image) {
1924 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001925 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001926 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1927 *error_msg = "Unexpected BootClassLoader in app image";
1928 return false;
1929 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001930 }
1931
Orion Hodson5880c772020-07-28 20:12:08 +01001932 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001933 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001934 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001935 }
1936 }
1937
1938 // Set entry point to interpreter if in InterpretOnly mode.
1939 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001940 // Set image methods' entry point to interpreter.
1941 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1942 if (!method.IsRuntimeMethod()) {
1943 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001944 if (!method.IsNative() && !method.IsResolutionMethod()) {
1945 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1946 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001947 }
1948 }
1949 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001950 }
1951
Nicolas Geoffray47171752020-08-31 15:03:20 +01001952 if (!runtime->IsAotCompiler()) {
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001953 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001954 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001955 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01001956 // In the image, the `data` pointer field of the ArtMethod contains the code
1957 // item offset. Change this to the actual pointer to the code item.
1958 if (method.HasCodeItem()) {
1959 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
1960 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01001961 method.SetCodeItem(code_item);
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
Orion Hodsonb9b7d912021-02-24 09:24:47 +00002370ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2371 const DexFile& dex_file,
2372 LinearAlloc* linear_alloc) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002373 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002374 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002375 WriterMutexLock mu(self, *Locks::dex_lock_);
Orion Hodsonb9b7d912021-02-24 09:24:47 +00002376 dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002377 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002378 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002379}
2380
Vladimir Marko70e2a762019-07-12 16:49:00 +01002381template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002382ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2383 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002384 uint32_t class_size,
2385 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002386 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002387 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002388 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002389 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2390 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002391 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002392 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002393 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002394 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002395 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002396}
2397
Vladimir Marko70e2a762019-07-12 16:49:00 +01002398template <bool kMovable>
2399ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2400 ObjPtr<mirror::Class> java_lang_Class,
2401 uint32_t class_size) {
2402 mirror::Class::InitializeClassVisitor visitor(class_size);
2403 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2404}
2405
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002406ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002407 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002408}
2409
Vladimir Marko70e2a762019-07-12 16:49:00 +01002410void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2411 ClassRoot primitive_root,
2412 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002413 // We make this class non-movable for the unlikely case where it were to be
2414 // moved by a sticky-bit (minor) collection when using the Generational
2415 // Concurrent Copying (CC) collector, potentially creating a stale reference
2416 // in the `klass_` field of one of its instances allocated in the Large-Object
2417 // Space (LOS) -- see the comment about the dirty card scanning logic in
2418 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002419 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2420 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2421 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2422 DCHECK(component_type->IsPrimitive());
2423 array_class->SetComponentType(component_type);
2424 SetClassRoot(array_root, array_class);
2425}
2426
2427void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2428 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2429 array_class->SetSuperClass(java_lang_Object);
2430 array_class->SetVTable(java_lang_Object->GetVTable());
2431 array_class->SetPrimitiveType(Primitive::kPrimNot);
2432 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2433 array_class->SetClassFlags(component_type->IsPrimitive()
2434 ? mirror::kClassFlagNoReferenceFields
2435 : mirror::kClassFlagObjectArray);
2436 array_class->SetClassLoader(component_type->GetClassLoader());
2437 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2438 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2439 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2440 array_class->SetImt(object_imt, image_pointer_size_);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002441 DCHECK_EQ(array_class->NumMethods(), 0u);
2442
2443 // don't need to set new_class->SetObjectSize(..)
2444 // because Object::SizeOf delegates to Array::SizeOf
2445
2446 // All arrays have java/lang/Cloneable and java/io/Serializable as
2447 // interfaces. We need to set that up here, so that stuff like
2448 // "instanceof" works right.
2449
2450 // Use the single, global copies of "interfaces" and "iftable"
2451 // (remember not to free them for arrays).
2452 {
2453 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2454 CHECK(array_iftable != nullptr);
2455 array_class->SetIfTable(array_iftable);
2456 }
2457
2458 // Inherit access flags from the component type.
2459 int access_flags = component_type->GetAccessFlags();
2460 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2461 access_flags &= kAccJavaFlagsMask;
2462 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2463 // and remove "interface".
2464 access_flags |= kAccAbstract | kAccFinal;
2465 access_flags &= ~kAccInterface;
Vladimir Marko70e2a762019-07-12 16:49:00 +01002466
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002467 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002468
Vladimir Markobf121912019-06-04 13:49:05 +01002469 // Array classes are fully initialized either during single threaded startup,
2470 // or from a pre-fence visitor, so visibly initialized.
2471 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002472}
2473
2474void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2475 // Do not hold lock on the array class object, the initialization of
2476 // core array classes is done while the process is still single threaded.
2477 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2478 FinishArrayClassSetup(array_class);
2479
2480 std::string temp;
2481 const char* descriptor = array_class->GetDescriptor(&temp);
2482 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2483 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2484 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002485}
2486
Vladimir Markobcf17522018-06-01 13:14:32 +01002487ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002488 Thread* self,
2489 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002490 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002491 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002492}
2493
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002494ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2495 const char* descriptor,
2496 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002497 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002498 if (kIsDebugBuild) {
2499 StackHandleScope<1> hs(self);
2500 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2501 Thread::PoisonObjectPointersIfDebug();
2502 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002503
2504 // For temporary classes we must wait for them to be retired.
2505 if (init_done_ && klass->IsTemp()) {
2506 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002507 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002508 ThrowEarlierClassFailure(klass);
2509 return nullptr;
2510 }
2511 StackHandleScope<1> hs(self);
2512 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2513 ObjectLock<mirror::Class> lock(self, h_class);
2514 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002515 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002516 lock.WaitIgnoringInterrupts();
2517 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002518 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002519 ThrowEarlierClassFailure(h_class.Get());
2520 return nullptr;
2521 }
2522 CHECK(h_class->IsRetired());
2523 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002524 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002525 }
2526
Brian Carlstromaded5f72011-10-07 17:15:04 -07002527 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002528 size_t index = 0;
2529 // Maximum number of yield iterations until we start sleeping.
2530 static const size_t kNumYieldIterations = 1000;
2531 // How long each sleep is in us.
2532 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002533 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002534 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002535 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002536 {
2537 ObjectTryLock<mirror::Class> lock(self, h_class);
2538 // Can not use a monitor wait here since it may block when returning and deadlock if another
2539 // thread has locked klass.
2540 if (lock.Acquired()) {
2541 // Check for circular dependencies between classes, the lock is required for SetStatus.
2542 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2543 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002544 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002545 return nullptr;
2546 }
2547 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002548 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002549 {
2550 // Handle wrapper deals with klass moving.
2551 ScopedThreadSuspension sts(self, kSuspended);
2552 if (index < kNumYieldIterations) {
2553 sched_yield();
2554 } else {
2555 usleep(kSleepDurationUS);
2556 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002557 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002558 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002559 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002560
Vladimir Marko72ab6842017-01-20 19:32:50 +00002561 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002562 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002563 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002564 }
2565 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002566 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002567 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002568 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002569}
2570
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002571using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002572
2573// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002574ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002575 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002576 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002577 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002578 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002579 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002580 return ClassPathEntry(dex_file, dex_class_def);
2581 }
2582 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002583 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002584}
2585
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002586bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2587 Thread* self,
2588 const char* descriptor,
2589 size_t hash,
2590 Handle<mirror::ClassLoader> class_loader,
2591 /*out*/ ObjPtr<mirror::Class>* result) {
2592 ArtField* field =
2593 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2594 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2595 if (raw_shared_libraries == nullptr) {
2596 return true;
2597 }
2598
2599 StackHandleScope<2> hs(self);
2600 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2601 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2602 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002603 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2604 temp_loader.Assign(loader);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002605 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2606 return false; // One of the shared libraries is not supported.
2607 }
2608 if (*result != nullptr) {
2609 return true; // Found the class up the chain.
2610 }
2611 }
2612 return true;
2613}
2614
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002615bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2616 Thread* self,
2617 const char* descriptor,
2618 size_t hash,
2619 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002620 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002621 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002622 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002623 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002624 return true;
2625 }
2626
David Brazdil05909d82018-12-06 16:25:16 +00002627 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002628 // For regular path or dex class loader the search order is:
2629 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002630 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002631 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002632
Calin Juravlecdd49122017-07-05 20:09:53 -07002633 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2634 StackHandleScope<1> hs(self);
2635 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2636 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2637 return false; // One of the parents is not supported.
2638 }
2639 if (*result != nullptr) {
2640 return true; // Found the class up the chain.
2641 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002642
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002643 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2644 return false; // One of the shared library loader is not supported.
2645 }
2646 if (*result != nullptr) {
2647 return true; // Found the class in a shared library.
2648 }
2649
Calin Juravlecdd49122017-07-05 20:09:53 -07002650 // Search the current class loader classpath.
2651 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002652 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002653 }
2654
Calin Juravlecdd49122017-07-05 20:09:53 -07002655 if (IsDelegateLastClassLoader(soa, class_loader)) {
2656 // For delegate last, the search order is:
2657 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002658 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002659 // - class loader dex files
2660 // - parent
2661 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2662 if (*result != nullptr) {
2663 return true; // The class is part of the boot class path.
2664 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002665 if (self->IsExceptionPending()) {
2666 // Pending exception means there was an error other than ClassNotFound that must be returned
2667 // to the caller.
2668 return false;
2669 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002670
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002671 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2672 return false; // One of the shared library loader is not supported.
2673 }
2674 if (*result != nullptr) {
2675 return true; // Found the class in a shared library.
2676 }
2677
Calin Juravlecdd49122017-07-05 20:09:53 -07002678 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2679 if (*result != nullptr) {
2680 return true; // Found the class in the current class loader
2681 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002682 if (self->IsExceptionPending()) {
2683 // Pending exception means there was an error other than ClassNotFound that must be returned
2684 // to the caller.
2685 return false;
2686 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002687
2688 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2689 StackHandleScope<1> hs(self);
2690 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2691 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2692 }
2693
2694 // Unsupported class loader.
2695 *result = nullptr;
2696 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002697}
2698
Andreas Gampe501c3b02019-04-17 21:54:27 +00002699namespace {
2700
2701// Matches exceptions caught in DexFile.defineClass.
2702ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2703 ClassLinker* class_linker)
2704 REQUIRES_SHARED(Locks::mutator_lock_) {
2705 return
2706 // ClassNotFoundException.
2707 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2708 class_linker))
2709 ||
2710 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2711 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2712}
2713
2714// Clear exceptions caught in DexFile.defineClass.
2715ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2716 REQUIRES_SHARED(Locks::mutator_lock_) {
2717 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2718 self->ClearException();
2719 }
2720}
2721
2722} // namespace
2723
Calin Juravle415dc3d2017-06-28 11:03:12 -07002724// Finds the class in the boot class loader.
2725// If the class is found the method returns the resolved class. Otherwise it returns null.
2726ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2727 const char* descriptor,
2728 size_t hash) {
2729 ObjPtr<mirror::Class> result = nullptr;
2730 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2731 if (pair.second != nullptr) {
2732 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2733 if (klass != nullptr) {
2734 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002735 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002736 result = DefineClass(self,
2737 descriptor,
2738 hash,
2739 ScopedNullHandle<mirror::ClassLoader>(),
2740 *pair.first,
2741 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002742 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002743 if (result == nullptr) {
2744 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002745 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002746 }
2747 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002748 return result;
2749}
Andreas Gampef865ea92015-04-13 22:14:19 -07002750
Calin Juravle415dc3d2017-06-28 11:03:12 -07002751ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2752 ScopedObjectAccessAlreadyRunnable& soa,
2753 const char* descriptor,
2754 size_t hash,
2755 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002756 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2757 IsInMemoryDexClassLoader(soa, class_loader) ||
2758 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002759 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002760
Vladimir Marko68c07582021-04-19 16:01:15 +00002761 const DexFile* dex_file = nullptr;
2762 const dex::ClassDef* class_def = nullptr;
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002763 ObjPtr<mirror::Class> ret;
Vladimir Marko68c07582021-04-19 16:01:15 +00002764 auto find_class_def = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2765 const dex::ClassDef* cp_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2766 if (cp_class_def != nullptr) {
2767 dex_file = cp_dex_file;
2768 class_def = cp_class_def;
2769 return false; // Found a class definition, stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002770 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002771 return true; // Continue with the next DexFile.
2772 };
Vladimir Marko68c07582021-04-19 16:01:15 +00002773 VisitClassLoaderDexFiles(soa, class_loader, find_class_def);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002774
Vladimir Marko68c07582021-04-19 16:01:15 +00002775 ObjPtr<mirror::Class> klass = nullptr;
2776 if (class_def != nullptr) {
2777 klass = DefineClass(soa.Self(), descriptor, hash, class_loader, *dex_file, *class_def);
2778 if (UNLIKELY(klass == nullptr)) {
2779 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2780 FilterDexFileCaughtExceptions(soa.Self(), this);
2781 } else {
2782 DCHECK(!soa.Self()->IsExceptionPending());
2783 }
2784 }
2785 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002786}
2787
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002788ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2789 const char* descriptor,
2790 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002791 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002792 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002793 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002794 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002795 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002796 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2797 // for primitive classes that aren't backed by dex files.
2798 return FindPrimitiveClass(descriptor[0]);
2799 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002800 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002801 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002802 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002803 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002804 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002805 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002806 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002807 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002808 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002809 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002810 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002811 return DefineClass(self,
2812 descriptor,
2813 hash,
2814 ScopedNullHandle<mirror::ClassLoader>(),
2815 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002816 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002817 } else {
2818 // The boot class loader is searched ahead of the application class loader, failures are
2819 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2820 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002821 ObjPtr<mirror::Throwable> pre_allocated =
2822 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002823 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002824 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002825 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002826 }
2827 ObjPtr<mirror::Class> result_ptr;
2828 bool descriptor_equals;
2829 if (descriptor[0] == '[') {
2830 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2831 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2832 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2833 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002834 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002835 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002836 bool known_hierarchy =
2837 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2838 if (result_ptr != nullptr) {
2839 // The chain was understood and we found the class. We still need to add the class to
2840 // the class table to protect from racy programs that can try and redefine the path list
2841 // which would change the Class<?> returned for subsequent evaluation of const-class.
2842 DCHECK(known_hierarchy);
2843 DCHECK(result_ptr->DescriptorEquals(descriptor));
2844 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002845 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002846 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002847 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2848 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002849 //
2850 // If the chain was understood but we did not find the class, let the Java-side
2851 // rediscover all this and throw the exception with the right stack trace. Note that
2852 // the Java-side could still succeed for racy programs if another thread is actively
2853 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002854
Alex Light185a4612018-10-04 15:54:25 -07002855 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002856 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002857 // Oops, we can't call into java so we can't run actual class-loader code.
2858 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002859 ObjPtr<mirror::Throwable> pre_allocated =
2860 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2861 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002862 return nullptr;
2863 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002864
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002865 // Inlined DescriptorToDot(descriptor) with extra validation.
2866 //
2867 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2868 // the DescriptorEquals() check below and give a confusing error message. For example,
2869 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2870 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2871 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2872 size_t descriptor_length = strlen(descriptor);
2873 if (UNLIKELY(descriptor[0] != 'L') ||
2874 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2875 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2876 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2877 return nullptr;
2878 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002879
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002880 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2881 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002882 if (known_hierarchy &&
2883 fast_class_not_found_exceptions_ &&
2884 !Runtime::Current()->IsJavaDebuggable()) {
2885 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2886 // debuggable, optimize this path by throwing directly here without going back to Java
2887 // language. This reduces how many ClassNotFoundExceptions happen.
2888 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2889 "%s",
2890 class_name_string.c_str());
2891 } else {
2892 ScopedLocalRef<jobject> class_loader_object(
2893 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2894 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2895 {
2896 ScopedThreadStateChange tsc(self, kNative);
2897 ScopedLocalRef<jobject> class_name_object(
2898 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2899 if (class_name_object.get() == nullptr) {
2900 DCHECK(self->IsExceptionPending()); // OOME.
2901 return nullptr;
2902 }
2903 CHECK(class_loader_object.get() != nullptr);
2904 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2905 WellKnownClasses::java_lang_ClassLoader_loadClass,
2906 class_name_object.get()));
2907 }
2908 if (result.get() == nullptr && !self->IsExceptionPending()) {
2909 // broken loader - throw NPE to be compatible with Dalvik
2910 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2911 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002912 return nullptr;
2913 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002914 result_ptr = soa.Decode<mirror::Class>(result.get());
2915 // Check the name of the returned class.
2916 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002917 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002918 } else {
2919 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002920 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002921 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002922
2923 if (self->IsExceptionPending()) {
2924 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2925 // However, to comply with the RI behavior, first check if another thread succeeded.
2926 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2927 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2928 self->ClearException();
2929 return EnsureResolved(self, descriptor, result_ptr);
2930 }
2931 return nullptr;
2932 }
2933
2934 // Try to insert the class to the class table, checking for mismatch.
2935 ObjPtr<mirror::Class> old;
2936 {
2937 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2938 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2939 old = class_table->Lookup(descriptor, hash);
2940 if (old == nullptr) {
2941 old = result_ptr; // For the comparison below, after releasing the lock.
2942 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002943 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002944 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002945 } // else throw below, after releasing the lock.
2946 }
2947 }
2948 if (UNLIKELY(old != result_ptr)) {
2949 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2950 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01002951 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002952 const char* loader_class_name =
2953 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2954 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2955 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2956 << DescriptorToDot(descriptor) << "\").";
2957 return EnsureResolved(self, descriptor, old);
2958 }
2959 if (UNLIKELY(!descriptor_equals)) {
2960 std::string result_storage;
2961 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2962 std::string loader_storage;
2963 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2964 ThrowNoClassDefFoundError(
2965 "Initiating class loader of type %s returned class %s instead of %s.",
2966 DescriptorToDot(loader_class_name).c_str(),
2967 DescriptorToDot(result_name).c_str(),
2968 DescriptorToDot(descriptor).c_str());
2969 return nullptr;
2970 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002971 // Success.
2972 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002973}
2974
Alex Light270db1c2019-12-03 12:20:01 +00002975// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
2976// define-class and how many recursive DefineClasses we are at in order to allow for doing things
2977// like pausing class definition.
2978struct ScopedDefiningClass {
2979 public:
2980 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
2981 : self_(self), returned_(false) {
2982 Locks::mutator_lock_->AssertSharedHeld(self_);
2983 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
2984 self_->IncrDefineClassCount();
2985 }
2986 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
2987 Locks::mutator_lock_->AssertSharedHeld(self_);
2988 CHECK(returned_);
2989 }
2990
2991 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
2992 REQUIRES_SHARED(Locks::mutator_lock_) {
2993 CHECK(!returned_);
2994 self_->DecrDefineClassCount();
2995 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
2996 Thread::PoisonObjectPointersIfDebug();
2997 returned_ = true;
2998 return h_klass.Get();
2999 }
3000
3001 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3002 REQUIRES_SHARED(Locks::mutator_lock_) {
3003 StackHandleScope<1> hs(self_);
3004 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3005 return Finish(h_klass);
3006 }
3007
3008 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3009 REQUIRES_SHARED(Locks::mutator_lock_) {
3010 ScopedNullHandle<mirror::Class> snh;
3011 return Finish(snh);
3012 }
3013
3014 private:
3015 Thread* self_;
3016 bool returned_;
3017};
3018
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003019ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3020 const char* descriptor,
3021 size_t hash,
3022 Handle<mirror::ClassLoader> class_loader,
3023 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003024 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003025 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003026 StackHandleScope<3> hs(self);
Eric Holk74584e62021-02-18 14:39:17 -08003027 metrics::AutoTimer timer{GetMetrics()->ClassLoadingTotalTime()};
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003028 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003029
Brian Carlstromaded5f72011-10-07 17:15:04 -07003030 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003031 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003032 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003033 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003034 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003035 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003036 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003037 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003038 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003039 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003040 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003041 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003042 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003043 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003044 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003045 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003046 }
3047
Vladimir Markob9c29f62019-03-20 14:22:51 +00003048 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3049 // some runtime modules. Prevent definition of classes in app class loader that could clash
3050 // with these modules as these classes could be resolved differently during execution.
3051 if (class_loader != nullptr &&
3052 Runtime::Current()->IsAotCompiler() &&
Vladimir Markod1f73512020-04-02 10:50:35 +01003053 IsUpdatableBootClassPathDescriptor(descriptor)) {
Vladimir Markob9c29f62019-03-20 14:22:51 +00003054 ObjPtr<mirror::Throwable> pre_allocated =
3055 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3056 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003057 return sdc.Finish(nullptr);
Vladimir Markob9c29f62019-03-20 14:22:51 +00003058 }
3059
Calin Juravle33787682019-07-26 14:27:18 -07003060 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3061 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3062 // public class path then we prevent the definition of the class.
3063 //
3064 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3065 // classpath is not checked.
3066 if (class_loader == nullptr &&
3067 Runtime::Current()->IsAotCompiler() &&
3068 DenyAccessBasedOnPublicSdk(descriptor)) {
3069 ObjPtr<mirror::Throwable> pre_allocated =
3070 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3071 self->SetException(pre_allocated);
3072 return sdc.Finish(nullptr);
3073 }
3074
Alex Lighte9f61032018-09-24 16:04:51 -07003075 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3076 // code to be executed. We put it up here so we can avoid all the allocations associated with
3077 // creating the class. This can happen with (eg) jit threads.
3078 if (!self->CanLoadClasses()) {
3079 // Make sure we don't try to load anything, potentially causing an infinite loop.
3080 ObjPtr<mirror::Throwable> pre_allocated =
3081 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3082 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003083 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003084 }
3085
Andreas Gampefa4333d2017-02-14 11:10:34 -08003086 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003087 // Allocate a class with the status of not ready.
3088 // Interface object should get the right size here. Regular class will
3089 // figure out the right size later and be replaced with one of the right
3090 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003091 if (CanAllocClass()) {
3092 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3093 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003094 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003095 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003096 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003097 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003098 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003099 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003100 }
Alex Lightb0f11922017-01-23 14:25:17 -08003101 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3102 // nothing.
3103 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003104 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003105 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3106 // will only be called once.
3107 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3108 klass,
3109 class_loader,
3110 dex_file,
3111 dex_class_def,
3112 &new_dex_file,
3113 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003114 // Check to see if an exception happened during runtime callbacks. Return if so.
3115 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003116 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003117 }
Alex Lightb0f11922017-01-23 14:25:17 -08003118 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003119 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003120 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003121 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003122 }
3123 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003124 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003125
Jeff Hao848f70a2014-01-15 13:49:50 -08003126 // Mark the string class by setting its access flag.
3127 if (UNLIKELY(!init_done_)) {
3128 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3129 klass->SetStringClass();
3130 }
3131 }
3132
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003133 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003134 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003135 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003136 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003137
Mathieu Chartier590fee92013-09-13 13:46:47 -07003138 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003139 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003140 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003141 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3142 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003143 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003144 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003145
Mathieu Chartierc7853442015-03-27 14:35:38 -07003146 // Load the fields and other things after we are inserted in the table. This is so that we don't
3147 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3148 // other reason is that the field roots are only visited from the class table. So we need to be
3149 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003150 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003151 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003152 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003153 // An exception occured during load, set status to erroneous while holding klass' lock in case
3154 // notification is necessary.
3155 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003156 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003157 }
Alex Light270db1c2019-12-03 12:20:01 +00003158 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003159 }
3160
Brian Carlstromaded5f72011-10-07 17:15:04 -07003161 // Finish loading (if necessary) by finding parents
3162 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003163 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003164 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003165 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003166 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003167 }
Alex Light270db1c2019-12-03 12:20:01 +00003168 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003169 }
3170 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003171
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003172 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003173 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003174 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003175
Brian Carlstromaded5f72011-10-07 17:15:04 -07003176 // Link the class (if necessary)
3177 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003178 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003179 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003180
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003181 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003182 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003183 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003184 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003185 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003186 }
Alex Light270db1c2019-12-03 12:20:01 +00003187 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003188 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003189 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003190 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003191 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003192
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003193 // Instrumentation may have updated entrypoints for all methods of all
3194 // classes. However it could not update methods of this class while we
3195 // were loading it. Now the class is resolved, we can update entrypoints
3196 // as required by instrumentation.
3197 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3198 // We must be in the kRunnable state to prevent instrumentation from
3199 // suspending all threads to update entrypoints while we are doing it
3200 // for this class.
3201 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003202 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003203 }
3204
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003205 /*
3206 * We send CLASS_PREPARE events to the debugger from here. The
3207 * definition of "preparation" is creating the static fields for a
3208 * class and initializing them to the standard default values, but not
3209 * executing any code (that comes later, during "initialization").
3210 *
3211 * We did the static preparation in LinkClass.
3212 *
3213 * The class has been prepared and resolved but possibly not yet verified
3214 * at this point.
3215 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003216 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003217
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003218 // Notify native debugger of the new class and its layout.
3219 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3220
Alex Light270db1c2019-12-03 12:20:01 +00003221 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003222}
3223
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003224uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003225 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003226 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003227 size_t num_8 = 0;
3228 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003229 size_t num_32 = 0;
3230 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003231 ClassAccessor accessor(dex_file, dex_class_def);
3232 // We allow duplicate definitions of the same field in a class_data_item
3233 // but ignore the repeated indexes here, b/21868015.
3234 uint32_t last_field_idx = dex::kDexNoIndex;
3235 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3236 uint32_t field_idx = field.GetIndex();
3237 // Ordering enforced by DexFileVerifier.
3238 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3239 if (UNLIKELY(field_idx == last_field_idx)) {
3240 continue;
3241 }
3242 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003243 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003244 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3245 char c = descriptor[0];
3246 switch (c) {
3247 case 'L':
3248 case '[':
3249 num_ref++;
3250 break;
3251 case 'J':
3252 case 'D':
3253 num_64++;
3254 break;
3255 case 'I':
3256 case 'F':
3257 num_32++;
3258 break;
3259 case 'S':
3260 case 'C':
3261 num_16++;
3262 break;
3263 case 'B':
3264 case 'Z':
3265 num_8++;
3266 break;
3267 default:
3268 LOG(FATAL) << "Unknown descriptor: " << c;
3269 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003270 }
3271 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003272 return mirror::Class::ComputeClassSize(false,
3273 0,
3274 num_8,
3275 num_16,
3276 num_32,
3277 num_64,
3278 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003279 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003280}
3281
Alex Lightfc49fec2018-01-16 22:28:36 +00003282// Special case to get oat code without overwriting a trampoline.
3283const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003284 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003285 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003286 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003287 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003288 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003289 if (code != nullptr) {
3290 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003291 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003292
3293 jit::Jit* jit = Runtime::Current()->GetJit();
3294 if (jit != nullptr) {
3295 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3296 if (code != nullptr) {
3297 return code;
3298 }
3299 }
3300
Alex Lightfc49fec2018-01-16 22:28:36 +00003301 if (method->IsNative()) {
3302 // No code and native? Use generic trampoline.
3303 return GetQuickGenericJniStub();
3304 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003305
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003306 if (interpreter::CanRuntimeUseNterp() && CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003307 return interpreter::GetNterpEntryPoint();
3308 }
3309
Alex Lightfc49fec2018-01-16 22:28:36 +00003310 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003311}
3312
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003313bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003314 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003315 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3316 return false;
3317 }
3318
Elliott Hughes956af0f2014-12-11 14:34:28 -08003319 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003320 return true;
3321 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003322
3323 Runtime* runtime = Runtime::Current();
3324 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3325 if (instr->InterpretOnly()) {
3326 return true;
3327 }
3328
3329 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3330 // Doing this check avoids doing compiled/interpreter transitions.
3331 return true;
3332 }
3333
Alex Lightfc588092020-01-23 15:39:08 -08003334 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003335 // Force the use of interpreter when it is required by the debugger.
3336 return true;
3337 }
3338
Alex Light8f34aba2017-10-09 13:46:32 -07003339 if (Thread::Current()->IsAsyncExceptionPending()) {
3340 // Force use of interpreter to handle async-exceptions
3341 return true;
3342 }
3343
Alex Light2d441b12018-06-08 15:33:21 -07003344 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3345 const void* instr_target = instr->GetCodeForInvoke(method);
3346 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3347 return ShouldUseInterpreterEntrypoint(method, instr_target);
3348 }
3349
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003350 if (runtime->IsJavaDebuggable()) {
3351 // For simplicity, we ignore precompiled code and go to the interpreter
3352 // assuming we don't already have jitted code.
3353 // We could look at the oat file where `quick_code` is being defined,
3354 // and check whether it's been compiled debuggable, but we decided to
3355 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003356 jit::Jit* jit = Runtime::Current()->GetJit();
3357 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3358 }
3359
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003360 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003361 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003362 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003363 // since we want to JIT it (at first use) with extra stackmaps for native
3364 // debugging. We keep however all AOT code from the boot image,
3365 // since the JIT-at-first-use is blocking and would result in non-negligible
3366 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003367 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003368 }
3369
3370 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003371}
3372
Vladimir Marko86c87522020-05-11 16:55:55 +01003373void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003374 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003375 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003376 size_t num_direct_methods = klass->NumDirectMethods();
3377 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003378 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003379 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003380 if (UNLIKELY(klass->IsProxyClass())) {
3381 return;
3382 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003383 PointerSize pointer_size = image_pointer_size_;
3384 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3385 klass->GetDirectMethods(pointer_size).end(),
3386 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3387 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3388 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3389 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3390 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3391 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3392 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3393 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3394 lb->first->SetEntryPointFromJni(lb->second);
3395 lb = critical_native_code_with_clinit_check_.erase(lb);
3396 }
3397 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003398 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003399 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003400 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003401 return; // OAT file unavailable.
3402 }
Ian Rogers19846512012-02-24 11:42:47 -08003403 }
Alex Light64ad14d2014-08-19 14:23:13 -07003404
Mathieu Chartierf8322842014-05-16 10:59:25 -07003405 const DexFile& dex_file = klass->GetDexFile();
Ian Rogers97b52f82014-08-14 11:34:07 -07003406 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003407 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3408 klass->GetDexClassDefIndex(),
3409 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003410 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003411 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3412 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003413 if (!method->IsStatic()) {
3414 // Only update static methods.
3415 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003416 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003417 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003418
3419 // In order:
3420 // 1) Check if we have AOT Code.
3421 // 2) Check if we have JIT Code.
3422 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003423 if (has_oat_class) {
3424 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003425 quick_code = oat_method.GetQuickCode();
3426 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003427
Vladimir Markocce414f2019-10-07 08:51:33 +01003428 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003429 if (quick_code == nullptr && jit != nullptr) {
3430 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003431 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003432
3433 if (quick_code == nullptr &&
3434 interpreter::CanRuntimeUseNterp() &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003435 CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003436 quick_code = interpreter::GetNterpEntryPoint();
3437 }
3438
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003439 // Check whether the method is native, in which case it's generic JNI.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003440 if (quick_code == nullptr && method->IsNative()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003441 quick_code = GetQuickGenericJniStub();
3442 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003443 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003444 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3445 // If we have the trampoline or the bridge already, no need to update.
3446 // This saves in not dirtying boot image memory.
3447 continue;
3448 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003449 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003450 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003451 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003452 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003453 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003454 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003455}
3456
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003457// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3458// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003459inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3460 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003461 DCHECK(method != nullptr);
3462 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003463 method->SetEntryPointFromQuickCompiledCodePtrSize(
3464 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3465 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003466}
3467
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003468static void LinkCode(ClassLinker* class_linker,
3469 ArtMethod* method,
3470 const OatFile::OatClass* oat_class,
3471 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003472 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003473 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003474 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003475 // The following code only applies to a non-compiler runtime.
3476 return;
3477 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003478
Ian Rogers62d6c772013-02-27 08:32:07 -08003479 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003480 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003481
Alex Light9139e002015-10-09 15:59:48 -07003482 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003483 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003484 return;
3485 }
Ian Rogers19846512012-02-24 11:42:47 -08003486
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003487 const void* quick_code = nullptr;
3488 if (oat_class != nullptr) {
3489 // Every kind of method should at least get an invoke stub from the oat_method.
3490 // non-abstract methods also get their code pointers.
3491 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3492 quick_code = oat_method.GetQuickCode();
3493 }
3494
3495 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3496
3497 // Note: this mimics the logic in image_writer.cc that installs the resolution
3498 // stub only if we have compiled code and the method needs a class initialization
3499 // check.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003500 if (quick_code == nullptr) {
Nicolas Geoffray4ef36492021-06-16 17:26:51 +01003501 if (method->IsNative()) {
3502 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Nicolas Geoffray4ef36492021-06-16 17:26:51 +01003503 } else {
Nicolas Geoffray6cd7ab32021-07-07 09:35:50 +01003504 // Note we cannot use the nterp entrypoint because we do not know if the
3505 // method will need the slow interpreter for lock verification. This will
3506 // be updated in EnsureSkipAccessChecksMethods.
Nicolas Geoffray4ef36492021-06-16 17:26:51 +01003507 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
3508 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003509 } else if (enter_interpreter) {
3510 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003511 } else if (NeedsClinitCheckBeforeCall(method)) {
3512 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3513 // If we do have code but the method needs a class initialization check before calling
3514 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003515 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3516 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003517 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003518 } else {
3519 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003520 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003521
Ian Rogers62d6c772013-02-27 08:32:07 -08003522 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003523 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3524 // as the extra processing for @CriticalNative is not needed yet.
3525 method->SetEntryPointFromJni(
3526 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Andreas Gampe90546832014-03-12 18:07:19 -07003527
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003528 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003529 // We have a native method here without code. Then it should have the generic JNI
3530 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003531 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003532 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003533 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003534 }
3535}
3536
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003537void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003538 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003539 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003540 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003541 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003542 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003543 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003544 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003545 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003546
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003547 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003548 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003549 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003550 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003551 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003552 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003553 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003554
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003555 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003556 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003557}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003558
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003559LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3560 LinearAlloc* allocator,
3561 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003562 if (length == 0) {
3563 return nullptr;
3564 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003565 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3566 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3567 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003568 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003569 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003570 CHECK(ret != nullptr);
3571 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3572 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003573}
3574
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003575LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3576 LinearAlloc* allocator,
3577 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003578 if (length == 0) {
3579 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003580 }
Vladimir Marko14632852015-08-17 12:07:23 +01003581 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3582 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003583 const size_t storage_size =
3584 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003585 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003586 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003587 CHECK(ret != nullptr);
3588 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003589 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003590 }
3591 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003592}
3593
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003594LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003595 if (class_loader == nullptr) {
3596 return Runtime::Current()->GetLinearAlloc();
3597 }
3598 LinearAlloc* allocator = class_loader->GetAllocator();
3599 DCHECK(allocator != nullptr);
3600 return allocator;
3601}
3602
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003603LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003604 if (class_loader == nullptr) {
3605 return Runtime::Current()->GetLinearAlloc();
3606 }
3607 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3608 LinearAlloc* allocator = class_loader->GetAllocator();
3609 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003610 RegisterClassLoader(class_loader);
3611 allocator = class_loader->GetAllocator();
3612 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003613 }
3614 return allocator;
3615}
3616
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003617void ClassLinker::LoadClass(Thread* self,
3618 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003619 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003620 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003621 ClassAccessor accessor(dex_file,
3622 dex_class_def,
3623 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003624 if (!accessor.HasClassData()) {
3625 return;
3626 }
3627 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003628 {
3629 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3630 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003631 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003632 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003633 // We allow duplicate definitions of the same field in a class_data_item
3634 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003635 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003636 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3637 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003638 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003639 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3640 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003641 accessor.NumInstanceFields());
3642 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003643 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003644 uint32_t last_static_field_idx = 0u;
3645 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003646
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003647 // Methods
3648 bool has_oat_class = false;
3649 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3650 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3651 : OatFile::OatClass::Invalid();
3652 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3653 klass->SetMethodsPtr(
3654 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3655 accessor.NumDirectMethods(),
3656 accessor.NumVirtualMethods());
3657 size_t class_def_method_index = 0;
3658 uint32_t last_dex_method_index = dex::kDexNoIndex;
3659 size_t last_class_def_method_index = 0;
3660
3661 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3662 // methods needs to decode all of the fields.
3663 accessor.VisitFieldsAndMethods([&](
3664 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3665 uint32_t field_idx = field.GetIndex();
3666 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3667 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3668 LoadField(field, klass, &sfields->At(num_sfields));
3669 ++num_sfields;
3670 last_static_field_idx = field_idx;
3671 }
3672 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3673 uint32_t field_idx = field.GetIndex();
3674 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3675 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3676 LoadField(field, klass, &ifields->At(num_ifields));
3677 ++num_ifields;
3678 last_instance_field_idx = field_idx;
3679 }
3680 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3681 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3682 image_pointer_size_);
3683 LoadMethod(dex_file, method, klass, art_method);
3684 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3685 uint32_t it_method_index = method.GetIndex();
3686 if (last_dex_method_index == it_method_index) {
3687 // duplicate case
3688 art_method->SetMethodIndex(last_class_def_method_index);
3689 } else {
3690 art_method->SetMethodIndex(class_def_method_index);
3691 last_dex_method_index = it_method_index;
3692 last_class_def_method_index = class_def_method_index;
3693 }
3694 ++class_def_method_index;
3695 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3696 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3697 class_def_method_index - accessor.NumDirectMethods(),
3698 image_pointer_size_);
3699 LoadMethod(dex_file, method, klass, art_method);
3700 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3701 ++class_def_method_index;
3702 });
3703
3704 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003705 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003706 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3707 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3708 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003709 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3710 if (sfields != nullptr) {
3711 sfields->SetSize(num_sfields);
3712 }
3713 if (ifields != nullptr) {
3714 ifields->SetSize(num_ifields);
3715 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003716 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003717 // Set the field arrays.
3718 klass->SetSFieldsPtr(sfields);
3719 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003720 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003721 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003722 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003723 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003724 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003725 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003726}
3727
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003728void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003729 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003730 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003731 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003732 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003733 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003734
David Brazdil85865692018-10-30 17:26:20 +00003735 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3736 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003737}
3738
Mathieu Chartier268764d2016-09-13 12:09:38 -07003739void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003740 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003741 Handle<mirror::Class> klass,
3742 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003743 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003744 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003745 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003746
Mathieu Chartier268764d2016-09-13 12:09:38 -07003747 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003748 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003749 dst->SetDeclaringClass(klass.Get());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003750
David Brazdil85865692018-10-30 17:26:20 +00003751 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3752 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003753
Ian Rogersdfb325e2013-10-30 01:00:44 -07003754 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003755 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003756 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3757 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003758 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003759 klass->SetFinalizable();
3760 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003761 std::string temp;
3762 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003763 // The Enum class declares a "final" finalize() method to prevent subclasses from
3764 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3765 // subclasses, so we exclude it here.
3766 // We also want to avoid setting the flag on Object, where we know that finalize() is
3767 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003768 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3769 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003770 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003771 }
3772 }
3773 }
3774 } else if (method_name[0] == '<') {
3775 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003776 bool is_init = (strcmp("<init>", method_name) == 0);
3777 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003778 if (UNLIKELY(!is_init && !is_clinit)) {
3779 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3780 } else {
3781 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3782 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003783 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003784 access_flags |= kAccConstructor;
3785 }
3786 }
3787 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003788 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3789 // Check if the native method is annotated with @FastNative or @CriticalNative.
3790 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3791 dex_file, dst->GetClassDef(), dex_method_idx);
3792 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003793 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003794 // Must be done after SetAccessFlags since IsAbstract depends on it.
3795 if (klass->IsInterface() && dst->IsAbstract()) {
3796 dst->CalculateAndSetImtIndex();
3797 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01003798 if (dst->HasCodeItem()) {
3799 DCHECK_NE(method.GetCodeItemOffset(), 0u);
3800 if (Runtime::Current()->IsAotCompiler()) {
3801 dst->SetDataPtrSize(reinterpret_cast32<void*>(method.GetCodeItemOffset()), image_pointer_size_);
3802 } else {
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01003803 dst->SetCodeItem(dst->GetDexFile()->GetCodeItem(method.GetCodeItemOffset()));
Nicolas Geoffray47171752020-08-31 15:03:20 +01003804 }
3805 } else {
3806 dst->SetDataPtrSize(nullptr, image_pointer_size_);
3807 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3808 }
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003809
3810 // Set optimization flags related to the shorty.
3811 const char* shorty = dst->GetShorty();
3812 bool all_parameters_are_reference = true;
3813 bool all_parameters_are_reference_or_int = true;
3814 bool return_type_is_fp = (shorty[0] == 'F' || shorty[0] == 'D');
3815
3816 for (size_t i = 1, e = strlen(shorty); i < e; ++i) {
3817 if (shorty[i] != 'L') {
3818 all_parameters_are_reference = false;
3819 if (shorty[i] == 'F' || shorty[i] == 'D' || shorty[i] == 'J') {
3820 all_parameters_are_reference_or_int = false;
3821 break;
3822 }
3823 }
3824 }
3825
3826 if (!dst->IsNative() && all_parameters_are_reference) {
3827 dst->SetNterpEntryPointFastPathFlag();
3828 }
3829
3830 if (!return_type_is_fp && all_parameters_are_reference_or_int) {
3831 dst->SetNterpInvokeFastPathFlag();
3832 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003833}
3834
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003835void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00003836 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
3837 self,
3838 *dex_file,
3839 Runtime::Current()->GetLinearAlloc());
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003840 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003841 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003842}
3843
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003844void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003845 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003846 CHECK(dex_file != nullptr);
3847 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3848 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003849 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003850 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003851}
3852
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003853void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003854 ObjPtr<mirror::DexCache> dex_cache,
3855 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003856 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003857 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003858 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003859 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003860 // For app images, the dex cache location may be a suffix of the dex file location since the
3861 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003862 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3863 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003864 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3865 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003866 // The following paths checks don't work on preopt when using boot dex files, where the dex
3867 // cache location is the one on device, and the dex_file's location is the one on host.
3868 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3869 CHECK_GE(dex_file_location.length(), dex_cache_length)
3870 << dex_cache_location << " " << dex_file.GetLocation();
3871 const std::string dex_file_suffix = dex_file_location.substr(
3872 dex_file_location.length() - dex_cache_length,
3873 dex_cache_length);
3874 // Example dex_cache location is SettingsProvider.apk and
3875 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3876 CHECK_EQ(dex_cache_location, dex_file_suffix);
3877 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003878 const OatFile* oat_file =
3879 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003880 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3881 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3882 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3883 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003884 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003885 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3886 DexCacheData data = *it;
3887 if (self->IsJWeakCleared(data.weak_root)) {
3888 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003889 it = dex_caches_.erase(it);
3890 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003891 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003892 it->dex_file->GetOatDexFile() != nullptr &&
3893 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003894 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003895 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003896 ++it;
3897 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003898 }
Vladimir Markob066d432018-01-03 13:14:37 +00003899 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003900 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003901 }
David Brazdila5c3a802019-03-08 14:59:41 +00003902 // Let hiddenapi assign a domain to the newly registered dex file.
3903 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3904
Vladimir Markocd556b02017-02-03 11:47:34 +00003905 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003906 DexCacheData data;
3907 data.weak_root = dex_cache_jweak;
3908 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003909 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003910 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003911 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003912 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3913 // path dex caches without an image.
3914 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003915 // Make sure that the dex cache holds the classloader live.
3916 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003917 if (class_loader != nullptr) {
3918 // Since we added a strong root to the class table, do the write barrier as required for
3919 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003920 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003921 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003922 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003923}
3924
Alex Light725da8f2020-02-19 14:46:33 -08003925ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3926 return data != nullptr
3927 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003928 : nullptr;
3929}
3930
Alex Light725da8f2020-02-19 14:46:33 -08003931bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003932 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003933 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003934 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003935 CHECK(data != nullptr);
3936 DCHECK_EQ(dex_cache->GetDexFile(), data->dex_file);
3937 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003938}
3939
Alex Light07f06212017-06-01 14:01:43 -07003940void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3941 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003942 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003943 Thread* self = Thread::Current();
3944 StackHandleScope<2> hs(self);
3945 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3946 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3947 const DexFile* dex_file = dex_cache->GetDexFile();
3948 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3949 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003950 ReaderMutexLock mu(self, *Locks::dex_lock_);
3951 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3952 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003953 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3954 << "been registered on dex file " << dex_file->GetLocation();
3955 }
3956 ClassTable* table;
3957 {
3958 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3959 table = InsertClassTableForClassLoader(h_class_loader.Get());
3960 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003961 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3962 // a thread holding the dex lock and blocking on a condition variable regarding
3963 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003964 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003965 WriterMutexLock mu(self, *Locks::dex_lock_);
3966 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3967 table->InsertStrongRoot(h_dex_cache.Get());
3968 if (h_class_loader.Get() != nullptr) {
3969 // Since we added a strong root to the class table, do the write barrier as required for
3970 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003971 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003972 }
3973}
3974
Alex Lightde7f8782020-02-24 10:14:22 -08003975static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
3976 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08003977 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08003978 "Attempt to register dex file %s with multiple class loaders",
3979 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08003980}
3981
Vladimir Markocd556b02017-02-03 11:47:34 +00003982ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3983 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003984 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08003985 ObjPtr<mirror::DexCache> old_dex_cache;
3986 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003987 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003988 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003989 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
3990 old_dex_cache = DecodeDexCacheLocked(self, old_data);
3991 if (old_dex_cache != nullptr) {
3992 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
3993 return old_dex_cache;
3994 } else {
3995 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
3996 // be thrown when it's safe to do so to simplify this.
3997 registered_with_another_class_loader = true;
3998 }
3999 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004000 }
Alex Light725da8f2020-02-19 14:46:33 -08004001 // We need to have released the dex_lock_ to allocate safely.
4002 if (registered_with_another_class_loader) {
4003 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4004 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07004005 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004006 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004007 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4008 DCHECK(linear_alloc != nullptr);
4009 ClassTable* table;
4010 {
4011 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4012 table = InsertClassTableForClassLoader(class_loader);
4013 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004014 // Don't alloc while holding the lock, since allocation may need to
4015 // suspend all threads and another thread may need the dex_lock_ to
4016 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004017 StackHandleScope<3> hs(self);
4018 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00004019 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004020 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004021 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4022 // a thread holding the dex lock and blocking on a condition variable regarding
4023 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004024 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004025 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004026 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4027 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004028 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00004029 // Do InitializeNativeFields while holding dex lock to make sure two threads don't call it
David Srbecky86d6cd52020-12-02 18:13:10 +00004030 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
4031 // DCHECK that the arrays are null.
Orion Hodsonb9b7d912021-02-24 09:24:47 +00004032 h_dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Vladimir Markocd556b02017-02-03 11:47:34 +00004033 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004034 }
Alex Light725da8f2020-02-19 14:46:33 -08004035 if (old_dex_cache != nullptr) {
4036 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4037 // If this thread encountered OOME, ignore it.
4038 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
4039 self->ClearException();
4040 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
4041 // dex_lock_.
4042 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
4043 return old_dex_cache;
4044 } else {
4045 registered_with_another_class_loader = true;
4046 }
4047 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004048 }
Alex Light725da8f2020-02-19 14:46:33 -08004049 if (registered_with_another_class_loader) {
4050 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4051 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004052 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004053 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004054 self->AssertPendingOOMException();
4055 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004056 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004057 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004058 if (h_class_loader.Get() != nullptr) {
4059 // Since we added a strong root to the class table, do the write barrier as required for
4060 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004061 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004062 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004063 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
Nicolas Geoffray4f6bb442021-06-02 18:05:51 +01004064 PaletteNotifyDexFileLoaded(dex_file.GetLocation().c_str());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004065 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004066}
4067
Vladimir Markocd556b02017-02-03 11:47:34 +00004068bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004069 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004070 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004071}
4072
Vladimir Markocd556b02017-02-03 11:47:34 +00004073ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4074 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004075 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4076 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004077 if (dex_cache != nullptr) {
4078 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004079 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004080 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004081 for (const DexCacheData& data : dex_caches_) {
Alex Light725da8f2020-02-19 14:46:33 -08004082 if (DecodeDexCacheLocked(self, &data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004083 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004084 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004085 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004086 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
Alex Light725da8f2020-02-19 14:46:33 -08004087 << " " << &dex_file << " " << dex_cache_data->dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004088 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004089}
4090
Vladimir Markocd556b02017-02-03 11:47:34 +00004091ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4092 const DexFile* dex_file = dex_cache->GetDexFile();
4093 DCHECK(dex_file != nullptr);
4094 ReaderMutexLock mu(self, *Locks::dex_lock_);
4095 // Search assuming unique-ness of dex file.
4096 for (const DexCacheData& data : dex_caches_) {
4097 // Avoid decoding (and read barriers) other unrelated dex caches.
4098 if (data.dex_file == dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004099 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004100 if (registered_dex_cache != nullptr) {
4101 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4102 return data.class_table;
4103 }
4104 }
4105 }
4106 return nullptr;
4107}
4108
Alex Light725da8f2020-02-19 14:46:33 -08004109const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004110 // Search assuming unique-ness of dex file.
4111 for (const DexCacheData& data : dex_caches_) {
4112 // Avoid decoding (and read barriers) other unrelated dex caches.
4113 if (data.dex_file == &dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004114 return &data;
Vladimir Markocd556b02017-02-03 11:47:34 +00004115 }
4116 }
Alex Light725da8f2020-02-19 14:46:33 -08004117 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004118}
4119
Vladimir Marko70e2a762019-07-12 16:49:00 +01004120void ClassLinker::CreatePrimitiveClass(Thread* self,
4121 Primitive::Type type,
4122 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004123 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004124 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004125 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4126 // Do not hold lock on the primitive class object, the initialization of
4127 // primitive classes is done while the process is still single threaded.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004128 primitive_class->SetAccessFlagsDuringLinking(kAccPublic | kAccFinal | kAccAbstract);
Vladimir Marko70e2a762019-07-12 16:49:00 +01004129 primitive_class->SetPrimitiveType(type);
4130 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko70e2a762019-07-12 16:49:00 +01004131 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004132 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4133 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004134 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004135 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004136 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004137 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004138 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004139 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004140}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004141
Vladimir Marko02610552018-06-04 14:38:00 +01004142inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4143 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4144}
4145
Brian Carlstrombe977852011-07-19 14:54:54 -07004146// Create an array class (i.e. the class object for the array, not the
4147// array itself). "descriptor" looks like "[C" or "[[[[B" or
4148// "[Ljava/lang/String;".
4149//
4150// If "descriptor" refers to an array of primitives, look up the
4151// primitive type's internally-generated class object.
4152//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004153// "class_loader" is the class loader of the class that's referring to
4154// us. It's used to ensure that we're looking for the element type in
4155// the right context. It does NOT become the class loader for the
4156// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004157//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004158// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004159ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4160 const char* descriptor,
4161 size_t hash,
4162 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004163 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004164 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004165 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004166
4167 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4168 // code to be executed. We put it up here so we can avoid all the allocations associated with
4169 // creating the class. This can happen with (eg) jit threads.
4170 if (!self->CanLoadClasses()) {
4171 // Make sure we don't try to load anything, potentially causing an infinite loop.
4172 ObjPtr<mirror::Throwable> pre_allocated =
4173 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4174 self->SetException(pre_allocated);
4175 return nullptr;
4176 }
4177
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004178 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4179 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004180 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004181 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004182 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004183 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4184 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004185 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004186 DCHECK(self->IsExceptionPending());
4187 return nullptr;
4188 } else {
4189 self->ClearException();
4190 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004191 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004192 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4193 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4194 return nullptr;
4195 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004196 // See if the component type is already loaded. Array classes are
4197 // always associated with the class loader of their underlying
4198 // element type -- an array of Strings goes with the loader for
4199 // java/lang/String -- so we need to look for it there. (The
4200 // caller should have checked for the existence of the class
4201 // before calling here, but they did so with *their* class loader,
4202 // not the component type's loader.)
4203 //
4204 // If we find it, the caller adds "loader" to the class' initiating
4205 // loader list, which should prevent us from going through this again.
4206 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004207 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004208 // are the same, because our caller (FindClass) just did the
4209 // lookup. (Even if we get this wrong we still have correct behavior,
4210 // because we effectively do this lookup again when we add the new
4211 // class to the hash table --- necessary because of possible races with
4212 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004213 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004214 ObjPtr<mirror::Class> new_class =
4215 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004216 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004217 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004218 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004219 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004220 // Core array classes, i.e. Object[], Class[], String[] and primitive
4221 // arrays, have special initialization and they should be found above.
4222 DCHECK(!component_type->IsObjectClass() ||
4223 // Guard from false positives for errors before setting superclass.
4224 component_type->IsErroneousUnresolved());
4225 DCHECK(!component_type->IsStringClass());
4226 DCHECK(!component_type->IsClassClass());
4227 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004228
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004229 // Fill out the fields in the Class.
4230 //
4231 // It is possible to execute some methods against arrays, because
4232 // all arrays are subclasses of java_lang_Object_, so we need to set
4233 // up a vtable. We can just point at the one in java_lang_Object_.
4234 //
4235 // Array classes are simple enough that we don't need to do a full
4236 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004237 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4238 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4239 size_t usable_size)
4240 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004241 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004242 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4243 init_class(obj, usable_size);
4244 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4245 klass->SetComponentType(component_type.Get());
4246 // Do not hold lock for initialization, the fence issued after the visitor
4247 // returns ensures memory visibility together with the implicit consume
4248 // semantics (for all supported architectures) for any thread that loads
4249 // the array class reference from any memory locations afterwards.
4250 FinishArrayClassSetup(klass);
4251 };
4252 auto new_class = hs.NewHandle<mirror::Class>(
4253 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004254 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004255 self->AssertPendingOOMException();
4256 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004257 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004258
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004259 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004260 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004261 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4262 // duplicate events in case of races. Array classes don't really follow dedicated
4263 // load and prepare, anyways.
4264 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4265 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4266
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004267 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004268 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004269 }
4270 // Another thread must have loaded the class after we
4271 // started but before we finished. Abandon what we've
4272 // done.
4273 //
4274 // (Yes, this happens.)
4275
Vladimir Markobcf17522018-06-01 13:14:32 +01004276 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004277}
4278
Vladimir Marko9186b182018-11-06 14:55:54 +00004279ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4280 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004281 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004282 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4283 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4284 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4285 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4286 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4287 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4288 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4289 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4290 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004291 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004292 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004293 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004294 return GetClassRoot(class_root, this);
4295}
4296
4297ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4298 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4299 if (UNLIKELY(result == nullptr)) {
4300 std::string printable_type(PrintableChar(type));
4301 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4302 }
4303 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004304}
4305
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004306ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4307 ObjPtr<mirror::Class> klass,
4308 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004309 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004310 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004311 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004312 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004313 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004314 source += " from ";
4315 source += dex_cache->GetLocation()->ToModifiedUtf8();
4316 }
4317 LOG(INFO) << "Loaded class " << descriptor << source;
4318 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004319 {
4320 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004321 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004322 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004323 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004324 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004325 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004326 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004327 VerifyObject(klass);
4328 class_table->InsertWithHash(klass, hash);
4329 if (class_loader != nullptr) {
4330 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004331 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004332 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004333 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004334 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004335 }
4336 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004337 if (kIsDebugBuild) {
4338 // Test that copied methods correctly can find their holder.
4339 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4340 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4341 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004342 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004343 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004344}
4345
Vladimir Marko1998cd02017-01-13 13:02:58 +00004346void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004347 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4348 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4349 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4350 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004351 }
4352}
4353
Alex Lighte64300b2015-12-15 15:02:47 -08004354// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004355void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004356 LengthPrefixedArray<ArtMethod>* new_methods) {
4357 klass->SetMethodsPtrUnchecked(new_methods,
4358 klass->NumDirectMethods(),
4359 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004360 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004361 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004362}
4363
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004364ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4365 const char* descriptor,
4366 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004367 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4368}
4369
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004370ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4371 const char* descriptor,
4372 size_t hash,
4373 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004374 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4375 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4376 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004377 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004378 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004379 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004380 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004381 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004382 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004383}
4384
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004385class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4386 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004387 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004388
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004389 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004390 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004391 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004392 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004393 if (class_table != nullptr) {
4394 class_table->FreezeSnapshot();
4395 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004396 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004397};
4398
4399void ClassLinker::MoveClassTableToPreZygote() {
4400 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004401 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004402 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004403 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004404}
4405
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004406// Look up classes by hash and descriptor and put all matching ones in the result array.
4407class LookupClassesVisitor : public ClassLoaderVisitor {
4408 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004409 LookupClassesVisitor(const char* descriptor,
4410 size_t hash,
4411 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004412 : descriptor_(descriptor),
4413 hash_(hash),
4414 result_(result) {}
4415
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004416 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004417 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004418 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004419 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004420 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4421 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004422 result_->push_back(klass);
4423 }
4424 }
4425
4426 private:
4427 const char* const descriptor_;
4428 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004429 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004430};
4431
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004432void ClassLinker::LookupClasses(const char* descriptor,
4433 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004434 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004435 Thread* const self = Thread::Current();
4436 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004437 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004438 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004439 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004440 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004441 result.push_back(klass);
4442 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004443 LookupClassesVisitor visitor(descriptor, hash, &result);
4444 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004445}
4446
Alex Lightf1f10492015-10-07 16:08:36 -07004447bool ClassLinker::AttemptSupertypeVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004448 verifier::VerifierDeps* verifier_deps,
Alex Lightf1f10492015-10-07 16:08:36 -07004449 Handle<mirror::Class> klass,
4450 Handle<mirror::Class> supertype) {
4451 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004452 DCHECK(klass != nullptr);
4453 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004454
Alex Lightf1f10492015-10-07 16:08:36 -07004455 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004456 VerifyClass(self, verifier_deps, supertype);
Alex Lightf1f10492015-10-07 16:08:36 -07004457 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004458
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004459 if (supertype->IsVerified()
4460 || supertype->ShouldVerifyAtRuntime()
4461 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004462 // The supertype is either verified, or we soft failed at AOT time.
4463 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004464 return true;
4465 }
4466 // If we got this far then we have a hard failure.
4467 std::string error_msg =
4468 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004469 klass->PrettyDescriptor().c_str(),
4470 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004471 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004472 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004473 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004474 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004475 // Set during VerifyClass call (if at all).
4476 self->ClearException();
4477 }
4478 // Change into a verify error.
4479 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004480 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004481 self->GetException()->SetCause(cause.Get());
4482 }
4483 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4484 if (Runtime::Current()->IsAotCompiler()) {
4485 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4486 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004487 // Need to grab the lock to change status.
4488 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004489 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004490 return false;
4491}
4492
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004493verifier::FailureKind ClassLinker::VerifyClass(Thread* self,
4494 verifier::VerifierDeps* verifier_deps,
4495 Handle<mirror::Class> klass,
4496 verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004497 {
4498 // TODO: assert that the monitor on the Class is held
4499 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004500
Andreas Gampe884f3b82016-03-30 19:52:58 -07004501 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004502 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004503 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004504 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004505 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4506 // case we may see the same status again. b/62912904. This is why the check is
4507 // greater or equal.
4508 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004509 << "Class '" << klass->PrettyClass()
4510 << "' performed an illegal verification state transition from " << old_status
4511 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004512 old_status = klass->GetStatus();
4513 }
jeffhao98eacac2011-09-14 16:11:53 -07004514
Andreas Gampe884f3b82016-03-30 19:52:58 -07004515 // The class might already be erroneous, for example at compile time if we attempted to verify
4516 // this class as a parent to another.
4517 if (klass->IsErroneous()) {
4518 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004519 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004520 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004521
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004522 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004523 if (klass->IsVerified()) {
Nicolas Geoffray80789962021-04-30 16:50:39 +01004524 if (verifier_deps != nullptr &&
4525 verifier_deps->ContainsDexFile(klass->GetDexFile()) &&
4526 !verifier_deps->HasRecordedVerifiedStatus(klass->GetDexFile(), *klass->GetClassDef()) &&
4527 !Runtime::Current()->IsAotCompiler()) {
4528 // If the klass is verified, but `verifier_deps` did not record it, this
4529 // means we are running background verification of a secondary dex file.
4530 // Re-run the verifier to populate `verifier_deps`.
4531 // No need to run the verification when running on the AOT Compiler, as
4532 // the driver handles those multithreaded cases already.
4533 std::string error_msg;
4534 verifier::FailureKind failure =
4535 PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
4536 // We could have soft failures, so just check that we don't have a hard
4537 // failure.
4538 DCHECK_NE(failure, verifier::FailureKind::kHardFailure) << error_msg;
4539 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004540 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004541 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004542
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004543 if (klass->IsVerifiedNeedsAccessChecks()) {
4544 if (!Runtime::Current()->IsAotCompiler()) {
4545 // Mark the class as having a verification attempt to avoid re-running
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004546 // the verifier.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004547 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4548 }
4549 return verifier::FailureKind::kAccessChecksFailure;
4550 }
4551
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004552 // For AOT, don't attempt to re-verify if we have already found we should
4553 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004554 if (klass->ShouldVerifyAtRuntime()) {
4555 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004556 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004557 }
jeffhao98eacac2011-09-14 16:11:53 -07004558
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004559 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4560 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004561
4562 // Skip verification if disabled.
4563 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004564 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004565 UpdateClassAfterVerification(klass, image_pointer_size_, verifier::FailureKind::kNoFailure);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004566 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004567 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004568 }
4569
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004570 VLOG(class_linker) << "Beginning verification for class: "
4571 << klass->PrettyDescriptor()
4572 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4573
Ian Rogers9ffb0392012-09-10 11:56:50 -07004574 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004575 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004576 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4577 // If we have a superclass and we get a hard verification failure we can return immediately.
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004578 if (supertype != nullptr &&
4579 !AttemptSupertypeVerification(self, verifier_deps, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004580 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004581 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004582 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004583
Alex Lightf1f10492015-10-07 16:08:36 -07004584 // Verify all default super-interfaces.
4585 //
4586 // (1) Don't bother if the superclass has already had a soft verification failure.
4587 //
4588 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4589 // recursive initialization by themselves. This is because when an interface is initialized
4590 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4591 // but choose not to for an optimization. If the interfaces is being verified due to a class
4592 // initialization (which would need all the default interfaces to be verified) the class code
4593 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004594 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004595 && !klass->IsInterface()) { // See (2)
4596 int32_t iftable_count = klass->GetIfTableCount();
4597 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4598 // Loop through all interfaces this class has defined. It doesn't matter the order.
4599 for (int32_t i = 0; i < iftable_count; i++) {
4600 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004601 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004602 // We only care if we have default interfaces and can skip if we are already verified...
4603 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4604 continue;
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004605 } else if (UNLIKELY(!AttemptSupertypeVerification(self, verifier_deps, klass, iface))) {
Alex Lightf1f10492015-10-07 16:08:36 -07004606 // We had a hard failure while verifying this interface. Just return immediately.
4607 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004608 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004609 } else if (UNLIKELY(!iface->IsVerified())) {
4610 // We softly failed to verify the iface. Stop checking and clean up.
4611 // Put the iface into the supertype handle so we know what caused us to fail.
4612 supertype.Assign(iface.Get());
4613 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004614 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004615 }
4616 }
4617
Alex Lightf1f10492015-10-07 16:08:36 -07004618 // At this point if verification failed, then supertype is the "first" supertype that failed
4619 // verification (without a specific order). If verification succeeded, then supertype is either
4620 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004621 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004622 supertype.Get() == klass->GetSuperClass() ||
4623 !supertype->IsVerified());
4624
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004625 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004626 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004627 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004628 bool preverified = VerifyClassUsingOatFile(self, dex_file, klass, oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004629
4630 VLOG(class_linker) << "Class preverified status for class "
4631 << klass->PrettyDescriptor()
4632 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4633 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004634 << preverified
4635 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004636
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004637 // If the oat file says the class had an error, re-run the verifier. That way we will either:
4638 // 1) Be successful at runtime, or
4639 // 2) Get a precise error message.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004640 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004641
Ian Rogers62d6c772013-02-27 08:32:07 -08004642 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004643 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004644 if (!preverified) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004645 verifier_failure = PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004646 } else if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks) {
4647 verifier_failure = verifier::FailureKind::kAccessChecksFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004648 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004649
4650 // Verification is done, grab the lock again.
4651 ObjectLock<mirror::Class> lock(self, klass);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004652 self->AssertNoPendingException();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004653
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004654 if (verifier_failure == verifier::FailureKind::kHardFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004655 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004656 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4657 << " because: " << error_msg;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004658 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004659 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004660 return verifier_failure;
jeffhao5cfd6fb2011-09-27 13:54:29 -07004661 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004662
4663 // Make sure all classes referenced by catch blocks are resolved.
4664 ResolveClassExceptionHandlerTypes(klass);
4665
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004666 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004667 if (supertype != nullptr && supertype->ShouldVerifyAtRuntime()) {
4668 // Regardless of our own verification result, we need to verify the class
4669 // at runtime if the super class is not verified. This is required in case
4670 // we generate an app/boot image.
4671 verifier_failure = verifier::FailureKind::kSoftFailure;
4672 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4673 } else if (verifier_failure == verifier::FailureKind::kNoFailure) {
4674 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4675 } else if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4676 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
4677 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4678 } else {
4679 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4680 }
4681 // Notify the compiler about the verification status, in case the class
4682 // was verified implicitly (eg super class of a compiled class). When the
4683 // compiler unloads dex file after compilation, we still want to keep
4684 // verification states.
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004685 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4686 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004687 } else {
4688 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004689 }
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004690
4691 UpdateClassAfterVerification(klass, image_pointer_size_, verifier_failure);
Nicolas Geoffray08025182016-10-25 17:20:18 +01004692 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004693}
4694
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004695verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004696 verifier::VerifierDeps* verifier_deps,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004697 Handle<mirror::Class> klass,
4698 verifier::HardFailLogMode log_level,
4699 std::string* error_msg) {
4700 Runtime* const runtime = Runtime::Current();
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004701 StackHandleScope<2> hs(self);
4702 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4703 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004704 return verifier::ClassVerifier::VerifyClass(self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004705 verifier_deps,
Nicolas Geoffray7744b692021-07-06 16:19:32 +01004706 dex_cache->GetDexFile(),
4707 klass,
4708 dex_cache,
4709 class_loader,
4710 *klass->GetClassDef(),
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004711 runtime->GetCompilerCallbacks(),
4712 runtime->IsAotCompiler(),
4713 log_level,
4714 Runtime::Current()->GetTargetSdkVersion(),
4715 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004716}
4717
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004718bool ClassLinker::VerifyClassUsingOatFile(Thread* self,
4719 const DexFile& dex_file,
4720 Handle<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004721 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004722 // If we're compiling, we can only verify the class using the oat file if
4723 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004724 // the compilation unit (app - dependencies). We will let the compiler callback
4725 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004726 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004727 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004728 // We are compiling an app (not the image).
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004729 if (!callbacks->CanUseOatStatusForVerification(klass.Get())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004730 return false;
4731 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004732 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004733
Andreas Gampeb40d3612018-06-26 15:49:42 -07004734 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004735 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004736 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004737 return false;
4738 }
4739
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004740 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004741 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004742 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004743 return true;
4744 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004745 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4746 // We return that the clas has already been verified, and the caller should
4747 // check the class status to ensure we run with access checks.
4748 return true;
4749 }
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004750
4751 // Check the class status with the vdex file.
4752 const OatFile* oat_file = oat_dex_file->GetOatFile();
4753 if (oat_file != nullptr) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004754 ClassStatus vdex_status = oat_file->GetVdexFile()->ComputeClassStatus(self, klass);
4755 if (vdex_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4756 oat_file_class_status = vdex_status;
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004757 return true;
4758 }
4759 }
4760
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004761 // If we only verified a subset of the classes at compile time, we can end up with classes that
4762 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004763 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004764 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004765 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004766 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4767 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4768 << klass->PrettyClass() << " " << dex_file.GetLocation();
4769
Vladimir Marko72ab6842017-01-20 19:32:50 +00004770 if (mirror::Class::IsErroneous(oat_file_class_status)) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004771 // Compile time verification failed with a hard error. We'll re-run
4772 // verification, which might be successful at runtime.
jeffhao1ac29442012-03-26 11:37:32 -07004773 return false;
4774 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004775 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004776 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4777 // not loading the class.
4778 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4779 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004780 return false;
4781 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004782 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004783 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004784 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004785 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004786 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004787}
4788
Alex Light5a559862016-01-29 12:24:48 -08004789void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004790 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004791 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004792 }
4793}
4794
Alex Light5a559862016-01-29 12:24:48 -08004795void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004796 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004797 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004798 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004799 return; // native or abstract method
4800 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004801 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004802 return; // nothing to process
4803 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004804 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004805 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004806 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4807 CatchHandlerIterator iterator(handlers_ptr);
4808 for (; iterator.HasNext(); iterator.Next()) {
4809 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4810 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004811 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004812 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004813 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004814 DCHECK(Thread::Current()->IsExceptionPending());
4815 Thread::Current()->ClearException();
4816 }
4817 }
4818 }
4819 handlers_ptr = iterator.EndDataPointer();
4820 }
4821}
4822
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004823ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4824 jstring name,
4825 jobjectArray interfaces,
4826 jobject loader,
4827 jobjectArray methods,
4828 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004829 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004830
4831 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4832 // code to be executed. We put it up here so we can avoid all the allocations associated with
4833 // creating the class. This can happen with (eg) jit-threads.
4834 if (!self->CanLoadClasses()) {
4835 // Make sure we don't try to load anything, potentially causing an infinite loop.
4836 ObjPtr<mirror::Throwable> pre_allocated =
4837 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4838 self->SetException(pre_allocated);
4839 return nullptr;
4840 }
4841
Alex Light133987d2020-03-26 19:22:12 +00004842 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004843 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004844 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004845 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004846 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004847 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004848 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004849 DCHECK(temp_klass->GetClass() != nullptr);
4850 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004851 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4852 // the methods.
Nicolas Geoffray66934ef2021-07-07 14:56:23 +01004853 temp_klass->SetAccessFlagsDuringLinking(kAccClassIsProxy | kAccPublic | kAccFinal);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004854 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4855 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4856 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004857 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004858 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004859 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004860 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004861 std::string storage;
4862 const char* descriptor = temp_klass->GetDescriptor(&storage);
4863 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004864
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004865 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004866 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004867
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004868 // Insert the class before loading the fields as the field roots
4869 // (ArtField::declaring_class_) are only visited from the class
4870 // table. There can't be any suspend points between inserting the
4871 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004872 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004873 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004874
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004875 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004876 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004877 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004878 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004879
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004880 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4881 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004882 ArtField& interfaces_sfield = sfields->At(0);
4883 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004884 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004885 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004886
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004887 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004888 ArtField& throws_sfield = sfields->At(1);
4889 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004890 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004891 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004892
Ian Rogers466bb252011-10-14 03:29:56 -07004893 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004894 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004895
Alex Light133987d2020-03-26 19:22:12 +00004896 // The array we get passed contains all methods, including private and static
4897 // ones that aren't proxied. We need to filter those out since only interface
4898 // methods (non-private & virtual) are actually proxied.
4899 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4900 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004901 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004902 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004903 // List of the actual virtual methods this class will have.
4904 std::vector<ArtMethod*> proxied_methods;
4905 std::vector<size_t> proxied_throws_idx;
4906 proxied_methods.reserve(h_methods->GetLength());
4907 proxied_throws_idx.reserve(h_methods->GetLength());
4908 // Filter out to only the non-private virtual methods.
4909 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4910 ArtMethod* m = mirror->GetArtMethod();
4911 if (!m->IsPrivate() && !m->IsStatic()) {
4912 proxied_methods.push_back(m);
4913 proxied_throws_idx.push_back(idx);
4914 }
4915 }
4916 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004917 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4918 // contains an array of all the classes each function is declared to throw.
4919 // This is used to wrap unexpected exceptions in a
4920 // UndeclaredThrowableException exception. This array is in the same order as
4921 // the methods array and like the methods array must be filtered to remove any
4922 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004923 const bool has_filtered_methods =
4924 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4925 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4926 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4927 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4928 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4929 (has_filtered_methods)
4930 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4931 self, original_proxied_throws->GetClass(), num_virtual_methods)
4932 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004933 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4934 self->AssertPendingOOMException();
4935 return nullptr;
4936 }
Alex Light133987d2020-03-26 19:22:12 +00004937 if (has_filtered_methods) {
4938 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
4939 DCHECK_LE(new_idx, orig_idx);
4940 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
4941 }
4942 }
Alex Lighte64300b2015-12-15 15:02:47 -08004943
4944 // Create the methods array.
4945 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4946 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004947 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4948 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004949 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004950 self->AssertPendingOOMException();
4951 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004952 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004953 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004954
4955 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004956 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004957
4958 // Create virtual method using specified prototypes.
4959 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004960 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004961 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004962 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004963 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004964 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4965 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004966 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004967
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004968 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004969 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004970 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004971 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004972 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004973
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004974 // At this point the class is loaded. Publish a ClassLoad event.
4975 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4976 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4977
4978 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004979 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004980 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004981 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004982 // Link the fields and virtual methods, creating vtable and iftables.
4983 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004984 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004985 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004986 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Markoa4d28dd2021-06-30 11:28:06 +01004987 if (!temp_klass->IsErroneous()) {
4988 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
4989 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004990 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004991 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004992 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004993 CHECK(temp_klass->IsRetired());
4994 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004995
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004996 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004997 interfaces_sfield.SetObject<false>(
4998 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004999 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005000 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5001 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005002 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00005003 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005004
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005005 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5006
Vladimir Marko305c38b2018-02-14 11:50:07 +00005007 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5008 // See also ClassLinker::EnsureInitialized().
5009 if (kBitstringSubtypeCheckEnabled) {
5010 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5011 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5012 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5013 }
5014
Vladimir Markobf121912019-06-04 13:49:05 +01005015 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005016 {
5017 // Lock on klass is released. Lock new class object.
5018 ObjectLock<mirror::Class> initialization_lock(self, klass);
Vladimir Markobf121912019-06-04 13:49:05 +01005019 // Conservatively go through the ClassStatus::kInitialized state.
5020 callback = MarkClassInitialized(self, klass);
5021 }
5022 if (callback != nullptr) {
5023 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005024 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005025
David Srbecky346fd962020-07-27 16:51:00 +01005026 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07005027 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005028 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005029 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5030
Ian Rogersc2b44472011-12-14 21:17:17 -08005031 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005032 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005033 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08005034 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005035
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005036 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005037 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005038 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005039 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005040 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005041
5042 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005043 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005044 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005045
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005046 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005047 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005048 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005049 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005050 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005051 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005052}
5053
Mathieu Chartiere401d142015-04-22 13:56:20 -07005054void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5055 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005056 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5057 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005058
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005059 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5060 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005061 ArtMethod* proxy_constructor =
5062 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005063 DCHECK(proxy_constructor != nullptr)
5064 << "Could not find <init> method in java.lang.reflect.Proxy";
5065
Jeff Haodb8a6642014-08-14 17:18:52 -07005066 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5067 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005068 DCHECK(out != nullptr);
5069 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005070 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005071 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005072 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005073 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5074 kAccPublic |
5075 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005076 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005077
5078 // Set the original constructor method.
5079 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005080}
5081
Mathieu Chartiere401d142015-04-22 13:56:20 -07005082void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005083 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005084 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5085 CHECK_STREQ(np->GetName(), "<init>");
5086 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005087 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005088}
5089
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005090void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005091 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005092 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005093 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005094 DCHECK(out != nullptr);
5095 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005096
Alex Lighte9dd04f2016-03-16 16:09:45 -07005097 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005098 out->SetDeclaringClass(klass.Get());
Vladimir Markode0d0de2021-03-18 14:12:35 +00005099 // Clear the abstract and default flags to ensure that defaults aren't picked in
Alex Lighte9dd04f2016-03-16 16:09:45 -07005100 // preference to the invocation handler.
Vladimir Markode0d0de2021-03-18 14:12:35 +00005101 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005102 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005103 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5104 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005105 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5106
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005107 // Set the original interface method.
5108 out->SetDataPtrSize(prototype, image_pointer_size_);
5109
Ian Rogers466bb252011-10-14 03:29:56 -07005110 // At runtime the method looks like a reference and argument saving method, clone the code
5111 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005112 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005113}
Jesse Wilson95caa792011-10-12 18:14:17 -04005114
Mathieu Chartiere401d142015-04-22 13:56:20 -07005115void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005116 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005117 CHECK(!prototype->IsFinal());
5118 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005119 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005120
5121 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5122 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005123 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005124 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005125}
5126
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005127bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005128 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005129 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005130 return true;
5131 }
5132 if (!can_init_statics) {
5133 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005134 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005135 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005136 return false;
5137 }
5138 // Check if there are encoded static values needing initialization.
5139 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005140 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005141 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005142 if (dex_class_def->static_values_off_ != 0) {
5143 return false;
5144 }
5145 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005146 }
5147 // If we are a class we need to initialize all interfaces with default methods when we are
5148 // initialized. Check all of them.
5149 if (!klass->IsInterface()) {
5150 size_t num_interfaces = klass->GetIfTableCount();
5151 for (size_t i = 0; i < num_interfaces; i++) {
5152 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5153 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5154 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005155 return false;
5156 }
5157 }
5158 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005159 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005160 if (klass->IsInterface() || !klass->HasSuperClass()) {
5161 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005162 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005163 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005164 if (super_class->IsInitialized()) {
5165 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005166 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005167 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005168}
5169
Mathieu Chartier23369542020-03-04 08:24:11 -08005170bool ClassLinker::InitializeClass(Thread* self,
5171 Handle<mirror::Class> klass,
5172 bool can_init_statics,
5173 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005174 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5175
5176 // Are we already initialized and therefore done?
5177 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5178 // an initialized class will never change its state.
5179 if (klass->IsInitialized()) {
5180 return true;
5181 }
5182
5183 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005184 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005185 return false;
5186 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005187
Ian Rogers7b078e82014-09-10 14:44:24 -07005188 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005189 Runtime* const runtime = Runtime::Current();
5190 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005191 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005192 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005193 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005194
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005195 // Re-check under the lock in case another thread initialized ahead of us.
5196 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005197 return true;
5198 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005199
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005200 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005201 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005202 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005203 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005204 return false;
5205 }
5206
Vladimir Marko72ab6842017-01-20 19:32:50 +00005207 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5208 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005209
5210 if (!klass->IsVerified()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00005211 VerifyClass(self, /*verifier_deps= */ nullptr, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005212 if (!klass->IsVerified()) {
5213 // We failed to verify, expect either the klass to be erroneous or verification failed at
5214 // compile time.
5215 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005216 // The class is erroneous. This may be a verifier error, or another thread attempted
5217 // verification and/or initialization and failed. We can distinguish those cases by
5218 // whether an exception is already pending.
5219 if (self->IsExceptionPending()) {
5220 // Check that it's a VerifyError.
Nicolas Geoffray4dc65892021-07-05 17:43:35 +01005221 DCHECK(IsVerifyError(self->GetException()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005222 } else {
5223 // Check that another thread attempted initialization.
5224 DCHECK_NE(0, klass->GetClinitThreadId());
5225 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5226 // Need to rethrow the previous failure now.
5227 ThrowEarlierClassFailure(klass.Get(), true);
5228 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005229 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005230 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005231 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005232 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005233 self->AssertNoPendingException();
5234 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005235 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005236 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005237 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005238 } else {
5239 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005240 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005241
5242 // A separate thread could have moved us all the way to initialized. A "simple" example
5243 // involves a subclass of the current class being initialized at the same time (which
5244 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005245 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005246 if (klass->IsInitialized()) {
5247 return true;
5248 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005249 }
5250
Vladimir Marko2c64a832018-01-04 11:31:56 +00005251 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005252 // initializing higher up the stack or another thread has beat us
5253 // to initializing and we need to wait. Either way, this
5254 // invocation of InitializeClass will not be responsible for
5255 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005256 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005257 // Could have got an exception during verification.
5258 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005259 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005260 return false;
5261 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005262 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005263 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005264 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005265 return true;
5266 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005267 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005268 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005269 }
5270
Jeff Haoe2e40342017-07-19 10:45:18 -07005271 // Try to get the oat class's status for this class if the oat file is present. The compiler
5272 // tries to validate superclass descriptors, and writes the result into the oat file.
5273 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5274 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5275 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005276 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005277 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5278 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5279 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005280 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005281 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005282 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005283 return false;
5284 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005285 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005286
Vladimir Marko2c64a832018-01-04 11:31:56 +00005287 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005288 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005289
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005290 // From here out other threads may observe that we're initializing and so changes of state
5291 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005292 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005293 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005294
Mathieu Chartier23369542020-03-04 08:24:11 -08005295 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005296 }
5297
Andreas Gampeaf864702019-07-23 14:05:35 -07005298 uint64_t t_sub = 0;
5299
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005300 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005301 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005302 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005303 if (!super_class->IsInitialized()) {
5304 CHECK(!super_class->IsInterface());
5305 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005306 StackHandleScope<1> hs(self);
5307 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005308 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005309 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005310 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005311 if (!super_initialized) {
5312 // The super class was verified ahead of entering initializing, we should only be here if
5313 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005314 // For the case of aot compiler, the super class might also be initializing but we don't
5315 // want to process circular dependencies in pre-compile.
5316 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005317 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005318 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005319 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005320 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005321 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005322 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005323 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005324 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005325 return false;
5326 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005327 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005328 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005329 }
5330
Alex Lighteb7c1442015-08-31 13:17:42 -07005331 if (!klass->IsInterface()) {
5332 // Initialize interfaces with default methods for the JLS.
5333 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005334 // Only setup the (expensive) handle scope if we actually need to.
5335 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005336 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005337 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5338 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005339 handle_scope_iface.Assign(klass->GetDirectInterface(i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005340 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005341 CHECK(handle_scope_iface->IsInterface());
5342 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5343 // We have already done this for this interface. Skip it.
5344 continue;
5345 }
5346 // We cannot just call initialize class directly because we need to ensure that ALL
5347 // interfaces with default methods are initialized. Non-default interface initialization
5348 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005349 // This is not very precise, misses all walking.
5350 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005351 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5352 handle_scope_iface,
5353 can_init_statics,
5354 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005355 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005356 if (!iface_initialized) {
5357 ObjectLock<mirror::Class> lock(self, klass);
5358 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005359 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005360 return false;
5361 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005362 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005363 }
5364 }
5365 }
5366
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005367 const size_t num_static_fields = klass->NumStaticFields();
5368 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005369 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005370 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005371 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005372 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005373 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005374
5375 // Eagerly fill in static fields so that the we don't have to do as many expensive
5376 // Class::FindStaticField in ResolveField.
5377 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005378 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005379 const uint32_t field_idx = field->GetDexFieldIndex();
David Srbecky5de5efe2021-02-15 21:23:00 +00005380 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005381 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005382 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005383 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5384 field,
5385 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5386 hiddenapi::AccessMethod::kNone));
David Srbecky5de5efe2021-02-15 21:23:00 +00005387 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005388 } else {
5389 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005390 }
5391 }
5392
Vladimir Markoe11dd502017-12-08 14:09:45 +00005393 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5394 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005395 this,
5396 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005397 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005398
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005399 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005400 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005401 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005402 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5403 if (!value_it.HasNext()) {
5404 break;
5405 }
5406 ArtField* art_field = ResolveField(field.GetIndex(),
5407 dex_cache,
5408 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005409 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005410 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005411 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005412 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005413 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005414 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005415 if (self->IsExceptionPending()) {
5416 break;
5417 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005418 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005419 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005420 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005421 }
5422 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005423
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005424
Mathieu Chartierda595be2016-08-10 13:57:39 -07005425 if (!self->IsExceptionPending()) {
5426 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5427 if (clinit != nullptr) {
5428 CHECK(can_init_statics);
5429 JValue result;
5430 clinit->Invoke(self, nullptr, 0, &result, "V");
5431 }
5432 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005433 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005434 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005435
Vladimir Markobf121912019-06-04 13:49:05 +01005436 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005437 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005438 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005439 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005440
5441 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005442 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005443 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005444 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005445 } else if (Runtime::Current()->IsTransactionAborted()) {
5446 // The exception thrown when the transaction aborted has been caught and cleared
5447 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005448 VLOG(compiler) << "Return from class initializer of "
5449 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005450 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005451 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005452 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005453 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005454 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005455 if (stats_enabled) {
5456 RuntimeStats* global_stats = runtime->GetStats();
5457 RuntimeStats* thread_stats = self->GetStats();
5458 ++global_stats->class_init_count;
5459 ++thread_stats->class_init_count;
5460 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5461 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5462 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005463 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005464 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005465 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005466 std::string temp;
5467 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005468 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005469 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005470 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005471 }
Vladimir Markobf121912019-06-04 13:49:05 +01005472 if (callback != nullptr) {
5473 callback->MakeVisible(self);
5474 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005475 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005476}
5477
Alex Lighteb7c1442015-08-31 13:17:42 -07005478// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5479// and perform the initialization only on those interfaces that contain default methods.
5480bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5481 Handle<mirror::Class> iface,
5482 bool can_init_statics,
5483 bool can_init_parents) {
5484 CHECK(iface->IsInterface());
5485 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005486 // Only create the (expensive) handle scope if we need it.
5487 if (UNLIKELY(num_direct_ifaces > 0)) {
5488 StackHandleScope<1> hs(self);
5489 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5490 // First we initialize all of iface's super-interfaces recursively.
5491 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005492 ObjPtr<mirror::Class> super_iface = iface->GetDirectInterface(i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005493 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005494 if (!super_iface->HasBeenRecursivelyInitialized()) {
5495 // Recursive step
5496 handle_super_iface.Assign(super_iface);
5497 if (!InitializeDefaultInterfaceRecursive(self,
5498 handle_super_iface,
5499 can_init_statics,
5500 can_init_parents)) {
5501 return false;
5502 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005503 }
5504 }
5505 }
5506
5507 bool result = true;
5508 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5509 // initialize if we don't have default methods.
5510 if (iface->HasDefaultMethods()) {
5511 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5512 }
5513
5514 // Mark that this interface has undergone recursive default interface initialization so we know we
5515 // can skip it on any later class initializations. We do this even if we are not a default
5516 // interface since we can still avoid the traversal. This is purely a performance optimization.
5517 if (result) {
5518 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005519 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5520 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5521 // initialization is a performance optimization (to avoid another idempotent visit
5522 // for other implementing classes/interfaces), and can be revisited later.
5523 ObjectTryLock<mirror::Class> lock(self, iface);
5524 if (lock.Acquired()) {
5525 iface->SetRecursivelyInitialized();
5526 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005527 }
5528 return result;
5529}
5530
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005531bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5532 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005533 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005534 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005535 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005536 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005537 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005538 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005539
5540 // When we wake up, repeat the test for init-in-progress. If
5541 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005542 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005543 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005544 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005545 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005546 return false;
5547 }
5548 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005549 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005550 continue;
5551 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005552 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005553 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005554 // Compile time initialization failed.
5555 return false;
5556 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005557 if (klass->IsErroneous()) {
5558 // The caller wants an exception, but it was thrown in a
5559 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005560 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005561 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005562 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005563 return false;
5564 }
5565 if (klass->IsInitialized()) {
5566 return true;
5567 }
David Sehr709b0702016-10-13 09:12:37 -07005568 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005569 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005570 }
Ian Rogers07140832014-09-30 15:43:59 -07005571 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005572}
5573
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005574static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5575 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005576 ArtMethod* method,
5577 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005578 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005579 DCHECK(Thread::Current()->IsExceptionPending());
5580 DCHECK(!m->IsProxyMethod());
5581 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005582 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5583 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005584 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005585 std::string return_type = dex_file->PrettyType(return_type_idx);
5586 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005587 ThrowWrappedLinkageError(klass.Get(),
5588 "While checking class %s method %s signature against %s %s: "
5589 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005590 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5591 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005592 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005593 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005594 return_type.c_str(), class_loader.c_str());
5595}
5596
5597static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5598 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005599 ArtMethod* method,
5600 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005601 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005602 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005603 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005604 DCHECK(Thread::Current()->IsExceptionPending());
5605 DCHECK(!m->IsProxyMethod());
5606 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005607 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5608 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005609 ThrowWrappedLinkageError(klass.Get(),
5610 "While checking class %s method %s signature against %s %s: "
5611 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005612 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5613 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005614 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005615 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005616 index, arg_type.c_str(), class_loader.c_str());
5617}
5618
5619static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5620 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005621 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005622 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005623 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005624 ThrowLinkageError(klass.Get(),
5625 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005626 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5627 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005628 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005629 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005630 error_msg.c_str());
5631}
5632
Ian Rogersb5fb2072014-12-02 17:22:02 -08005633static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005634 Handle<mirror::Class> klass,
5635 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005636 ArtMethod* method1,
5637 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005638 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005639 {
5640 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005641 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005642 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005643 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005644 return false;
5645 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005646 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005647 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005648 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005649 return false;
5650 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005651 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005652 ThrowSignatureMismatch(klass, super_klass, method1,
5653 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005654 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005655 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005656 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005657 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005658 return false;
5659 }
5660 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005661 const dex::TypeList* types1 = method1->GetParameterTypeList();
5662 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005663 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005664 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005665 ThrowSignatureMismatch(klass, super_klass, method1,
5666 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005667 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005668 return false;
5669 }
5670 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005671 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005672 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005673 ThrowSignatureMismatch(klass, super_klass, method1,
5674 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005675 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005676 return false;
5677 }
5678 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005679 }
5680 uint32_t num_types = types1->Size();
5681 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005682 ThrowSignatureMismatch(klass, super_klass, method1,
5683 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005684 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005685 return false;
5686 }
5687 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005688 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005689 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005690 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005691 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005692 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005693 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005694 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005695 return false;
5696 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005697 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005698 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005699 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005700 if (UNLIKELY(other_param_type == nullptr)) {
5701 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005702 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005703 return false;
5704 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005705 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005706 ThrowSignatureMismatch(klass, super_klass, method1,
5707 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5708 i,
David Sehr709b0702016-10-13 09:12:37 -07005709 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005710 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005711 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005712 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005713 return false;
5714 }
5715 }
5716 return true;
5717}
5718
5719
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005720bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005721 if (klass->IsInterface()) {
5722 return true;
5723 }
Ian Rogers151f2212014-05-06 11:27:27 -07005724 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005725 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005726 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005727 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005728 if (klass->HasSuperClass() &&
5729 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005730 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005731 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005732 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5733 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5734 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005735 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5736 klass,
5737 super_klass,
5738 m,
5739 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005740 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005741 return false;
5742 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005743 }
5744 }
5745 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005746 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005747 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5748 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5749 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005750 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005751 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5752 j, image_pointer_size_);
5753 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5754 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005755 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5756 klass,
5757 super_klass,
5758 m,
5759 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005760 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005761 return false;
5762 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005763 }
5764 }
5765 }
5766 }
5767 return true;
5768}
5769
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005770bool ClassLinker::EnsureInitialized(Thread* self,
5771 Handle<mirror::Class> c,
5772 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005773 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005774 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005775
Mathieu Chartier524507a2014-08-27 15:28:28 -07005776 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005777 // If we've seen an initialized but not visibly initialized class
5778 // many times, request visible initialization.
5779 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5780 // Thanks to the x86 memory model classes skip the initialized status.
5781 DCHECK(c->IsVisiblyInitialized());
5782 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5783 if (self->IncrementMakeVisiblyInitializedCounter()) {
5784 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5785 }
5786 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07005787 return true;
5788 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005789 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5790 //
5791 // Ensure the bitstring is initialized before any of the class initialization
5792 // logic occurs. Once a class initializer starts running, objects can
5793 // escape into the heap and use the subtype checking code.
5794 //
5795 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5796 // can be used as a source for the IsSubClass check, and that all ancestors
5797 // of the class are Assigned (can be used as a target for IsSubClass check)
5798 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005799 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005800 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005801 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005802 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5803 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005804 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005805 if (!success) {
5806 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005807 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Vladimir Markoac576912021-03-31 11:16:22 +01005808 } else {
5809 // There may or may not be an exception pending. If there is, clear it.
5810 // We propagate the exception only if we can initialize fields and parents.
5811 self->ClearException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005812 }
5813 } else {
5814 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005815 }
5816 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005817}
5818
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005819void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5820 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005821 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005822 for (ArtField& field : new_class->GetIFields()) {
5823 if (field.GetDeclaringClass() == temp_class) {
5824 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005825 }
5826 }
5827
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005828 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005829 for (ArtField& field : new_class->GetSFields()) {
5830 if (field.GetDeclaringClass() == temp_class) {
5831 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005832 }
5833 }
5834
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005835 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005836 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005837 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005838 if (method.GetDeclaringClass() == temp_class) {
5839 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005840 }
5841 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005842
5843 // Make sure the remembered set and mod-union tables know that we updated some of the native
5844 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005845 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005846}
5847
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005848void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005849 CHECK(class_loader->GetAllocator() == nullptr);
5850 CHECK(class_loader->GetClassTable() == nullptr);
5851 Thread* const self = Thread::Current();
5852 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005853 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005854 // Create and set the class table.
5855 data.class_table = new ClassTable;
5856 class_loader->SetClassTable(data.class_table);
5857 // Create and set the linear allocator.
5858 data.allocator = Runtime::Current()->CreateLinearAlloc();
5859 class_loader->SetAllocator(data.allocator);
5860 // Add to the list so that we know to free the data later.
5861 class_loaders_.push_back(data);
5862}
5863
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005864ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005865 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005866 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005867 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005868 ClassTable* class_table = class_loader->GetClassTable();
5869 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005870 RegisterClassLoader(class_loader);
5871 class_table = class_loader->GetClassTable();
5872 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005873 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005874 return class_table;
5875}
5876
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005877ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005878 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005879}
5880
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005881static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005882 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005883 while (klass->HasSuperClass()) {
5884 klass = klass->GetSuperClass();
5885 if (klass->ShouldHaveImt()) {
5886 return klass->GetImt(pointer_size);
5887 }
5888 }
5889 return nullptr;
5890}
5891
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005892bool ClassLinker::LinkClass(Thread* self,
5893 const char* descriptor,
5894 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005895 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005896 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005897 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005898
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005899 if (!LinkSuperClass(klass)) {
5900 return false;
5901 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005902 ArtMethod* imt_data[ImTable::kSize];
5903 // If there are any new conflicts compared to super class.
5904 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005905 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005906 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005907 return false;
5908 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005909 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005910 return false;
5911 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005912 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005913 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005914 return false;
5915 }
5916 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005917 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005918
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005919 ImTable* imt = nullptr;
5920 if (klass->ShouldHaveImt()) {
5921 // If there are any new conflicts compared to the super class we can not make a copy. There
5922 // can be cases where both will have a conflict method at the same slot without having the same
5923 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5924 // will possibly create a table that is incorrect for either of the classes.
5925 // Same IMT with new_conflict does not happen very often.
5926 if (!new_conflict) {
5927 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5928 if (super_imt != nullptr) {
5929 bool imt_equals = true;
5930 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5931 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5932 }
5933 if (imt_equals) {
5934 imt = super_imt;
5935 }
5936 }
5937 }
5938 if (imt == nullptr) {
5939 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5940 imt = reinterpret_cast<ImTable*>(
5941 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5942 if (imt == nullptr) {
5943 return false;
5944 }
5945 imt->Populate(imt_data, image_pointer_size_);
5946 }
5947 }
5948
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005949 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5950 // We don't need to retire this class as it has no embedded tables or it was created the
5951 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005952 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005953
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005954 if (klass->ShouldHaveEmbeddedVTable()) {
5955 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005956 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005957 if (klass->ShouldHaveImt()) {
5958 klass->SetImt(imt, image_pointer_size_);
5959 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005960
5961 // Update CHA info based on whether we override methods.
5962 // Have to do this before setting the class as resolved which allows
5963 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005964 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005965 cha_->UpdateAfterLoadingOf(klass);
5966 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005967
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005968 // This will notify waiters on klass that saw the not yet resolved
5969 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005970 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005971 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005972 } else {
5973 CHECK(!klass->IsResolved());
5974 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005975 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01005976 Handle<mirror::Class> h_new_class =
5977 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005978 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5979 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5980 // may not see any references to the target space and clean the card for a class if another
5981 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005982 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005983 klass->SetSFieldsPtrUnchecked(nullptr);
5984 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005985 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005986 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005987 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005988 return false;
5989 }
5990
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005991 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5992 ObjectLock<mirror::Class> lock(self, h_new_class);
5993 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005994
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005995 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005996 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005997 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005998 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005999 const ObjPtr<mirror::Class> existing =
6000 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006001 if (class_loader != nullptr) {
6002 // We updated the class in the class table, perform the write barrier so that the GC knows
6003 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006004 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006005 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006006 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006007 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006008 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6009 }
6010 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006011
Mingyao Yang063fc772016-08-02 11:02:54 -07006012 // Update CHA info based on whether we override methods.
6013 // Have to do this before setting the class as resolved which allows
6014 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006015 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006016 cha_->UpdateAfterLoadingOf(h_new_class);
6017 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006018
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006019 // This will notify waiters on temp class that saw the not yet resolved class in the
6020 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006021 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006022
Vladimir Marko2c64a832018-01-04 11:31:56 +00006023 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006024 // This will notify waiters on new_class that saw the not yet resolved
6025 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006026 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006027 // Return the new class.
6028 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006029 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006030 return true;
6031}
6032
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006033bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006034 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006035 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006036 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6037 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006038 // Check that a class does not inherit from itself directly.
6039 //
6040 // TODO: This is a cheap check to detect the straightforward case
6041 // of a class extending itself (b/28685551), but we should do a
6042 // proper cycle detection on loaded classes, to detect all cases
6043 // of class circularity errors (b/28830038).
6044 if (super_class_idx == class_def.class_idx_) {
6045 ThrowClassCircularityError(klass.Get(),
6046 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006047 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006048 return false;
6049 }
6050
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006051 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006052 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006053 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006054 return false;
6055 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006056 // Verify
6057 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006058 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006059 super_class->PrettyDescriptor().c_str(),
6060 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006061 return false;
6062 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006063 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006064 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006065 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006066 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006067 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006068 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006069 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006070 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006071 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006072 DCHECK(Thread::Current()->IsExceptionPending());
6073 return false;
6074 }
6075 // Verify
6076 if (!klass->CanAccess(interface)) {
6077 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006078 ThrowIllegalAccessError(klass.Get(),
6079 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006080 interface->PrettyDescriptor().c_str(),
6081 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006082 return false;
6083 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006084 }
6085 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006086 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006087 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006088 return true;
6089}
6090
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006091bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006092 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006093 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006094 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6095 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006096 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006097 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006098 return false;
6099 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006100 return true;
6101 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006102 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006103 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006104 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006105 return false;
6106 }
6107 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006108 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006109 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6110 return false;
6111 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006112 if (super->IsFinal()) {
6113 ThrowVerifyError(klass.Get(),
6114 "Superclass %s of %s is declared final",
6115 super->PrettyDescriptor().c_str(),
6116 klass->PrettyDescriptor().c_str());
6117 return false;
6118 }
6119 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006120 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006121 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006122 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006123 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006124 return false;
6125 }
6126 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006127 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006128 super->PrettyDescriptor().c_str(),
6129 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006130 return false;
6131 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006132
Brian Carlstromf3632832014-05-20 15:36:53 -07006133 // Inherit kAccClassIsFinalizable from the superclass in case this
6134 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006135 if (super->IsFinalizable()) {
6136 klass->SetFinalizable();
6137 }
6138
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006139 // Inherit class loader flag form super class.
6140 if (super->IsClassLoaderClass()) {
6141 klass->SetClassLoaderClass();
6142 }
6143
Elliott Hughes2da50362011-10-10 16:57:08 -07006144 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006145 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006146 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006147 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006148 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006149 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006150 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006151 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006152 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006153 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006154 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006155 return false;
6156 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006157
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006158 if (kIsDebugBuild) {
6159 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006160 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006161 CHECK(super->IsResolved());
6162 super = super->GetSuperClass();
6163 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006164 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006165 return true;
6166}
6167
Vladimir Marko782fb712020-12-23 12:47:31 +00006168// A wrapper class representing the result of a method translation used for linking methods and
6169// updating superclass default methods. For each method in a classes vtable there are 4 states it
6170// could be in:
6171// 1) No translation is necessary. In this case there is no MethodTranslation object for it. This
6172// is the standard case and is true when the method is not overridable by a default method,
6173// the class defines a concrete implementation of the method, the default method implementation
6174// remains the same, or an abstract method stayed abstract.
6175// 2) The method must be translated to a different default method. We note this with
6176// CreateTranslatedMethod.
6177// 3) The method must be replaced with a conflict method. This happens when a superclass
6178// implements an interface with a default method and this class implements an unrelated
6179// interface that also defines that default method. We note this with CreateConflictingMethod.
6180// 4) The method must be replaced with an abstract miranda method. This happens when a superclass
6181// implements an interface with a default method and this class implements a subinterface of
6182// the superclass's interface which declares the default method abstract. We note this with
6183// CreateAbstractMethod.
6184//
6185// When a method translation is unnecessary (case #1), we don't put it into the
6186// default_translation maps. So an instance of MethodTranslation must be in one of #2-#4.
6187class ClassLinker::MethodTranslation {
6188 public:
6189 MethodTranslation() : translation_(nullptr), type_(Type::kInvalid) {}
6190
6191 // This slot must become a default conflict method.
6192 static MethodTranslation CreateConflictingMethod() {
6193 return MethodTranslation(Type::kConflict, /*translation=*/nullptr);
6194 }
6195
6196 // This slot must become an abstract method.
6197 static MethodTranslation CreateAbstractMethod() {
6198 return MethodTranslation(Type::kAbstract, /*translation=*/nullptr);
6199 }
6200
6201 // Use the given method as the current value for this vtable slot during translation.
6202 static MethodTranslation CreateTranslatedMethod(ArtMethod* new_method) {
6203 return MethodTranslation(Type::kTranslation, new_method);
6204 }
6205
6206 // Returns true if this is a method that must become a conflict method.
6207 bool IsInConflict() const {
6208 return type_ == Type::kConflict;
6209 }
6210
6211 // Returns true if this is a method that must become an abstract method.
6212 bool IsAbstract() const {
6213 return type_ == Type::kAbstract;
6214 }
6215
6216 // Returns true if this is a method that must become a different method.
6217 bool IsTranslation() const {
6218 return type_ == Type::kTranslation;
6219 }
6220
6221 // Get the translated version of this method.
6222 ArtMethod* GetTranslation() const {
6223 DCHECK(IsTranslation());
6224 DCHECK(translation_ != nullptr);
6225 return translation_;
6226 }
6227
6228 private:
6229 enum class Type {
6230 kInvalid,
6231 kTranslation,
6232 kConflict,
6233 kAbstract,
6234 };
6235
6236 MethodTranslation(Type type, ArtMethod* translation)
6237 : translation_(translation), type_(type) {}
6238
6239 ArtMethod* translation_;
6240 Type type_;
6241};
6242
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006243// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006244bool ClassLinker::LinkMethods(Thread* self,
6245 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006246 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006247 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006248 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006249 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006250 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6251 // need to have default methods be in the virtuals array of each class but we don't set that up
6252 // until LinkInterfaceMethods.
Vladimir Marko782fb712020-12-23 12:47:31 +00006253 constexpr size_t kBufferSize = 8; // Avoid malloc/free for a few translations.
6254 std::pair<size_t, ClassLinker::MethodTranslation> buffer[kBufferSize];
6255 HashMap<size_t, ClassLinker::MethodTranslation> default_translations(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07006256 // Link virtual methods then interface methods.
6257 // We set up the interface lookup table first because we need it to determine if we need to update
6258 // any vtable entries with new default method implementations.
6259 return SetupInterfaceLookupTable(self, klass, interfaces)
6260 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006261 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006262}
6263
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006264// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6265// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6266// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006267class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006268 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006269 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006270 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006271 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006272 name_view_() {
David Sehr709b0702016-10-13 09:12:37 -07006273 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006274 }
6275
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006276 ALWAYS_INLINE std::string_view GetNameView() {
6277 if (name_view_.empty()) {
6278 name_view_ = dex_file_->StringViewByIdx(mid_->name_idx_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006279 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006280 return name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006281 }
6282
Mathieu Chartiere401d142015-04-22 13:56:20 -07006283 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006284 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006285 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006286 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006287 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006288 if (dex_file_ == other_dex_file) {
6289 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6290 }
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006291 return GetNameView() == other_dex_file->StringViewByIdx(other_mid.name_idx_) &&
6292 dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006293 }
6294
6295 private:
6296 // Dex file for the method to compare against.
6297 const DexFile* const dex_file_;
6298 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006299 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006300 // Lazily computed name from the dex file's strings.
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006301 std::string_view name_view_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006302};
6303
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006304class LinkVirtualHashTable {
6305 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006306 LinkVirtualHashTable(Handle<mirror::Class> klass,
6307 size_t hash_size,
6308 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006309 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006310 : klass_(klass),
6311 hash_size_(hash_size),
6312 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006313 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006314 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6315 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006316
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006317 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006318 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6319 virtual_method_index, image_pointer_size_);
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006320 std::string_view name_view =
6321 local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetNameView();
6322 uint32_t hash = ComputeModifiedUtf8Hash(name_view);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006323 uint32_t index = hash % hash_size_;
6324 // Linear probe until we have an empty slot.
6325 while (hash_table_[index] != invalid_index_) {
6326 if (++index == hash_size_) {
6327 index = 0;
6328 }
6329 }
6330 hash_table_[index] = virtual_method_index;
6331 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006332
Vladimir Marko43354742021-02-03 15:37:01 +00006333 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator, uint32_t hash)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006334 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006335 DCHECK_EQ(hash, ComputeModifiedUtf8Hash(comparator->GetNameView()));
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006336 size_t index = hash % hash_size_;
6337 while (true) {
6338 const uint32_t value = hash_table_[index];
6339 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6340 // the block and can safely assume not found.
6341 if (value == invalid_index_) {
6342 break;
6343 }
6344 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006345 ArtMethod* virtual_method =
6346 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6347 if (comparator->HasSameNameAndSignature(
6348 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006349 hash_table_[index] = removed_index_;
6350 return value;
6351 }
6352 }
6353 if (++index == hash_size_) {
6354 index = 0;
6355 }
6356 }
6357 return GetNotFoundIndex();
6358 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006359
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006360 static uint32_t GetNotFoundIndex() {
6361 return invalid_index_;
6362 }
6363
6364 private:
6365 static const uint32_t invalid_index_;
6366 static const uint32_t removed_index_;
6367
6368 Handle<mirror::Class> klass_;
6369 const size_t hash_size_;
6370 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006371 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006372};
6373
6374const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6375const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6376
Stephen Hines1ddd9132017-02-08 01:51:18 -08006377bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006378 Thread* self,
6379 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00006380 /*out*/HashMap<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006381 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006382 if (klass->IsInterface()) {
6383 // No vtable.
6384 if (!IsUint<16>(num_virtual_methods)) {
6385 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6386 return false;
6387 }
6388 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006389 // Assign each method an IMT index and set the default flag.
6390 for (size_t i = 0; i < num_virtual_methods; ++i) {
6391 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6392 m->SetMethodIndex(i);
6393 if (!m->IsAbstract()) {
Vladimir Marko1c993cd2020-05-28 09:30:06 +00006394 // If the dex file does not support default methods, throw ClassFormatError.
6395 // This check is necessary to protect from odd cases, such as native default
6396 // methods, that the dex file verifier permits for old dex file versions. b/157170505
6397 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
6398 // currently running CTS tests for default methods with dex file version 035 which
6399 // does not support default methods. So, we limit this to native methods. b/157718952
6400 if (m->IsNative()) {
6401 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
6402 ThrowClassFormatError(klass.Get(),
6403 "Dex file does not support default method '%s'",
6404 m->PrettyMethod().c_str());
6405 return false;
6406 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006407 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6408 has_defaults = true;
6409 }
6410 }
6411 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6412 // during initialization. This is a performance optimization. We could simply traverse the
6413 // virtual_methods_ array again during initialization.
6414 if (has_defaults) {
6415 klass->SetHasDefaultMethods();
6416 }
6417 return true;
6418 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006419 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6420 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006421 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006422 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006423 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006424 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006425 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006426 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006427 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006428 return false;
6429 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006430 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006431 vtable->SetElementPtrSize(
6432 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006433 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006434 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6435 // might give us new default methods). If no new interfaces then we can skip the rest since
6436 // the class cannot override any of the super-class's methods. This is required for
6437 // correctness since without it we might not update overridden default method vtable entries
6438 // correctly.
6439 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006440 klass->SetVTable(vtable.Get());
6441 return true;
6442 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006443 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006444 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006445 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006446 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006447 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6448 // might give us new default methods). See comment above.
6449 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006450 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006451 return true;
6452 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006453 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6454 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006455 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006456 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006457 return false;
6458 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006459 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006460 // How the algorithm works:
6461 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6462 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6463 // method which has not been matched to a vtable method, and j if the virtual method at the
6464 // index overrode the super virtual method at index j.
6465 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6466 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6467 // the need for the initial vtable which we later shrink back down).
6468 // 3. Add non overridden methods to the end of the vtable.
6469 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006470 // + 1 so that even if we only have new default methods we will still be able to use this hash
6471 // table (i.e. it will never have 0 size).
6472 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006473 uint32_t* hash_table_ptr;
6474 std::unique_ptr<uint32_t[]> hash_heap_storage;
6475 if (hash_table_size <= kMaxStackHash) {
6476 hash_table_ptr = reinterpret_cast<uint32_t*>(
6477 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6478 } else {
6479 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6480 hash_table_ptr = hash_heap_storage.get();
6481 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006482 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006483 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006484 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006485 DCHECK(klass->GetVirtualMethodDuringLinking(
6486 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006487 hash_table.Add(i);
6488 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006489 // Loop through each super vtable method and see if they are overridden by a method we added to
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006490 // the hash table.
6491 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006492 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006493 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006494 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6495 super_method->GetAccessFlags())) {
6496 // Continue on to the next method since this one is package private and canot be overridden.
6497 // Before Android 4.1, the package-private method super_method might have been incorrectly
6498 // overridden.
6499 continue;
6500 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006501 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006502 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006503 // We remove the method so that subsequent lookups will be faster by making the hash-map
6504 // smaller as we go on.
Vladimir Marko43354742021-02-03 15:37:01 +00006505 uint32_t hash = (j < mirror::Object::kVTableLength)
6506 ? object_virtual_method_hashes_[j]
Vladimir Markob4bd92f2021-07-05 12:18:26 +01006507 : ComputeModifiedUtf8Hash(super_method_name_comparator.GetNameView());
Vladimir Marko43354742021-02-03 15:37:01 +00006508 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator, hash);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006509 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006510 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6511 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006512 if (super_method->IsFinal()) {
6513 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6514 virtual_method->PrettyMethod().c_str(),
6515 super_method->GetDeclaringClassDescriptor());
6516 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006517 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006518 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6519 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006520 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006521 // We didn't directly override this method but we might through default methods...
6522 // Check for default method update.
6523 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006524 switch (FindDefaultMethodImplementation(self,
6525 super_method,
6526 klass,
6527 /*out*/&default_method)) {
6528 case DefaultMethodSearchResult::kDefaultConflict: {
6529 // A conflict was found looking for default methods. Note this (assuming it wasn't
6530 // pre-existing) in the translations map.
6531 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6532 // Don't generate another conflict method to reduce memory use as an optimization.
6533 default_translations->insert(
6534 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6535 }
6536 break;
6537 }
6538 case DefaultMethodSearchResult::kAbstractFound: {
6539 // No conflict but method is abstract.
6540 // We note that this vtable entry must be made abstract.
6541 if (UNLIKELY(!super_method->IsAbstract())) {
6542 default_translations->insert(
6543 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6544 }
6545 break;
6546 }
6547 case DefaultMethodSearchResult::kDefaultFound: {
6548 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6549 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6550 // Found a default method implementation that is new.
6551 // TODO Refactor this add default methods to virtuals here and not in
6552 // LinkInterfaceMethods maybe.
6553 // The problem is default methods might override previously present
6554 // default-method or miranda-method vtable entries from the superclass.
6555 // Unfortunately we need these to be entries in this class's virtuals. We do not
6556 // give these entries there until LinkInterfaceMethods so we pass this map around
6557 // to let it know which vtable entries need to be updated.
6558 // Make a note that vtable entry j must be updated, store what it needs to be updated
6559 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6560 // then.
6561 default_translations->insert(
6562 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006563 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6564 << " overridden by default "
6565 << default_method->PrettyMethod()
6566 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006567 }
6568 break;
6569 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006570 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006571 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006572 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006573 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006574 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006575 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006576 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006577 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6578 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006579 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006580 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006581 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006582 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006583 local_method->SetMethodIndex(actual_count);
6584 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006585 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006586 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006587 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006588 return false;
6589 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006590 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006591 CHECK_LE(actual_count, max_count);
6592 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006593 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6594 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006595 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006596 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006597 return false;
6598 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006599 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006600 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006601 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006602 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006603 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006604 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6605 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006606 return false;
6607 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006608 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006609 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006610 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006611 return false;
6612 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006613 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006614 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6615 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006616 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006617 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006618 klass->SetVTable(vtable);
Vladimir Marko43354742021-02-03 15:37:01 +00006619 InitializeObjectVirtualMethodHashes(klass.Get(),
6620 image_pointer_size_,
6621 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006622 }
6623 return true;
6624}
6625
Alex Light9139e002015-10-09 15:59:48 -07006626// Determine if the given iface has any subinterface in the given list that declares the method
6627// specified by 'target'.
6628//
6629// Arguments
6630// - self: The thread we are running on
6631// - target: A comparator that will match any method that overrides the method we are checking for
6632// - iftable: The iftable we are searching for an overriding method on.
6633// - ifstart: The index of the interface we are checking to see if anything overrides
6634// - iface: The interface we are checking to see if anything overrides.
6635// - image_pointer_size:
6636// The image pointer size.
6637//
6638// Returns
6639// - True: There is some method that matches the target comparator defined in an interface that
6640// is a subtype of iface.
6641// - False: There is no method that matches the target comparator in any interface that is a subtype
6642// of iface.
6643static bool ContainsOverridingMethodOf(Thread* self,
6644 MethodNameAndSignatureComparator& target,
6645 Handle<mirror::IfTable> iftable,
6646 size_t ifstart,
6647 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006648 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006649 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006650 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006651 DCHECK(iface != nullptr);
6652 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006653 DCHECK_GE(ifstart, 0u);
6654 DCHECK_LT(ifstart, iftable->Count());
6655 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6656 DCHECK(iface->IsInterface());
6657
6658 size_t iftable_count = iftable->Count();
6659 StackHandleScope<1> hs(self);
6660 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6661 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6662 // Skip ifstart since our current interface obviously cannot override itself.
6663 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006664 // Iterate through every method on this interface. The order does not matter.
6665 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006666 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006667 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006668 // Check if the i'th interface is a subtype of this one.
6669 if (iface->IsAssignableFrom(current_iface.Get())) {
6670 return true;
6671 }
6672 break;
6673 }
6674 }
6675 }
6676 return false;
6677}
6678
Alex Lighteb7c1442015-08-31 13:17:42 -07006679// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006680// out_default_method and returns kDefaultFound on success. If no default method was found return
6681// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6682// default_method conflict) it will return kDefaultConflict.
6683ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6684 Thread* self,
6685 ArtMethod* target_method,
6686 Handle<mirror::Class> klass,
6687 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006688 DCHECK(self != nullptr);
6689 DCHECK(target_method != nullptr);
6690 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006691
6692 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006693
6694 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6695 // table. This lets us walk the table backwards when searching for default methods. The first one
6696 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6697 // track of it and then continue checking all other interfaces, since we need to throw an error if
6698 // we encounter conflicting default method implementations (one is not a subtype of the other).
6699 //
6700 // The order of unrelated interfaces does not matter and is not defined.
6701 size_t iftable_count = klass->GetIfTableCount();
6702 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006703 // No interfaces. We have already reset out to null so just return kAbstractFound.
6704 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006705 }
6706
Alex Light9139e002015-10-09 15:59:48 -07006707 StackHandleScope<3> hs(self);
6708 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006709 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006710 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006711 MethodNameAndSignatureComparator target_name_comparator(
6712 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6713 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006714 for (size_t k = iftable_count; k != 0; ) {
6715 --k;
6716
Alex Lighteb7c1442015-08-31 13:17:42 -07006717 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006718
6719 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006720 // Iterate through every declared method on this interface. The order does not matter.
6721 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6722 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006723 // Skip abstract methods and methods with different names.
6724 if (current_method->IsAbstract() ||
6725 !target_name_comparator.HasSameNameAndSignature(
6726 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6727 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006728 } else if (!current_method->IsPublic()) {
6729 // The verifier should have caught the non-public method for dex version 37. Just warn and
6730 // skip it since this is from before default-methods so we don't really need to care that it
6731 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006732 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6733 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006734 << "This will be a fatal error in subsequent versions of android. "
6735 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006736 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006737 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006738 // We have multiple default impls of the same method. This is a potential default conflict.
6739 // We need to check if this possibly conflicting method is either a superclass of the chosen
6740 // default implementation or is overridden by a non-default interface method. In either case
6741 // there is no conflict.
6742 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6743 !ContainsOverridingMethodOf(self,
6744 target_name_comparator,
6745 iftable,
6746 k,
6747 iface,
6748 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006749 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006750 << current_method->PrettyMethod() << " and "
6751 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6752 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006753 *out_default_method = nullptr;
6754 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006755 } else {
6756 break; // Continue checking at the next interface.
6757 }
6758 } else {
Alex Light9139e002015-10-09 15:59:48 -07006759 // chosen_iface == null
6760 if (!ContainsOverridingMethodOf(self,
6761 target_name_comparator,
6762 iftable,
6763 k,
6764 iface,
6765 image_pointer_size_)) {
6766 // Don't set this as the chosen interface if something else is overriding it (because that
6767 // other interface would be potentially chosen instead if it was default). If the other
6768 // interface was abstract then we wouldn't select this interface as chosen anyway since
6769 // the abstract method masks it.
6770 *out_default_method = current_method;
6771 chosen_iface.Assign(iface.Get());
6772 // We should now finish traversing the graph to find if we have default methods that
6773 // conflict.
6774 } else {
David Sehr709b0702016-10-13 09:12:37 -07006775 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6776 << "' was "
6777 << "skipped because it was overridden by an abstract method in a "
6778 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006779 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006780 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006781 break;
6782 }
6783 }
Alex Light9139e002015-10-09 15:59:48 -07006784 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006785 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6786 << "' selected "
6787 << "as the implementation for '" << target_method->PrettyMethod()
6788 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006789 return DefaultMethodSearchResult::kDefaultFound;
6790 } else {
6791 return DefaultMethodSearchResult::kAbstractFound;
6792 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006793}
6794
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006795ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006796 ArtMethod* conflict_method,
6797 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006798 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006799 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006800 Runtime* const runtime = Runtime::Current();
6801 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006802
6803 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006804 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006805 ? runtime->CreateImtConflictMethod(linear_alloc)
6806 : conflict_method;
6807
6808 // Allocate a new table. Note that we will leak this table at the next conflict,
6809 // but that's a tradeoff compared to making the table fixed size.
6810 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006811 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6812 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006813 if (data == nullptr) {
6814 LOG(ERROR) << "Failed to allocate conflict table";
6815 return conflict_method;
6816 }
6817 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6818 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006819 method,
6820 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006821
6822 // Do a fence to ensure threads see the data in the table before it is assigned
6823 // to the conflict method.
6824 // Note that there is a race in the presence of multiple threads and we may leak
6825 // memory from the LinearAlloc, but that's a tradeoff compared to using
6826 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006827 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006828 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006829 return new_conflict_method;
6830}
6831
Vladimir Marko921094a2017-01-12 18:37:06 +00006832bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6833 Handle<mirror::Class> klass,
6834 Handle<mirror::IfTable> iftable) {
6835 DCHECK(!klass->IsInterface());
6836 const bool has_superclass = klass->HasSuperClass();
6837 const bool extend_super_iftable = has_superclass;
6838 const size_t ifcount = klass->GetIfTableCount();
6839 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6840 for (size_t i = 0; i < ifcount; ++i) {
6841 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6842 if (num_methods > 0) {
6843 const bool is_super = i < super_ifcount;
6844 // This is an interface implemented by a super-class. Therefore we can just copy the method
6845 // array from the superclass.
6846 const bool super_interface = is_super && extend_super_iftable;
6847 ObjPtr<mirror::PointerArray> method_array;
6848 if (super_interface) {
6849 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6850 DCHECK(if_table != nullptr);
6851 DCHECK(if_table->GetMethodArray(i) != nullptr);
6852 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006853 StackHandleScope<1u> hs(self);
6854 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6855 method_array =
6856 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006857 } else {
6858 method_array = AllocPointerArray(self, num_methods);
6859 }
6860 if (UNLIKELY(method_array == nullptr)) {
6861 self->AssertPendingOOMException();
6862 return false;
6863 }
6864 iftable->SetMethodArray(i, method_array);
6865 }
6866 }
6867 return true;
6868}
6869
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006870void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6871 ArtMethod* imt_conflict_method,
6872 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006873 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006874 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006875 // Place method in imt if entry is empty, place conflict otherwise.
6876 if (*imt_ref == unimplemented_method) {
6877 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006878 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006879 // If we are not a conflict and we have the same signature and name as the imt
6880 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006881 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6882 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006883 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006884 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006885 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006886 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006887 *imt_ref = current_method;
6888 } else {
Alex Light9139e002015-10-09 15:59:48 -07006889 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006890 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006891 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006892 } else {
6893 // Place the default conflict method. Note that there may be an existing conflict
6894 // method in the IMT, but it could be one tailored to the super class, with a
6895 // specific ImtConflictTable.
6896 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006897 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006898 }
6899}
6900
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006901void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006902 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6903 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006904 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006905 Runtime* const runtime = Runtime::Current();
6906 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6907 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006908 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006909 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006910 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006911 FillIMTFromIfTable(klass->GetIfTable(),
6912 unimplemented_method,
6913 conflict_method,
6914 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006915 /*create_conflict_tables=*/true,
6916 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006917 &new_conflict,
6918 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006919 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006920 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6921 // we can just use the same pointer.
6922 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006923 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006924 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6925 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6926 bool same = true;
6927 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6928 ArtMethod* method = imt_data[i];
6929 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6930 if (method != super_method) {
6931 bool is_conflict_table = method->IsRuntimeMethod() &&
6932 method != unimplemented_method &&
6933 method != conflict_method;
6934 // Verify conflict contents.
6935 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6936 super_method != unimplemented_method &&
6937 super_method != conflict_method;
6938 if (!is_conflict_table || !super_conflict_table) {
6939 same = false;
6940 } else {
6941 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6942 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6943 same = same && table1->Equals(table2, image_pointer_size_);
6944 }
6945 }
6946 }
6947 if (same) {
6948 imt = super_imt;
6949 }
6950 }
6951 if (imt == nullptr) {
6952 imt = klass->GetImt(image_pointer_size_);
6953 DCHECK(imt != nullptr);
6954 imt->Populate(imt_data, image_pointer_size_);
6955 } else {
6956 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006957 }
6958}
6959
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006960ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6961 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006962 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006963 void* data = linear_alloc->Alloc(Thread::Current(),
6964 ImtConflictTable::ComputeSize(count,
6965 image_pointer_size));
6966 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6967}
6968
6969ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6970 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6971}
6972
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006973void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006974 ArtMethod* unimplemented_method,
6975 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006976 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006977 bool create_conflict_tables,
6978 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006979 /*out*/bool* new_conflict,
6980 /*out*/ArtMethod** imt) {
6981 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006982 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006983 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006984 const size_t num_virtuals = interface->NumVirtualMethods();
6985 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6986 // Virtual methods can be larger than the if table methods if there are default methods.
6987 DCHECK_GE(num_virtuals, method_array_count);
6988 if (kIsDebugBuild) {
6989 if (klass->IsInterface()) {
6990 DCHECK_EQ(method_array_count, 0u);
6991 } else {
6992 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6993 }
6994 }
6995 if (method_array_count == 0) {
6996 continue;
6997 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006998 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006999 for (size_t j = 0; j < method_array_count; ++j) {
7000 ArtMethod* implementation_method =
7001 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7002 if (ignore_copied_methods && implementation_method->IsCopied()) {
7003 continue;
7004 }
7005 DCHECK(implementation_method != nullptr);
7006 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7007 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7008 // or interface methods in the IMT here they will not create extra conflicts since we compare
7009 // names and signatures in SetIMTRef.
7010 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007011 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007012
7013 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7014 // the same implementation method, keep track of this to avoid creating a conflict table in
7015 // this case.
7016
7017 // Conflict table size for each IMT slot.
7018 ++conflict_counts[imt_index];
7019
7020 SetIMTRef(unimplemented_method,
7021 imt_conflict_method,
7022 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007023 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007024 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007025 }
7026 }
7027
7028 if (create_conflict_tables) {
7029 // Create the conflict tables.
7030 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007031 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007032 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007033 if (imt[i] == imt_conflict_method) {
7034 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7035 if (new_table != nullptr) {
7036 ArtMethod* new_conflict_method =
7037 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7038 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7039 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007040 } else {
7041 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007042 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007043 }
7044 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007045 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007046 }
7047 }
7048
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007049 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007050 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007051 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7052 // Virtual methods can be larger than the if table methods if there are default methods.
7053 if (method_array_count == 0) {
7054 continue;
7055 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007056 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007057 for (size_t j = 0; j < method_array_count; ++j) {
7058 ArtMethod* implementation_method =
7059 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7060 if (ignore_copied_methods && implementation_method->IsCopied()) {
7061 continue;
7062 }
7063 DCHECK(implementation_method != nullptr);
7064 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007065 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007066 if (!imt[imt_index]->IsRuntimeMethod() ||
7067 imt[imt_index] == unimplemented_method ||
7068 imt[imt_index] == imt_conflict_method) {
7069 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007070 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007071 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7072 const size_t num_entries = table->NumEntries(image_pointer_size_);
7073 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7074 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007075 }
7076 }
7077 }
7078}
7079
Alex Lighteb7c1442015-08-31 13:17:42 -07007080// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7081// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007082static bool NotSubinterfaceOfAny(
Vladimir Marko782fb712020-12-23 12:47:31 +00007083 const HashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007084 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007085 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007086 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007087 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007088 for (ObjPtr<mirror::Class> c : classes) {
7089 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007090 return false;
7091 }
7092 }
7093 return true;
7094}
7095
7096// Fills in and flattens the interface inheritance hierarchy.
7097//
7098// By the end of this function all interfaces in the transitive closure of to_process are added to
7099// the iftable and every interface precedes all of its sub-interfaces in this list.
7100//
7101// all I, J: Interface | I <: J implies J precedes I
7102//
7103// (note A <: B means that A is a subtype of B)
7104//
7105// This returns the total number of items in the iftable. The iftable might be resized down after
7106// this call.
7107//
7108// We order this backwards so that we do not need to reorder superclass interfaces when new
7109// interfaces are added in subclass's interface tables.
7110//
7111// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7112// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7113// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7114// iftable must be large enough to hold all interfaces without changing its size.
Vladimir Markob10668c2021-06-10 09:52:53 +01007115static size_t FillIfTable(ObjPtr<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00007116 ObjPtr<mirror::ObjectArray<mirror::Class>> interfaces,
7117 ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007118 size_t super_ifcount,
Vladimir Marko782fb712020-12-23 12:47:31 +00007119 size_t num_interfaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007120 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00007121 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
7122 // This is the set of all classes already in the iftable. Used to make checking
7123 // if a class has already been added quicker.
7124 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
7125 mirror::Class* buffer[kBufferSize];
7126 HashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07007127 // The first super_ifcount elements are from the superclass. We note that they are already added.
7128 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007129 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007130 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007131 classes_in_iftable.insert(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007132 }
7133 size_t filled_ifcount = super_ifcount;
Vladimir Marko782fb712020-12-23 12:47:31 +00007134 const bool have_interfaces = interfaces != nullptr;
7135 for (size_t i = 0; i != num_interfaces; ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +01007136 ObjPtr<mirror::Class> interface =
7137 have_interfaces ? interfaces->Get(i) : klass->GetDirectInterface(i);
Vladimir Marko782fb712020-12-23 12:47:31 +00007138
Alex Lighteb7c1442015-08-31 13:17:42 -07007139 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7140 // At this point in the loop current-iface-list has the invariant that:
7141 // for every pair of interfaces I,J within it:
7142 // if index_of(I) < index_of(J) then I is not a subtype of J
7143
7144 // If we have already seen this element then all of its super-interfaces must already be in the
7145 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00007146 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007147 // We haven't seen this interface so add all of its super-interfaces onto the
7148 // current-iface-list, skipping those already on it.
7149 int32_t ifcount = interface->GetIfTableCount();
7150 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007151 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007152 if (!ContainsElement(classes_in_iftable, super_interface)) {
7153 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007154 classes_in_iftable.insert(super_interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007155 iftable->SetInterface(filled_ifcount, super_interface);
7156 filled_ifcount++;
7157 }
7158 }
7159 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7160 // Place this interface onto the current-iface-list after all of its super-interfaces.
Vladimir Marko782fb712020-12-23 12:47:31 +00007161 classes_in_iftable.insert(interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007162 iftable->SetInterface(filled_ifcount, interface);
7163 filled_ifcount++;
7164 } else if (kIsDebugBuild) {
7165 // Check all super-interfaces are already in the list.
7166 int32_t ifcount = interface->GetIfTableCount();
7167 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007168 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007169 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007170 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7171 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007172 }
7173 }
7174 }
7175 if (kIsDebugBuild) {
7176 // Check that the iftable is ordered correctly.
7177 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007178 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007179 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007180 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007181 // !(if_a <: if_b)
7182 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007183 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7184 << ") extends "
7185 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007186 << "interface list.";
7187 }
7188 }
7189 }
7190 return filled_ifcount;
7191}
7192
Vladimir Marko782fb712020-12-23 12:47:31 +00007193bool ClassLinker::SetupInterfaceLookupTable(Thread* self,
7194 Handle<mirror::Class> klass,
Alex Lighteb7c1442015-08-31 13:17:42 -07007195 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7196 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007197 const bool has_superclass = klass->HasSuperClass();
7198 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007199 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007200 const size_t num_interfaces =
7201 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007202 if (num_interfaces == 0) {
7203 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007204 if (LIKELY(has_superclass)) {
7205 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7206 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007207 // Class implements no interfaces.
7208 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007209 return true;
7210 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007211 // Class implements same interfaces as parent, are any of these not marker interfaces?
7212 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007213 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007214 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007215 if (super_iftable->GetMethodArrayCount(i) > 0) {
7216 has_non_marker_interface = true;
7217 break;
7218 }
7219 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007220 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007221 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007222 klass->SetIfTable(super_iftable);
7223 return true;
7224 }
7225 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007226 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007227 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007228 for (size_t i = 0; i < num_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01007229 ObjPtr<mirror::Class> interface =
7230 have_interfaces ? interfaces->GetWithoutChecks(i) : klass->GetDirectInterface(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007231 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007232 if (UNLIKELY(!interface->IsInterface())) {
7233 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007234 ThrowIncompatibleClassChangeError(klass.Get(),
7235 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007236 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007237 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7238 return false;
7239 }
7240 ifcount += interface->GetIfTableCount();
7241 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007242 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007243 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007244 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007245 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007246 return false;
7247 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007248 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007249 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007250 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007251 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007252 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007253 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007254 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007255 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007256
7257 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7258 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7259 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007260 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007261
Vladimir Markob10668c2021-06-10 09:52:53 +01007262 const size_t new_ifcount =
7263 FillIfTable(klass.Get(), interfaces.Get(), iftable.Get(), super_ifcount, num_interfaces);
Alex Lighteb7c1442015-08-31 13:17:42 -07007264
Ian Rogers7b078e82014-09-10 14:44:24 -07007265 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007266
Ian Rogersb52b01a2012-01-12 17:01:38 -08007267 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007268 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007269 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007270 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007271 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007272 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007273 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007274 return false;
7275 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007276 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007277 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007278 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007279 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007280 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007281 return true;
7282}
7283
Alex Light1f3925d2016-09-07 12:04:20 -07007284// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7285// of methods must be unique.
7286static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7287 return nullptr;
7288}
7289
7290template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007291static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007292 const ScopedArenaVector<ArtMethod*>& list,
7293 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007294 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007295 for (ArtMethod* method : list) {
7296 if (cmp.HasSameNameAndSignature(method)) {
7297 return method;
7298 }
7299 }
Alex Light1f3925d2016-09-07 12:04:20 -07007300 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007301}
7302
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007303namespace {
7304
Alex Light1f3925d2016-09-07 12:04:20 -07007305// Check that all vtable entries are present in this class's virtuals or are the same as a
7306// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007307void CheckClassOwnsVTableEntries(Thread* self,
7308 Handle<mirror::Class> klass,
7309 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007310 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007311 StackHandleScope<2> hs(self);
7312 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007313 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007314 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007315 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007316 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7317 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7318 CHECK(m != nullptr);
7319
Alex Lighta41a30782017-03-29 11:33:19 -07007320 if (m->GetMethodIndexDuringLinking() != i) {
7321 LOG(WARNING) << m->PrettyMethod()
7322 << " has an unexpected method index for its spot in the vtable for class"
7323 << klass->PrettyClass();
7324 }
Alex Lighte64300b2015-12-15 15:02:47 -08007325 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7326 auto is_same_method = [m] (const ArtMethod& meth) {
7327 return &meth == m;
7328 };
Alex Light3f980532017-03-17 15:10:32 -07007329 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7330 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7331 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7332 << klass->PrettyClass() << " or any of its superclasses!";
7333 }
Alex Lighte64300b2015-12-15 15:02:47 -08007334 }
7335}
7336
Alex Light1f3925d2016-09-07 12:04:20 -07007337// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7338// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007339template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007340void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007341 REQUIRES_SHARED(Locks::mutator_lock_) {
7342 StackHandleScope<1> hs(self);
7343 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7344 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007345
7346 // Observations:
7347 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7348 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7349 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7350 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7351 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7352 // * The single-pass algorithm will trade memory for speed, but that is OK.
7353
7354 CHECK_GT(num_entries, 0);
7355
7356 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7357 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7358 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7359 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7360 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7361 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7362 << m2->PrettyMethod() << " (0x" << std::hex
7363 << reinterpret_cast<uintptr_t>(m2) << ")";
7364 };
7365 struct BaseHashType {
7366 static size_t HashCombine(size_t seed, size_t val) {
7367 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7368 }
7369 };
7370
7371 // Check assuming all entries come from the same dex file.
7372 {
7373 // Find the first interesting method and its dex file.
7374 int32_t start = 0;
7375 for (; start < num_entries; ++start) {
7376 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7377 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7378 // maybe).
7379 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7380 vtable_entry->GetAccessFlags())) {
7381 continue;
7382 }
7383 break;
7384 }
7385 if (start == num_entries) {
7386 return;
7387 }
7388 const DexFile* dex_file =
7389 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7390 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7391
7392 // Helper function to avoid logging if we have to run the cross-file checks.
7393 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7394 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7395 using PairType = std::pair<uint32_t, uint16_t>;
7396 struct PairHash : BaseHashType {
7397 size_t operator()(const PairType& key) const {
7398 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7399 }
7400 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007401 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007402 seen.reserve(2 * num_entries);
7403 bool need_slow_path = false;
7404 bool found_dup = false;
7405 for (int i = start; i < num_entries; ++i) {
7406 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7407 // wrt/ kPointerSize.
7408 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7409 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7410 vtable_entry->GetAccessFlags())) {
7411 continue;
7412 }
7413 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7414 if (dex_file != m->GetDexFile()) {
7415 need_slow_path = true;
7416 break;
7417 }
7418 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7419 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7420 auto it = seen.find(pair);
7421 if (it != seen.end()) {
7422 found_dup = true;
7423 if (log_warn) {
7424 log_fn(it->second, i);
7425 }
7426 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007427 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007428 }
7429 }
7430 return std::make_pair(need_slow_path, found_dup);
7431 };
7432 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7433 if (!result.first) {
7434 if (result.second) {
7435 check_fn(/* log_warn= */ true);
7436 }
7437 return;
7438 }
7439 }
7440
7441 // Need to check across dex files.
7442 struct Entry {
7443 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00007444 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007445 const char* name = nullptr;
7446 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007447
Vladimir Marko782fb712020-12-23 12:47:31 +00007448 Entry() = default;
7449 Entry(const Entry& other) = default;
7450 Entry& operator=(const Entry& other) = default;
7451
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007452 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00007453 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
7454 // This call writes `name_len` and it is therefore necessary that the
7455 // initializer for `name_len` comes before it, otherwise the value
7456 // from the call would be overwritten by that initializer.
7457 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007458 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00007459 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
7460 if (name[name_len] != 0) {
7461 name_len += strlen(name + name_len);
7462 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007463 }
7464
7465 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00007466 return name_len == other.name_len &&
7467 memcmp(name, other.name, name_len) == 0 &&
7468 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007469 }
7470 };
7471 struct EntryHash {
7472 size_t operator()(const Entry& key) const {
7473 return key.cached_hash;
7474 }
7475 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007476 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007477 for (int32_t i = 0; i < num_entries; ++i) {
7478 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7479 // wrt/ kPointerSize.
7480 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7481 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7482 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007483 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7484 vtable_entry->GetAccessFlags())) {
7485 continue;
7486 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007487 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7488 const DexFile* dex_file = m->GetDexFile();
7489 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7490
7491 Entry e(dex_file, mid);
7492
7493 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7494 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7495 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7496 sig_hash);
7497
7498 auto it = map.find(e);
7499 if (it != map.end()) {
7500 log_fn(it->second, i);
7501 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007502 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07007503 }
7504 }
7505}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007506
7507void CheckVTableHasNoDuplicates(Thread* self,
7508 Handle<mirror::Class> klass,
7509 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007510 REQUIRES_SHARED(Locks::mutator_lock_) {
7511 switch (pointer_size) {
7512 case PointerSize::k64:
7513 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7514 break;
7515 case PointerSize::k32:
7516 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7517 break;
7518 }
7519}
Alex Light1f3925d2016-09-07 12:04:20 -07007520
Orion Hodson5880c772020-07-28 20:12:08 +01007521static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07007522 REQUIRES_SHARED(Locks::mutator_lock_) {
7523 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7524 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7525}
7526
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007527} // namespace
7528
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007529void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7530 ArtMethod* unimplemented_method,
7531 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007532 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007533 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007534 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007535 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007536 if (super_class->ShouldHaveImt()) {
7537 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7538 for (size_t i = 0; i < ImTable::kSize; ++i) {
7539 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007540 }
7541 } else {
7542 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007543 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007544 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007545 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007546 FillIMTFromIfTable(if_table,
7547 unimplemented_method,
7548 imt_conflict_method,
7549 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007550 /*create_conflict_tables=*/false,
7551 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007552 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007553 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007554 }
7555 }
7556}
7557
Vladimir Marko921094a2017-01-12 18:37:06 +00007558class ClassLinker::LinkInterfaceMethodsHelper {
7559 public:
7560 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7561 Handle<mirror::Class> klass,
7562 Thread* self,
7563 Runtime* runtime)
7564 : class_linker_(class_linker),
7565 klass_(klass),
7566 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7567 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7568 self_(self),
7569 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7570 allocator_(&stack_),
7571 default_conflict_methods_(allocator_.Adapter()),
7572 overriding_default_conflict_methods_(allocator_.Adapter()),
7573 miranda_methods_(allocator_.Adapter()),
7574 default_methods_(allocator_.Adapter()),
7575 overriding_default_methods_(allocator_.Adapter()),
7576 move_table_(allocator_.Adapter()) {
7577 }
7578
7579 ArtMethod* FindMethod(ArtMethod* interface_method,
7580 MethodNameAndSignatureComparator& interface_name_comparator,
7581 ArtMethod* vtable_impl)
7582 REQUIRES_SHARED(Locks::mutator_lock_);
7583
7584 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7585 MethodNameAndSignatureComparator& interface_name_comparator)
7586 REQUIRES_SHARED(Locks::mutator_lock_);
7587
7588 bool HasNewVirtuals() const {
7589 return !(miranda_methods_.empty() &&
7590 default_methods_.empty() &&
7591 overriding_default_methods_.empty() &&
7592 overriding_default_conflict_methods_.empty() &&
7593 default_conflict_methods_.empty());
7594 }
7595
7596 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7597
7598 ObjPtr<mirror::PointerArray> UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007599 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007600 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007601
7602 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7603
7604 void UpdateIMT(ArtMethod** out_imt);
7605
7606 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7607 if (kIsDebugBuild) {
7608 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7609 // Check that there are no stale methods are in the dex cache array.
7610 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7611 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
David Srbecky5de5efe2021-02-15 21:23:00 +00007612 auto pair = mirror::DexCache::GetNativePair(resolved_methods, i);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007613 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007614 CHECK(move_table_.find(m) == move_table_.end() ||
7615 // The original versions of copied methods will still be present so allow those too.
7616 // Note that if the first check passes this might fail to GetDeclaringClass().
7617 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7618 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7619 [m] (ArtMethod& meth) {
7620 return &meth == m;
7621 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7622 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7623 }
7624 }
7625 }
7626
7627 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7628 LengthPrefixedArray<ArtMethod>* methods) {
7629 if (kIsDebugBuild) {
7630 CHECK(methods != nullptr);
7631 // Put some random garbage in old methods to help find stale pointers.
7632 if (methods != old_methods && old_methods != nullptr) {
7633 // Need to make sure the GC is not running since it could be scanning the methods we are
7634 // about to overwrite.
7635 ScopedThreadStateChange tsc(self_, kSuspended);
7636 gc::ScopedGCCriticalSection gcs(self_,
7637 gc::kGcCauseClassLinker,
7638 gc::kCollectorTypeClassLinker);
7639 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7640 method_size_,
7641 method_alignment_);
7642 memset(old_methods, 0xFEu, old_size);
7643 }
7644 }
7645 }
7646
7647 private:
7648 size_t NumberOfNewVirtuals() const {
7649 return miranda_methods_.size() +
7650 default_methods_.size() +
7651 overriding_default_conflict_methods_.size() +
7652 overriding_default_methods_.size() +
7653 default_conflict_methods_.size();
7654 }
7655
7656 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7657 return !klass_->IsInterface();
7658 }
7659
7660 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7661 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7662 << "Interfaces should only have default-conflict methods appended to them.";
7663 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7664 << miranda_methods_.size()
7665 << " default_methods=" << default_methods_.size()
7666 << " overriding_default_methods=" << overriding_default_methods_.size()
7667 << " default_conflict_methods=" << default_conflict_methods_.size()
7668 << " overriding_default_conflict_methods="
7669 << overriding_default_conflict_methods_.size();
7670 }
7671
7672 ClassLinker* class_linker_;
7673 Handle<mirror::Class> klass_;
7674 size_t method_alignment_;
7675 size_t method_size_;
7676 Thread* const self_;
7677
7678 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7679 // the virtual methods array.
7680 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7681 // during cross compilation.
7682 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7683 ArenaStack stack_;
7684 ScopedArenaAllocator allocator_;
7685
7686 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7687 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7688 ScopedArenaVector<ArtMethod*> miranda_methods_;
7689 ScopedArenaVector<ArtMethod*> default_methods_;
7690 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7691
7692 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7693};
7694
7695ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7696 ArtMethod* interface_method,
7697 MethodNameAndSignatureComparator& interface_name_comparator,
7698 ArtMethod* vtable_impl) {
7699 ArtMethod* current_method = nullptr;
7700 switch (class_linker_->FindDefaultMethodImplementation(self_,
7701 interface_method,
7702 klass_,
7703 /*out*/&current_method)) {
7704 case DefaultMethodSearchResult::kDefaultConflict: {
7705 // Default method conflict.
7706 DCHECK(current_method == nullptr);
7707 ArtMethod* default_conflict_method = nullptr;
7708 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7709 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7710 default_conflict_method = vtable_impl;
7711 } else {
7712 // See if we already have a conflict method for this method.
7713 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7714 interface_name_comparator,
7715 default_conflict_methods_,
7716 overriding_default_conflict_methods_);
7717 if (LIKELY(preexisting_conflict != nullptr)) {
7718 // We already have another conflict we can reuse.
7719 default_conflict_method = preexisting_conflict;
7720 } else {
7721 // Note that we do this even if we are an interface since we need to create this and
7722 // cannot reuse another classes.
7723 // Create a new conflict method for this to use.
7724 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7725 new(default_conflict_method) ArtMethod(interface_method,
7726 class_linker_->GetImagePointerSize());
7727 if (vtable_impl == nullptr) {
7728 // Save the conflict method. We need to add it to the vtable.
7729 default_conflict_methods_.push_back(default_conflict_method);
7730 } else {
7731 // Save the conflict method but it is already in the vtable.
7732 overriding_default_conflict_methods_.push_back(default_conflict_method);
7733 }
7734 }
7735 }
7736 current_method = default_conflict_method;
7737 break;
7738 } // case kDefaultConflict
7739 case DefaultMethodSearchResult::kDefaultFound: {
7740 DCHECK(current_method != nullptr);
7741 // Found a default method.
7742 if (vtable_impl != nullptr &&
7743 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7744 // We found a default method but it was the same one we already have from our
7745 // superclass. Don't bother adding it to our vtable again.
7746 current_method = vtable_impl;
7747 } else if (LIKELY(FillTables())) {
7748 // Interfaces don't need to copy default methods since they don't have vtables.
7749 // Only record this default method if it is new to save space.
7750 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7751 // would make lookup for interface super much faster. (We would only need to scan
7752 // the iftable to find if there is a NSME or AME.)
7753 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7754 default_methods_,
7755 overriding_default_methods_);
7756 if (old == nullptr) {
7757 // We found a default method implementation and there were no conflicts.
7758 if (vtable_impl == nullptr) {
7759 // Save the default method. We need to add it to the vtable.
7760 default_methods_.push_back(current_method);
7761 } else {
7762 // Save the default method but it is already in the vtable.
7763 overriding_default_methods_.push_back(current_method);
7764 }
7765 } else {
7766 CHECK(old == current_method) << "Multiple default implementations selected!";
7767 }
7768 }
7769 break;
7770 } // case kDefaultFound
7771 case DefaultMethodSearchResult::kAbstractFound: {
7772 DCHECK(current_method == nullptr);
7773 // Abstract method masks all defaults.
7774 if (vtable_impl != nullptr &&
7775 vtable_impl->IsAbstract() &&
7776 !vtable_impl->IsDefaultConflicting()) {
7777 // We need to make this an abstract method but the version in the vtable already is so
7778 // don't do anything.
7779 current_method = vtable_impl;
7780 }
7781 break;
7782 } // case kAbstractFound
7783 }
7784 return current_method;
7785}
7786
7787ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7788 ArtMethod* interface_method,
7789 MethodNameAndSignatureComparator& interface_name_comparator) {
7790 // Find out if there is already a miranda method we can use.
7791 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7792 miranda_methods_);
7793 if (miranda_method == nullptr) {
7794 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7795 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7796 CHECK(miranda_method != nullptr);
7797 // Point the interface table at a phantom slot.
7798 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7799 miranda_methods_.push_back(miranda_method);
7800 }
7801 return miranda_method;
7802}
7803
7804void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7805 LogNewVirtuals();
7806
7807 const size_t old_method_count = klass_->NumMethods();
7808 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7809 DCHECK_NE(old_method_count, new_method_count);
7810
7811 // Attempt to realloc to save RAM if possible.
7812 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7813 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7814 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7815 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7816 // CopyFrom has internal read barriers.
7817 //
7818 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7819 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7820 method_size_,
7821 method_alignment_);
7822 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7823 method_size_,
7824 method_alignment_);
7825 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7826 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007827 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007828 self_, old_methods, old_methods_ptr_size, new_size));
7829 CHECK(methods != nullptr); // Native allocation failure aborts.
7830
7831 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7832 if (methods != old_methods) {
7833 // Maps from heap allocated miranda method to linear alloc miranda method.
7834 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7835 // Copy over the old methods.
7836 for (auto& m : klass_->GetMethods(pointer_size)) {
7837 move_table_.emplace(&m, &*out);
7838 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7839 // barriers when it copies.
7840 out->CopyFrom(&m, pointer_size);
7841 ++out;
7842 }
7843 }
7844 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7845 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7846 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007847 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7848 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007849 ArtMethod& new_method = *out;
7850 new_method.CopyFrom(mir_method, pointer_size);
Vladimir Markode0d0de2021-03-18 14:12:35 +00007851 uint32_t access_flags = new_method.GetAccessFlags();
7852 DCHECK_EQ(access_flags & kAccIntrinsic, 0u) << "Miranda method should not be an intrinsic!";
7853 DCHECK_EQ(access_flags & kAccDefault, 0u) << "Miranda method should not be a default method!";
7854 DCHECK_NE(access_flags & kAccAbstract, 0u) << "Miranda method should be abstract!";
7855 new_method.SetAccessFlags(access_flags | kAccCopied);
Vladimir Marko921094a2017-01-12 18:37:06 +00007856 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007857 // Update the entry in the method array, as the array will be used for future lookups,
7858 // where thread suspension is allowed.
7859 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7860 // would not see them.
7861 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007862 ++out;
7863 }
7864 // We need to copy the default methods into our own method table since the runtime requires that
7865 // every method on a class's vtable be in that respective class's virtual method table.
7866 // NOTE This means that two classes might have the same implementation of a method from the same
7867 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7868 // default method found on a class with one found on the declaring interface directly and must
7869 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007870 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7871 &overriding_default_methods_}) {
7872 for (size_t i = 0; i < methods_vec->size(); ++i) {
7873 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007874 ArtMethod& new_method = *out;
7875 new_method.CopyFrom(def_method, pointer_size);
7876 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7877 // verified yet it shouldn't have methods that are skipping access checks.
7878 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7879 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007880 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007881 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7882 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7883 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7884 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007885 // Update the entry in the method array, as the array will be used for future lookups,
7886 // where thread suspension is allowed.
7887 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7888 // would not see them.
7889 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007890 ++out;
7891 }
7892 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007893 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7894 &overriding_default_conflict_methods_}) {
7895 for (size_t i = 0; i < methods_vec->size(); ++i) {
7896 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007897 ArtMethod& new_method = *out;
7898 new_method.CopyFrom(conf_method, pointer_size);
7899 // This is a type of default method (there are default method impls, just a conflict) so
Vladimir Markode0d0de2021-03-18 14:12:35 +00007900 // mark this as a default. We use the `kAccAbstract` flag to distinguish it from invokable
7901 // copied default method without using a separate access flag but the default conflicting
7902 // method is technically not abstract and ArtMethod::IsAbstract() shall return false.
7903 // Also clear the kAccSkipAccessChecks bit since this class hasn't been verified yet it
7904 // shouldn't have methods that are skipping access checks. Also clear potential
7905 // kAccSingleImplementation to avoid CHA trying to inline the default method.
7906 uint32_t access_flags = new_method.GetAccessFlags();
7907 DCHECK_EQ(access_flags & kAccNative, 0u);
7908 DCHECK_EQ(access_flags & kAccIntrinsic, 0u);
7909 constexpr uint32_t kSetFlags = kAccDefault | kAccAbstract | kAccCopied;
7910 constexpr uint32_t kMaskFlags = ~(kAccSkipAccessChecks | kAccSingleImplementation);
7911 new_method.SetAccessFlags((access_flags | kSetFlags) & kMaskFlags);
Vladimir Marko921094a2017-01-12 18:37:06 +00007912 DCHECK(new_method.IsDefaultConflicting());
Vladimir Markode0d0de2021-03-18 14:12:35 +00007913 DCHECK(!new_method.IsAbstract());
Vladimir Marko921094a2017-01-12 18:37:06 +00007914 // The actual method might or might not be marked abstract since we just copied it from a
7915 // (possibly default) interface method. We need to set it entry point to be the bridge so
7916 // that the compiler will not invoke the implementation of whatever method we copied from.
7917 EnsureThrowsInvocationError(class_linker_, &new_method);
7918 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007919 // Update the entry in the method array, as the array will be used for future lookups,
7920 // where thread suspension is allowed.
7921 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7922 // would not see them.
7923 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007924 ++out;
7925 }
7926 }
7927 methods->SetSize(new_method_count);
7928 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7929}
7930
7931ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007932 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007933 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007934 // Update the vtable to the new method structures. We can skip this for interfaces since they
7935 // do not have vtables.
7936 const size_t old_vtable_count = old_vtable->GetLength();
7937 const size_t new_vtable_count = old_vtable_count +
7938 miranda_methods_.size() +
7939 default_methods_.size() +
7940 default_conflict_methods_.size();
7941
Vladimir Marko3068d582019-05-28 16:39:29 +01007942 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
7943 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007944 if (UNLIKELY(vtable == nullptr)) {
7945 self_->AssertPendingOOMException();
7946 return nullptr;
7947 }
7948
7949 size_t vtable_pos = old_vtable_count;
7950 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7951 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7952 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7953 default_conflict_methods_,
7954 miranda_methods_}) {
7955 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007956 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007957 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7958 // fields are references into the dex file the method was defined in. Since the ArtMethod
7959 // does not store that information it uses declaring_class_->dex_cache_.
7960 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7961 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7962 ++vtable_pos;
7963 }
7964 }
7965 DCHECK_EQ(vtable_pos, new_vtable_count);
7966
7967 // Update old vtable methods. We use the default_translations map to figure out what each
7968 // vtable entry should be updated to, if they need to be at all.
7969 for (size_t i = 0; i < old_vtable_count; ++i) {
7970 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7971 // Try and find what we need to change this method to.
7972 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007973 if (translation_it != default_translations.end()) {
7974 if (translation_it->second.IsInConflict()) {
7975 // Find which conflict method we are to use for this method.
7976 MethodNameAndSignatureComparator old_method_comparator(
7977 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7978 // We only need to look through overriding_default_conflict_methods since this is an
7979 // overridden method we are fixing up here.
7980 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7981 old_method_comparator, overriding_default_conflict_methods_);
7982 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7983 translated_method = new_conflict_method;
7984 } else if (translation_it->second.IsAbstract()) {
7985 // Find which miranda method we are to use for this method.
7986 MethodNameAndSignatureComparator old_method_comparator(
7987 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7988 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7989 miranda_methods_);
7990 DCHECK(miranda_method != nullptr);
7991 translated_method = miranda_method;
7992 } else {
7993 // Normal default method (changed from an older default or abstract interface method).
7994 DCHECK(translation_it->second.IsTranslation());
7995 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007996 auto it = move_table_.find(translated_method);
7997 DCHECK(it != move_table_.end());
7998 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007999 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008000 } else {
8001 auto it = move_table_.find(translated_method);
8002 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008003 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008004
8005 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008006 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008007 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008008 if (kIsDebugBuild) {
8009 auto* methods = klass_->GetMethodsPtr();
8010 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008011 reinterpret_cast<uintptr_t>(translated_method));
8012 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008013 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8014 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008015 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008016 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008017 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008018 }
8019 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008020 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008021 return vtable;
8022}
8023
8024void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8025 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8026 const size_t ifcount = klass_->GetIfTableCount();
8027 // Go fix up all the stale iftable pointers.
8028 for (size_t i = 0; i < ifcount; ++i) {
8029 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008030 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8031 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008032 DCHECK(m != nullptr) << klass_->PrettyClass();
8033 auto it = move_table_.find(m);
8034 if (it != move_table_.end()) {
8035 auto* new_m = it->second;
8036 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8037 method_array->SetElementPtrSize(j, new_m, pointer_size);
8038 }
8039 }
8040 }
8041}
8042
8043void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8044 // Fix up IMT next.
8045 for (size_t i = 0; i < ImTable::kSize; ++i) {
8046 auto it = move_table_.find(out_imt[i]);
8047 if (it != move_table_.end()) {
8048 out_imt[i] = it->second;
8049 }
8050 }
8051}
8052
Alex Light705ad492015-09-21 11:36:30 -07008053// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008054bool ClassLinker::LinkInterfaceMethods(
8055 Thread* self,
8056 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00008057 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008058 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008059 ArtMethod** out_imt) {
8060 StackHandleScope<3> hs(self);
8061 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008062
8063 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008064 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008065 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008066 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008067 const size_t ifcount = klass->GetIfTableCount();
8068
Vladimir Marko921094a2017-01-12 18:37:06 +00008069 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008070
8071 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8072 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008073 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008074 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008075 const bool extend_super_iftable = has_superclass;
8076 if (has_superclass && fill_tables) {
8077 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008078 unimplemented_method,
8079 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008080 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008081 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008082 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008083 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8084 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008085 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008086 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8087 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008088 }
8089 }
8090
Vladimir Marko921094a2017-01-12 18:37:06 +00008091 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8092
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008093 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008094 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008095 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8096 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8097 // they will already be null. This has the additional benefit that the declarer of a miranda
8098 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008099 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008100 --i;
Alex Light9139e002015-10-09 15:59:48 -07008101 DCHECK_LT(i, ifcount);
8102
Alex Light705ad492015-09-21 11:36:30 -07008103 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008104 if (num_methods > 0) {
8105 StackHandleScope<2> hs2(self);
8106 const bool is_super = i < super_ifcount;
8107 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008108 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8109 // conflict methods. Just set this as nullptr in those cases.
8110 Handle<mirror::PointerArray> method_array(fill_tables
8111 ? hs2.NewHandle(iftable->GetMethodArray(i))
8112 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008113
Alex Lighte64300b2015-12-15 15:02:47 -08008114 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008115 ScopedNullHandle<mirror::PointerArray> null_handle;
8116 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008117 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008118
Alex Light9139e002015-10-09 15:59:48 -07008119 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8120 // and confusing. Default methods should always look through all the superclasses
8121 // because they are the last choice of an implementation. We get around this by looking
8122 // at the super-classes iftable methods (copied into method_array previously) when we are
8123 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008124 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008125 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008126 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008127 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008128 using_virtuals = true;
Alex Lighta467a6e2020-03-23 16:07:29 -07008129 input_virtual_methods = klass->GetDeclaredVirtualMethodsSlice(image_pointer_size_);
Alex Lighte64300b2015-12-15 15:02:47 -08008130 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008131 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008132 // For a new interface, however, we need the whole vtable in case a new
8133 // interface method is implemented in the whole superclass.
8134 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008135 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008136 input_vtable_array = vtable;
8137 input_array_length = input_vtable_array->GetLength();
8138 }
Alex Lighte64300b2015-12-15 15:02:47 -08008139
Alex Lighteb7c1442015-08-31 13:17:42 -07008140 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008141 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008142 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008143 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008144 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008145 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008146 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008147 // For each method listed in the interface's method list, find the
8148 // matching method in our class's method list. We want to favor the
8149 // subclass over the superclass, which just requires walking
8150 // back from the end of the vtable. (This only matters if the
8151 // superclass defines a private method and this class redefines
8152 // it -- otherwise it would use the same vtable slot. In .dex files
8153 // those don't end up in the virtual method table, so it shouldn't
8154 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008155 //
8156 // To find defaults we need to do the same but also go over interfaces.
8157 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008158 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008159 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008160 ArtMethod* vtable_method = using_virtuals ?
8161 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008162 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8163 ArtMethod* vtable_method_for_name_comparison =
8164 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Alex Lighta467a6e2020-03-23 16:07:29 -07008165 DCHECK(!vtable_method->IsStatic()) << vtable_method->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008166 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008167 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008168 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008169 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8170 // allocations.
8171 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008172 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008173 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008174 vtable_method->PrettyMethod().c_str(),
8175 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008176 return false;
Alex Light9139e002015-10-09 15:59:48 -07008177 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008178 // We might have a newer, better, default method for this, so we just skip it. If we
8179 // are still using this we will select it again when scanning for default methods. To
8180 // obviate the need to copy the method again we will make a note that we already found
8181 // a default here.
8182 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008183 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008184 break;
8185 } else {
8186 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008187 if (LIKELY(fill_tables)) {
8188 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8189 // Place method in imt if entry is empty, place conflict otherwise.
8190 SetIMTRef(unimplemented_method,
8191 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008192 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008193 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008194 /*out*/imt_ptr);
8195 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008196 break;
8197 }
8198 }
Alex Light9139e002015-10-09 15:59:48 -07008199 }
8200 // Continue on to the next method if we are done.
8201 if (LIKELY(found_impl)) {
8202 continue;
8203 } else if (LIKELY(super_interface)) {
8204 // Don't look for a default implementation when the super-method is implemented directly
8205 // by the class.
8206 //
8207 // See if we can use the superclasses method and skip searching everything else.
8208 // Note: !found_impl && super_interface
8209 CHECK(extend_super_iftable);
8210 // If this is a super_interface method it is possible we shouldn't override it because a
8211 // superclass could have implemented it directly. We get the method the superclass used
8212 // to implement this to know if we can override it with a default method. Doing this is
8213 // safe since we know that the super_iftable is filled in so we can simply pull it from
8214 // there. We don't bother if this is not a super-classes interface since in that case we
8215 // have scanned the entire vtable anyway and would have found it.
8216 // TODO This is rather dirty but it is faster than searching through the entire vtable
8217 // every time.
8218 ArtMethod* supers_method =
8219 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8220 DCHECK(supers_method != nullptr);
8221 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008222 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008223 // The method is not overridable by a default method (i.e. it is directly implemented
8224 // in some class). Therefore move onto the next interface method.
8225 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008226 } else {
8227 // If the super-classes method is override-able by a default method we need to keep
8228 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8229 // 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 -07008230 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8231 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8232 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008233 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008234 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8235 << " and not 'nullptr' or "
8236 << supers_method->PrettyMethod()
8237 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008238 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008239 }
8240 }
8241 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008242 ArtMethod* current_method = helper.FindMethod(interface_method,
8243 interface_name_comparator,
8244 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008245 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008246 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008247 // We could not find an implementation for this method and since it is a brand new
8248 // interface we searched the entire vtable (and all default methods) for an
8249 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008250 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8251 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008252 }
8253
8254 if (current_method != nullptr) {
8255 // We found a default method implementation. Record it in the iftable and IMT.
8256 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8257 SetIMTRef(unimplemented_method,
8258 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008259 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008260 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008261 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008262 }
8263 }
Alex Light705ad492015-09-21 11:36:30 -07008264 } // For each method in interface end.
8265 } // if (num_methods > 0)
8266 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008267 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008268 if (helper.HasNewVirtuals()) {
8269 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8270 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8271 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8272
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008273 // 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 -07008274 // suspension assert.
8275 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008276
Alex Light705ad492015-09-21 11:36:30 -07008277 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008278 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008279 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008280 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008281 return false;
8282 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008283 helper.UpdateIfTable(iftable);
8284 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008285 }
Alex Light705ad492015-09-21 11:36:30 -07008286
Vladimir Marko921094a2017-01-12 18:37:06 +00008287 helper.CheckNoStaleMethodsInDexCache();
8288 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008289 } else {
8290 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008291 }
Alex Light705ad492015-09-21 11:36:30 -07008292 if (kIsDebugBuild && !is_interface) {
Orion Hodson5880c772020-07-28 20:12:08 +01008293 CheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008294 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008295 return true;
8296}
8297
Vladimir Marko42bee502021-01-28 14:58:35 +00008298class ClassLinker::LinkFieldsHelper {
8299 public:
8300 static bool LinkFields(ClassLinker* class_linker,
8301 Thread* self,
8302 Handle<mirror::Class> klass,
8303 bool is_static,
8304 size_t* class_size)
8305 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008306
Vladimir Marko42bee502021-01-28 14:58:35 +00008307 private:
8308 enum class FieldTypeOrder : uint16_t;
8309 class FieldGaps;
8310
8311 struct FieldTypeOrderAndIndex {
8312 FieldTypeOrder field_type_order;
8313 uint16_t field_index;
8314 };
8315
8316 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8317
8318 template <size_t kSize>
8319 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8320 REQUIRES_SHARED(Locks::mutator_lock_);
8321};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008322
Vladimir Markoc7993d52021-01-27 15:20:56 +00008323// We use the following order of field types for assigning offsets.
8324// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008325enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008326 kReference = 0u,
8327 kLong,
8328 kDouble,
8329 kInt,
8330 kFloat,
8331 kChar,
8332 kShort,
8333 kBoolean,
8334 kByte,
8335
8336 kLast64BitType = kDouble,
8337 kLast32BitType = kFloat,
8338 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008339};
8340
Vladimir Markoc7993d52021-01-27 15:20:56 +00008341ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008342ClassLinker::LinkFieldsHelper::FieldTypeOrder
8343ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008344 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008345 case 'J':
8346 return FieldTypeOrder::kLong;
8347 case 'D':
8348 return FieldTypeOrder::kDouble;
8349 case 'I':
8350 return FieldTypeOrder::kInt;
8351 case 'F':
8352 return FieldTypeOrder::kFloat;
8353 case 'C':
8354 return FieldTypeOrder::kChar;
8355 case 'S':
8356 return FieldTypeOrder::kShort;
8357 case 'Z':
8358 return FieldTypeOrder::kBoolean;
8359 case 'B':
8360 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008361 default:
8362 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8363 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008364 }
8365}
8366
8367// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008368class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008369 public:
8370 template <uint32_t kSize>
8371 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8372 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8373 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8374 uint32_t gap_start = field_offset.Uint32Value();
8375 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8376 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8377 }
8378 return field_offset;
8379 }
8380
8381 template <uint32_t kSize>
8382 bool HasGap() const {
8383 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8384 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8385 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8386 gap4_offset_ != kNoOffset;
8387 }
8388
8389 template <uint32_t kSize>
8390 MemberOffset ReleaseGap() {
8391 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8392 uint32_t result;
8393 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8394 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8395 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8396 result = gap1_offset_;
8397 gap1_offset_ = kNoOffset;
8398 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8399 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8400 result = gap2_offset_;
8401 gap2_offset_ = kNoOffset;
8402 if (kSize < 2u) {
8403 AddGaps<1u>(result + kSize, result + 2u);
8404 }
8405 } else {
8406 DCHECK_NE(gap4_offset_, kNoOffset);
8407 result = gap4_offset_;
8408 gap4_offset_ = kNoOffset;
8409 if (kSize < 4u) {
8410 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8411 }
8412 }
8413 return MemberOffset(result);
8414 }
8415
8416 private:
8417 template <uint32_t kGapsToCheck>
8418 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8419 if ((kGapsToCheck & 1u) != 0u) {
8420 DCHECK_LT(gap_start, gap_end);
8421 DCHECK_ALIGNED(gap_end, 2u);
8422 if ((gap_start & 1u) != 0u) {
8423 DCHECK_EQ(gap1_offset_, kNoOffset);
8424 gap1_offset_ = gap_start;
8425 gap_start += 1u;
8426 if (kGapsToCheck == 1u || gap_start == gap_end) {
8427 DCHECK_EQ(gap_start, gap_end);
8428 return;
8429 }
8430 }
8431 }
8432
8433 if ((kGapsToCheck & 2u) != 0u) {
8434 DCHECK_LT(gap_start, gap_end);
8435 DCHECK_ALIGNED(gap_start, 2u);
8436 DCHECK_ALIGNED(gap_end, 4u);
8437 if ((gap_start & 2u) != 0u) {
8438 DCHECK_EQ(gap2_offset_, kNoOffset);
8439 gap2_offset_ = gap_start;
8440 gap_start += 2u;
8441 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8442 DCHECK_EQ(gap_start, gap_end);
8443 return;
8444 }
8445 }
8446 }
8447
8448 if ((kGapsToCheck & 4u) != 0u) {
8449 DCHECK_LT(gap_start, gap_end);
8450 DCHECK_ALIGNED(gap_start, 4u);
8451 DCHECK_ALIGNED(gap_end, 8u);
8452 DCHECK_EQ(gap_start + 4u, gap_end);
8453 DCHECK_EQ(gap4_offset_, kNoOffset);
8454 gap4_offset_ = gap_start;
8455 return;
8456 }
8457
8458 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8459 << " after checking " << kGapsToCheck;
8460 }
8461
8462 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8463
8464 uint32_t gap4_offset_ = kNoOffset;
8465 uint32_t gap2_offset_ = kNoOffset;
8466 uint32_t gap1_offset_ = kNoOffset;
8467};
8468
8469template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008470ALWAYS_INLINE
8471MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8472 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008473 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8474 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8475 field->SetOffset(field_offset);
8476 return MemberOffset(field_offset.Uint32Value() + kSize);
8477}
8478
Vladimir Marko42bee502021-01-28 14:58:35 +00008479bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8480 Thread* self,
8481 Handle<mirror::Class> klass,
8482 bool is_static,
8483 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008484 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008485 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008486 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8487 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008488
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008489 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008490 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008491 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008492 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8493 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008494 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008495 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008496 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008497 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008498 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008499 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008500 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008501 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008502
David Sehr709b0702016-10-13 09:12:37 -07008503 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008504
Brian Carlstromdbc05252011-09-09 01:59:59 -07008505 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008506 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008507 //
8508 // The overall sort order order is:
8509 // 1) All object reference fields, sorted alphabetically.
8510 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8511 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8512 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8513 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8514 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8515 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8516 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8517 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8518 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008519 // (References are first to increase the chance of reference visiting
8520 // being able to take a fast path using a bitmap of references at the
8521 // start of the object, see `Class::reference_instance_offsets_`.)
8522 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008523 // Once the fields are sorted in this order we will attempt to fill any gaps
8524 // that might be present in the memory layout of the structure.
8525 // Note that we shall not fill gaps between the superclass fields.
8526
8527 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008528 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008529 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008530 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8531 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8532 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8533 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008534 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008535 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008536 } else {
8537 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008538 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008539 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008540 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008541 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008542 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008543 for (size_t i = 0; i != num_fields; ++i) {
8544 ArtField* field = &fields->At(i);
8545 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008546 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8547 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008548 // Insert references to the start, other fields to the end.
8549 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008550 if (field_type_order == FieldTypeOrder::kReference) {
8551 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008552 ++num_reference_fields;
8553 } else {
8554 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008555 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008556 }
8557 }
8558 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008559
Vladimir Marko42bee502021-01-28 14:58:35 +00008560 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008561 DCHECK(std::is_sorted(
8562 sorted_fields.begin(),
8563 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008564 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8565 ArtField* lhs_field = &fields->At(lhs.field_index);
8566 ArtField* rhs_field = &fields->At(rhs.field_index);
8567 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8568 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8569 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8570 lhs.field_index < rhs.field_index);
8571 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008572 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008573 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008574 DCHECK(std::is_sorted(
8575 sorted_fields.begin() + primitive_fields_start,
8576 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008577 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8578 ArtField* lhs_field = &fields->At(lhs.field_index);
8579 ArtField* rhs_field = &fields->At(rhs.field_index);
8580 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8581 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8582 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8583 lhs.field_index > rhs.field_index);
8584 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008585 }));
8586 // Sort the primitive fields by the field type order, then field index.
8587 std::sort(sorted_fields.begin() + primitive_fields_start,
8588 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008589 [](const auto& lhs, const auto& rhs) {
8590 if (lhs.field_type_order != rhs.field_type_order) {
8591 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008592 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008593 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008594 }
8595 });
8596 // Primitive fields are now sorted by field size (descending), then type, then field index.
8597 DCHECK(std::is_sorted(
8598 sorted_fields.begin() + primitive_fields_start,
8599 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008600 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8601 ArtField* lhs_field = &fields->At(lhs.field_index);
8602 ArtField* rhs_field = &fields->At(rhs.field_index);
8603 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008604 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008605 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008606 CHECK_NE(rhs_type, Primitive::kPrimNot);
8607 if (lhs_type != rhs_type) {
8608 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8609 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8610 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8611 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008612 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008613 }
8614 }));
8615
8616 // Process reference fields.
8617 FieldGaps field_gaps;
8618 size_t index = 0u;
8619 if (num_reference_fields != 0u) {
8620 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8621 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8622 for (; index != num_reference_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008623 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008624 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008625 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008626 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008627 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008628 if (index != num_fields &&
8629 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008630 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008631 while (index != num_fields &&
8632 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8633 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008634 field_offset = AssignFieldOffset<8u>(field, field_offset);
8635 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008636 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008637 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008638 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008639 if (index != num_fields &&
8640 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008641 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8642 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008643 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008644 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8645 ++index;
8646 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8647 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008648 while (index != num_fields &&
8649 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8650 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008651 field_offset = AssignFieldOffset<4u>(field, field_offset);
8652 ++index;
8653 }
8654 }
8655 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008656 if (index != num_fields &&
8657 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008658 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8659 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008660 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008661 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008662 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008663 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8664 ++index;
8665 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008666 while (index != num_fields &&
8667 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8668 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008669 field_offset = AssignFieldOffset<2u>(field, field_offset);
8670 ++index;
8671 }
8672 }
8673 // Process 8-bit fields.
8674 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008675 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008676 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8677 }
8678 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008679 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008680 field_offset = AssignFieldOffset<1u>(field, field_offset);
8681 }
8682
Ian Rogers7b078e82014-09-10 14:44:24 -07008683 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008684
Elliott Hughesadb460d2011-10-05 17:02:34 -07008685 // 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 +00008686 DCHECK(!class_linker->init_done_ || !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
8687 if (!is_static &&
8688 UNLIKELY(!class_linker->init_done_) &&
8689 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008690 // We know there are no non-reference fields in the Reference classes, and we know
8691 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008692 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008693 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008694 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008695 --num_reference_fields;
8696 }
8697
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008698 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008699 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008700 if (is_static) {
8701 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008702 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008703 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008704 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008705 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008706 if (num_reference_fields == 0 || super_class == nullptr) {
8707 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008708 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008709 if (super_class == nullptr ||
8710 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8711 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008712 }
8713 }
8714 if (kIsDebugBuild) {
8715 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8716 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008717 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008718 while (cur_super != nullptr) {
8719 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8720 cur_super = cur_super->GetSuperClass();
8721 }
8722 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008723 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008724 } else {
8725 // Check that there is at least num_reference_fields other than Object.class.
8726 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008727 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008728 }
8729 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008730 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008731 std::string temp;
8732 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8733 size_t previous_size = klass->GetObjectSize();
8734 if (previous_size != 0) {
8735 // Make sure that we didn't originally have an incorrect size.
8736 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008737 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008738 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008739 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008740 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008741
8742 if (kIsDebugBuild) {
8743 // Make sure that the fields array is ordered by name but all reference
8744 // offsets are at the beginning as far as alignment allows.
8745 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00008746 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008747 : klass->GetFirstReferenceInstanceFieldOffset();
8748 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8749 num_reference_fields *
8750 sizeof(mirror::HeapReference<mirror::Object>));
8751 MemberOffset current_ref_offset = start_ref_offset;
8752 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008753 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008754 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008755 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8756 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008757 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008758 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008759 // NOTE: The field names can be the same. This is not possible in the Java language
8760 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008761 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008762 }
8763 Primitive::Type type = field->GetTypeAsPrimitiveType();
8764 bool is_primitive = type != Primitive::kPrimNot;
8765 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8766 strcmp("referent", field->GetName()) == 0) {
8767 is_primitive = true; // We lied above, so we have to expect a lie here.
8768 }
8769 MemberOffset offset = field->GetOffsetDuringLinking();
8770 if (is_primitive) {
8771 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8772 // Shuffled before references.
8773 size_t type_size = Primitive::ComponentSize(type);
8774 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8775 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8776 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8777 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8778 }
8779 } else {
8780 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8781 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8782 sizeof(mirror::HeapReference<mirror::Object>));
8783 }
8784 }
8785 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8786 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008787 return true;
8788}
8789
Vladimir Marko42bee502021-01-28 14:58:35 +00008790bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
8791 CHECK(klass != nullptr);
8792 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
8793}
8794
8795bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
8796 CHECK(klass != nullptr);
8797 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
8798}
8799
Vladimir Marko76649e82014-11-10 18:32:59 +00008800// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008801void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008802 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008803 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008804 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008805 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008806 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008807 // Compute reference offsets unless our superclass overflowed.
8808 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8809 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008810 if (num_reference_fields != 0u) {
8811 // All of the fields that contain object references are guaranteed be grouped in memory
8812 // starting at an appropriately aligned address after super class object data.
8813 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8814 sizeof(mirror::HeapReference<mirror::Object>));
8815 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008816 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008817 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008818 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008819 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008820 reference_offsets |= (0xffffffffu << start_bit) &
8821 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008822 }
8823 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008824 }
8825 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008826 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008827}
8828
Vladimir Marko18090d12018-06-01 16:53:12 +01008829ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8830 ObjPtr<mirror::DexCache> dex_cache) {
8831 StackHandleScope<1> hs(Thread::Current());
8832 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8833 return DoResolveString(string_idx, h_dex_cache);
8834}
8835
8836ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8837 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008838 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008839 uint32_t utf16_length;
8840 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008841 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008842 if (string != nullptr) {
8843 dex_cache->SetResolvedString(string_idx, string);
8844 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008845 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008846}
8847
Vladimir Marko18090d12018-06-01 16:53:12 +01008848ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8849 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008850 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008851 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008852 uint32_t utf16_length;
8853 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008854 ObjPtr<mirror::String> string =
8855 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008856 if (string != nullptr) {
8857 dex_cache->SetResolvedString(string_idx, string);
8858 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008859 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008860}
8861
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008862ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008863 ObjPtr<mirror::Class> referrer) {
8864 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8865}
8866
8867ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008868 ObjPtr<mirror::DexCache> dex_cache,
8869 ObjPtr<mirror::ClassLoader> class_loader) {
8870 const DexFile& dex_file = *dex_cache->GetDexFile();
8871 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Vladimir Markoc63d9672021-03-31 15:50:39 +01008872 ObjPtr<mirror::Class> type = LookupResolvedType(descriptor, class_loader);
8873 if (type != nullptr) {
8874 DCHECK(type->IsResolved());
8875 dex_cache->SetResolvedType(type_idx, type);
8876 }
8877 return type;
8878}
8879
8880ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const char* descriptor,
8881 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008882 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8883 ObjPtr<mirror::Class> type = nullptr;
8884 if (descriptor[1] == '\0') {
8885 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8886 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008887 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008888 } else {
8889 Thread* const self = Thread::Current();
8890 DCHECK(self != nullptr);
8891 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8892 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008893 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008894 }
Vladimir Markoc63d9672021-03-31 15:50:39 +01008895 return (type != nullptr && type->IsResolved()) ? type : nullptr;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008896}
8897
Andreas Gampeb0625e02019-05-01 12:43:31 -07008898template <typename RefType>
8899ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008900 StackHandleScope<2> hs(Thread::Current());
8901 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8902 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8903 return DoResolveType(type_idx, dex_cache, class_loader);
8904}
8905
Andreas Gampe4835d212018-11-21 14:55:10 -08008906// Instantiate the above.
8907template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8908 ArtField* referrer);
8909template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8910 ArtMethod* referrer);
8911template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8912 ObjPtr<mirror::Class> referrer);
8913
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008914ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008915 Handle<mirror::DexCache> dex_cache,
8916 Handle<mirror::ClassLoader> class_loader) {
8917 Thread* self = Thread::Current();
8918 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8919 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8920 if (resolved != nullptr) {
8921 // TODO: we used to throw here if resolved's class loader was not the
8922 // boot class loader. This was to permit different classes with the
8923 // same name to be loaded simultaneously by different loaders
8924 dex_cache->SetResolvedType(type_idx, resolved);
8925 } else {
8926 CHECK(self->IsExceptionPending())
8927 << "Expected pending exception for failed resolution of: " << descriptor;
8928 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8929 StackHandleScope<1> hs(self);
8930 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008931 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008932 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8933 self->ClearException();
8934 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8935 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008936 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008937 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008938 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008939 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008940 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008941}
8942
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008943ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8944 ObjPtr<mirror::DexCache> dex_cache,
8945 ObjPtr<mirror::ClassLoader> class_loader,
8946 uint32_t method_idx) {
8947 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8948 // functions can optimize the search if the dex_cache is the same as the DexCache
8949 // of the class, with fall-back to name and signature search otherwise.
8950 ArtMethod* resolved = nullptr;
8951 if (klass->IsInterface()) {
8952 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8953 } else {
8954 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8955 }
8956 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008957 if (resolved != nullptr &&
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00008958 // We pass AccessMethod::kNone instead of kLinking to not warn yet on the
8959 // access, as we'll be looking if the method can be accessed through an
8960 // interface.
David Brazdilf50ac102018-10-17 18:00:06 +01008961 hiddenapi::ShouldDenyAccessToMember(resolved,
8962 hiddenapi::AccessContext(class_loader, dex_cache),
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00008963 hiddenapi::AccessMethod::kNone)) {
8964 // The resolved method that we have found cannot be accessed due to
8965 // hiddenapi (typically it is declared up the hierarchy and is not an SDK
8966 // method). Try to find an interface method from the implemented interfaces which is
Nicolas Geoffrayaf61f502021-03-31 16:03:50 +00008967 // part of the SDK.
8968 ArtMethod* itf_method = klass->FindAccessibleInterfaceMethod(resolved, image_pointer_size_);
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00008969 if (itf_method == nullptr) {
8970 // No interface method. Call ShouldDenyAccessToMember again but this time
8971 // with AccessMethod::kLinking to ensure that an appropriate warning is
8972 // logged.
8973 hiddenapi::ShouldDenyAccessToMember(resolved,
8974 hiddenapi::AccessContext(class_loader, dex_cache),
8975 hiddenapi::AccessMethod::kLinking);
8976 resolved = nullptr;
8977 } else {
8978 // We found an interface method that is accessible, continue with the resolved method.
8979 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008980 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008981 if (resolved != nullptr) {
8982 // In case of jmvti, the dex file gets verified before being registered, so first
8983 // check if it's registered before checking class tables.
8984 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008985 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8986 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008987 << "DexFile referrer: " << dex_file.GetLocation()
8988 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8989 // Be a good citizen and update the dex cache to speed subsequent calls.
David Srbecky5de5efe2021-02-15 21:23:00 +00008990 dex_cache->SetResolvedMethod(method_idx, resolved);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008991 // Disable the following invariant check as the verifier breaks it. b/73760543
8992 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8993 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8994 // << "Method: " << resolved->PrettyMethod() << ", "
8995 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8996 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008997 }
8998 return resolved;
8999}
9000
David Brazdil4525e0b2018-04-05 16:57:32 +01009001// Returns true if `method` is either null or hidden.
9002// Does not print any warnings if it is hidden.
9003static bool CheckNoSuchMethod(ArtMethod* method,
9004 ObjPtr<mirror::DexCache> dex_cache,
9005 ObjPtr<mirror::ClassLoader> class_loader)
9006 REQUIRES_SHARED(Locks::mutator_lock_) {
9007 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01009008 hiddenapi::ShouldDenyAccessToMember(method,
9009 hiddenapi::AccessContext(class_loader, dex_cache),
9010 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01009011}
9012
9013ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
9014 ObjPtr<mirror::DexCache> dex_cache,
9015 ObjPtr<mirror::ClassLoader> class_loader,
9016 uint32_t method_idx) {
9017 if (klass->IsInterface()) {
9018 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9019 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
9020 } else {
9021 // If there was an interface method with the same signature, we would have
9022 // found it in the "copied" methods. Only DCHECK that the interface method
9023 // really does not exist.
9024 if (kIsDebugBuild) {
9025 ArtMethod* method =
9026 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9027 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
9028 }
9029 return nullptr;
9030 }
9031}
9032
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009033template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00009034ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07009035 Handle<mirror::DexCache> dex_cache,
9036 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009037 ArtMethod* referrer,
9038 InvokeType type) {
Nicolas Geoffray605c5912020-04-08 15:12:39 +01009039 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Andreas Gampefa4333d2017-02-14 11:10:34 -08009040 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01009041 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07009042 // Check for hit in the dex cache.
David Srbecky5de5efe2021-02-15 21:23:00 +00009043 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009044 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009045 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
9046 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01009047 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
9048 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07009049 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009050 return resolved;
9051 }
Vladimir Marko89011192017-12-11 13:45:05 +00009052 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009053 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009054 ObjPtr<mirror::Class> klass = nullptr;
9055 if (valid_dex_cache_method) {
9056 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
9057 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009058 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009059 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009060 // We normaly should not end up here. However the verifier currently doesn't guarantee
9061 // the invariant of having the klass in the class table. b/73760543
9062 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Nicolas Geoffray07614192020-04-28 17:31:31 +01009063 if (klass == nullptr) {
9064 // This can only happen if the current thread is not allowed to load
9065 // classes.
9066 DCHECK(!Thread::Current()->CanLoadClasses());
9067 DCHECK(Thread::Current()->IsExceptionPending());
9068 return nullptr;
9069 }
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009070 }
Vladimir Markoba118822017-06-12 15:41:56 +01009071 } else {
9072 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009073 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01009074 if (klass == nullptr) {
9075 DCHECK(Thread::Current()->IsExceptionPending());
9076 return nullptr;
9077 }
9078 }
9079
9080 // Check if the invoke type matches the class type.
9081 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009082 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01009083 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07009084 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009085 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009086 }
Vladimir Markoba118822017-06-12 15:41:56 +01009087
9088 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009089 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009090 }
Vladimir Markoba118822017-06-12 15:41:56 +01009091
9092 // Note: We can check for IllegalAccessError only if we have a referrer.
9093 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
9094 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
9095 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9096 if (!referring_class->CheckResolvedMethodAccess(methods_class,
9097 resolved,
9098 dex_cache.Get(),
9099 method_idx,
9100 type)) {
9101 DCHECK(Thread::Current()->IsExceptionPending());
9102 return nullptr;
9103 }
9104 }
9105
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009106 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01009107 if (LIKELY(resolved != nullptr) &&
9108 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
9109 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07009110 return resolved;
9111 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009112 // If we had a method, or if we can find one with another lookup type,
9113 // it's an incompatible-class-change error.
9114 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01009115 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009116 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009117 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07009118 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009119 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009120 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009121 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
9122 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01009123 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07009124 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08009125 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009126 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07009127 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009128}
9129
Vladimir Marko89011192017-12-11 13:45:05 +00009130ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009131 Handle<mirror::DexCache> dex_cache,
9132 Handle<mirror::ClassLoader> class_loader) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009133 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009134 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009135 if (resolved != nullptr) {
9136 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009137 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9138 return resolved;
9139 }
9140 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009141 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009142 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009143 if (klass == nullptr) {
9144 Thread::Current()->AssertPendingException();
9145 return nullptr;
9146 }
9147 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009148 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9149 } else {
9150 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009151 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009152 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009153 hiddenapi::ShouldDenyAccessToMember(
9154 resolved,
9155 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9156 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009157 resolved = nullptr;
9158 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009159 return resolved;
9160}
9161
Vladimir Markof44d36c2017-03-14 14:18:46 +00009162ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9163 ObjPtr<mirror::DexCache> dex_cache,
9164 ObjPtr<mirror::ClassLoader> class_loader,
9165 bool is_static) {
9166 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009167 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009168 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9169 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009170 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009171 }
9172 if (klass == nullptr) {
9173 // The class has not been resolved yet, so the field is also unresolved.
9174 return nullptr;
9175 }
9176 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009177
David Brazdil1ab0fa82018-05-04 11:28:03 +01009178 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009179}
9180
Vladimir Markoe11dd502017-12-08 14:09:45 +00009181ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009182 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009183 Handle<mirror::ClassLoader> class_loader,
9184 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009185 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayf3688822020-03-25 15:04:03 +00009186 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
David Srbecky5de5efe2021-02-15 21:23:00 +00009187 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009188 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009189 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009190 return resolved;
9191 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009192 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009193 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009194 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009195 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08009196 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07009197 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009198 }
9199
David Brazdil1ab0fa82018-05-04 11:28:03 +01009200 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07009201 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08009202 const char* name = dex_file.GetFieldName(field_id);
9203 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009204 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009205 }
Ian Rogersb067ac22011-12-13 18:05:09 -08009206 return resolved;
9207}
9208
Vladimir Markoe11dd502017-12-08 14:09:45 +00009209ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009210 Handle<mirror::DexCache> dex_cache,
9211 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009212 DCHECK(dex_cache != nullptr);
David Srbecky5de5efe2021-02-15 21:23:00 +00009213 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009214 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009215 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009216 return resolved;
9217 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009218 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009219 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009220 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009221 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009222 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009223 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009224 }
9225
David Brazdil1ab0fa82018-05-04 11:28:03 +01009226 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9227 if (resolved == nullptr) {
9228 const char* name = dex_file.GetFieldName(field_id);
9229 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009230 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009231 }
9232 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009233}
9234
David Brazdil1ab0fa82018-05-04 11:28:03 +01009235ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9236 ObjPtr<mirror::DexCache> dex_cache,
9237 ObjPtr<mirror::ClassLoader> class_loader,
9238 uint32_t field_idx,
9239 bool is_static) {
Vladimir Markob10668c2021-06-10 09:52:53 +01009240 ArtField* resolved = is_static ? klass->FindStaticField(dex_cache, field_idx)
9241 : klass->FindInstanceField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009242 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009243 hiddenapi::ShouldDenyAccessToMember(resolved,
9244 hiddenapi::AccessContext(class_loader, dex_cache),
9245 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009246 resolved = nullptr;
9247 }
9248
9249 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009250 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009251 }
9252
9253 return resolved;
9254}
9255
9256ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9257 ObjPtr<mirror::DexCache> dex_cache,
9258 ObjPtr<mirror::ClassLoader> class_loader,
9259 uint32_t field_idx) {
Vladimir Markob10668c2021-06-10 09:52:53 +01009260 ArtField* resolved = klass->FindField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009261
9262 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009263 hiddenapi::ShouldDenyAccessToMember(resolved,
9264 hiddenapi::AccessContext(class_loader, dex_cache),
9265 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009266 resolved = nullptr;
9267 }
9268
9269 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009270 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009271 }
9272
9273 return resolved;
9274}
9275
Vladimir Markoaf940202017-12-08 15:01:18 +00009276ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9277 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009278 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009279 Handle<mirror::DexCache> dex_cache,
9280 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009281 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009282 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009283
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009284 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009285 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009286 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009287 }
9288
Narayan Kamath25352fc2016-08-03 12:46:58 +01009289 StackHandleScope<4> hs(self);
9290
9291 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009292 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009293 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009294 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009295 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009296 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009297 DCHECK(self->IsExceptionPending());
9298 return nullptr;
9299 }
9300
9301 // Then resolve the argument types.
9302 //
9303 // TODO: Is there a better way to figure out the number of method arguments
9304 // other than by looking at the shorty ?
9305 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9306
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009307 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009308 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9309 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009310 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009311 DCHECK(self->IsExceptionPending());
9312 return nullptr;
9313 }
9314
9315 DexFileParameterIterator it(dex_file, proto_id);
9316 int32_t i = 0;
9317 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9318 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009319 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009320 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009321 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009322 DCHECK(self->IsExceptionPending());
9323 return nullptr;
9324 }
9325
9326 method_params->Set(i++, param_class.Get());
9327 }
9328
9329 DCHECK(!it.HasNext());
9330
9331 Handle<mirror::MethodType> type = hs.NewHandle(
9332 mirror::MethodType::Create(self, return_type, method_params));
Nicolas Geoffray4aebd582021-07-23 15:27:31 +01009333 if (type != nullptr) {
9334 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9335 }
Narayan Kamath25352fc2016-08-03 12:46:58 +01009336
9337 return type.Get();
9338}
9339
Vladimir Markoaf940202017-12-08 15:01:18 +00009340ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009341 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009342 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009343 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009344 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9345 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009346 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009347}
9348
Vladimir Marko5aead702019-03-27 11:00:36 +00009349ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009350 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009351 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009352 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009353 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009354 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9355 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009356 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009357 bool is_static;
9358 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009359 switch (handle_type) {
9360 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009361 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009362 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009363 is_static = true;
9364 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009365 break;
9366 }
9367 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009368 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009369 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009370 is_static = true;
9371 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009372 break;
9373 }
9374 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009375 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009376 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009377 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009378 num_params = 2;
9379 break;
9380 }
9381 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009382 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009383 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009384 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009385 num_params = 1;
9386 break;
9387 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009388 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009389 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009390 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009391 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009392 case DexFile::MethodHandleType::kInvokeInterface:
9393 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009394 }
9395
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009396 ArtField* target_field =
9397 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9398 if (LIKELY(target_field != nullptr)) {
9399 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9400 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9401 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9402 ThrowIllegalAccessErrorField(referring_class, target_field);
9403 return nullptr;
9404 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009405 if (UNLIKELY(is_put && target_field->IsFinal())) {
9406 ThrowIllegalAccessErrorField(referring_class, target_field);
9407 return nullptr;
9408 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009409 } else {
9410 DCHECK(Thread::Current()->IsExceptionPending());
9411 return nullptr;
9412 }
9413
9414 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009415 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009416 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9417 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009418 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009419 DCHECK(self->IsExceptionPending());
9420 return nullptr;
9421 }
9422
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009423 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009424 Handle<mirror::Class> return_type;
9425 switch (handle_type) {
9426 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009427 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009428 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009429 break;
9430 }
9431 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009432 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009433 break;
9434 }
9435 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009436 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009437 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009438 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009439 break;
9440 }
9441 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009442 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009443 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009444 break;
9445 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009446 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009447 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009448 case DexFile::MethodHandleType::kInvokeConstructor:
9449 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009450 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009451 UNREACHABLE();
9452 }
9453
9454 for (int32_t i = 0; i < num_params; ++i) {
9455 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9456 DCHECK(self->IsExceptionPending());
9457 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009458 }
9459 }
9460
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009461 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009462 DCHECK(self->IsExceptionPending());
9463 return nullptr;
9464 }
9465
9466 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009467 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9468 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009469 DCHECK(self->IsExceptionPending());
9470 return nullptr;
9471 }
Orion Hodson631827d2017-04-10 14:53:47 +01009472
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009473 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9474 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9475}
9476
Vladimir Marko5aead702019-03-27 11:00:36 +00009477ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009478 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009479 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009480 ArtMethod* referrer) {
9481 DexFile::MethodHandleType handle_type =
9482 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9483 mirror::MethodHandle::Kind kind;
9484 uint32_t receiver_count = 0;
9485 ArtMethod* target_method = nullptr;
9486 switch (handle_type) {
9487 case DexFile::MethodHandleType::kStaticPut:
9488 case DexFile::MethodHandleType::kStaticGet:
9489 case DexFile::MethodHandleType::kInstancePut:
9490 case DexFile::MethodHandleType::kInstanceGet:
9491 UNREACHABLE();
9492 case DexFile::MethodHandleType::kInvokeStatic: {
9493 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9494 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009495 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9496 method_handle.field_or_method_idx_,
9497 referrer,
9498 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009499 break;
9500 }
9501 case DexFile::MethodHandleType::kInvokeInstance: {
9502 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9503 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009504 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9505 method_handle.field_or_method_idx_,
9506 referrer,
9507 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009508 break;
9509 }
9510 case DexFile::MethodHandleType::kInvokeConstructor: {
9511 // Constructors are currently implemented as a transform. They
9512 // are special cased later in this method.
9513 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9514 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009515 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9516 method_handle.field_or_method_idx_,
9517 referrer,
9518 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009519 break;
9520 }
9521 case DexFile::MethodHandleType::kInvokeDirect: {
9522 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9523 receiver_count = 1;
9524 StackHandleScope<2> hs(self);
9525 // A constant method handle with type kInvokeDirect can refer to
9526 // a method that is private or to a method in a super class. To
9527 // disambiguate the two options, we resolve the method ignoring
9528 // the invocation type to determine if the method is private. We
9529 // then resolve again specifying the intended invocation type to
9530 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009531 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009532 hs.NewHandle(referrer->GetDexCache()),
9533 hs.NewHandle(referrer->GetClassLoader()));
9534 if (UNLIKELY(target_method == nullptr)) {
9535 break;
9536 }
9537
9538 if (target_method->IsPrivate()) {
9539 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009540 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9541 method_handle.field_or_method_idx_,
9542 referrer,
9543 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009544 } else {
9545 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009546 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9547 method_handle.field_or_method_idx_,
9548 referrer,
9549 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009550 if (UNLIKELY(target_method == nullptr)) {
9551 break;
9552 }
9553 // Find the method specified in the parent in referring class
9554 // so invoke-super invokes the method in the parent of the
9555 // referrer.
9556 target_method =
9557 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9558 kRuntimePointerSize);
9559 }
9560 break;
9561 }
9562 case DexFile::MethodHandleType::kInvokeInterface: {
9563 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9564 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009565 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9566 method_handle.field_or_method_idx_,
9567 referrer,
9568 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009569 break;
9570 }
Orion Hodson631827d2017-04-10 14:53:47 +01009571 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009572
9573 if (UNLIKELY(target_method == nullptr)) {
9574 DCHECK(Thread::Current()->IsExceptionPending());
9575 return nullptr;
9576 }
9577
9578 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9579 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9580 uint32_t access_flags = target_method->GetAccessFlags();
9581 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9582 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9583 return nullptr;
9584 }
9585
9586 // Calculate the number of parameters from the method shorty. We add the
9587 // receiver count (0 or 1) and deduct one for the return value.
9588 uint32_t shorty_length;
9589 target_method->GetShorty(&shorty_length);
9590 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9591
Orion Hodsonecd58562018-09-24 11:27:33 +01009592 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009593 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009594 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9595 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9596 if (method_params.Get() == nullptr) {
9597 DCHECK(self->IsExceptionPending());
9598 return nullptr;
9599 }
9600
Orion Hodsonecd58562018-09-24 11:27:33 +01009601 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009602 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009603 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009604 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009605 // Insert receiver. Use the class identified in the method handle rather than the declaring
9606 // class of the resolved method which may be super class or default interface method
9607 // (b/115964401).
9608 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9609 // receiver_class should have been resolved when resolving the target method.
9610 DCHECK(receiver_class != nullptr);
9611 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009612 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009613
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009614 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009615 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009616 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009617 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009618 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009619 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009620 if (nullptr == klass) {
9621 DCHECK(self->IsExceptionPending());
9622 return nullptr;
9623 }
9624 method_params->Set(index++, klass);
9625 it.Next();
9626 }
9627
Orion Hodsonecd58562018-09-24 11:27:33 +01009628 Handle<mirror::Class> return_type =
9629 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009630 if (UNLIKELY(return_type.IsNull())) {
9631 DCHECK(self->IsExceptionPending());
9632 return nullptr;
9633 }
9634
9635 Handle<mirror::MethodType>
9636 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9637 if (UNLIKELY(method_type.IsNull())) {
9638 DCHECK(self->IsExceptionPending());
9639 return nullptr;
9640 }
9641
9642 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9643 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9644 Handle<mirror::MethodHandlesLookup> lookup =
9645 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9646 return lookup->FindConstructor(self, constructor_class, method_type);
9647 }
9648
9649 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9650 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9651}
9652
Vladimir Markoaf940202017-12-08 15:01:18 +00009653ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9654 uint32_t method_handle_idx,
9655 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009656 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009657 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009658 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009659 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9660 case DexFile::MethodHandleType::kStaticPut:
9661 case DexFile::MethodHandleType::kStaticGet:
9662 case DexFile::MethodHandleType::kInstancePut:
9663 case DexFile::MethodHandleType::kInstanceGet:
9664 return ResolveMethodHandleForField(self, method_handle, referrer);
9665 case DexFile::MethodHandleType::kInvokeStatic:
9666 case DexFile::MethodHandleType::kInvokeInstance:
9667 case DexFile::MethodHandleType::kInvokeConstructor:
9668 case DexFile::MethodHandleType::kInvokeDirect:
9669 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009670 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009671 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009672}
9673
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009674bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9675 return (entry_point == GetQuickResolutionStub()) ||
9676 (quick_resolution_trampoline_ == entry_point);
9677}
9678
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009679bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9680 return (entry_point == GetQuickToInterpreterBridge()) ||
9681 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9682}
9683
9684bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9685 return (entry_point == GetQuickGenericJniStub()) ||
9686 (quick_generic_jni_trampoline_ == entry_point);
9687}
9688
David Sehra49e0532017-08-25 08:05:29 -07009689bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009690 return entry_point == GetJniDlsymLookupStub() ||
9691 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009692}
9693
Vladimir Markofa458ac2020-02-12 14:08:07 +00009694bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9695 return entry_point == GetJniDlsymLookupCriticalStub() ||
9696 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9697}
9698
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009699const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9700 return GetQuickGenericJniStub();
9701}
9702
Mathieu Chartiere401d142015-04-22 13:56:20 -07009703void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009704 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009705 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9706 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009707 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009708 }
9709}
9710
Alex Lightdb01a092017-04-03 15:39:55 -07009711void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9712 DCHECK(method->IsObsolete());
9713 // We cannot mess with the entrypoints of native methods because they are used to determine how
9714 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9715 if (!method->IsNative()) {
9716 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9717 }
9718}
9719
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009720void ClassLinker::DumpForSigQuit(std::ostream& os) {
Hans Boehmfb3ad722021-08-16 16:53:17 +00009721 ScopedObjectAccess soa(Thread::Current());
9722 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009723 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9724 << NumNonZygoteClasses() << "\n";
Hans Boehmfb3ad722021-08-16 16:53:17 +00009725 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009726 os << "Dumping registered class loaders\n";
9727 size_t class_loader_index = 0;
9728 for (const ClassLoaderData& class_loader : class_loaders_) {
9729 ObjPtr<mirror::ClassLoader> loader =
Hans Boehmfb3ad722021-08-16 16:53:17 +00009730 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009731 if (loader != nullptr) {
9732 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9733 bool saw_one_dex_file = false;
9734 for (const DexCacheData& dex_cache : dex_caches_) {
9735 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9736 if (saw_one_dex_file) {
9737 os << ":";
9738 }
9739 saw_one_dex_file = true;
9740 os << dex_cache.dex_file->GetLocation();
9741 }
9742 }
9743 os << "]";
9744 bool found_parent = false;
9745 if (loader->GetParent() != nullptr) {
9746 size_t parent_index = 0;
9747 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9748 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
Hans Boehmfb3ad722021-08-16 16:53:17 +00009749 soa.Self()->DecodeJObject(class_loader2.weak_root));
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009750 if (loader2 == loader->GetParent()) {
9751 os << ", parent #" << parent_index;
9752 found_parent = true;
9753 break;
9754 }
9755 parent_index++;
9756 }
9757 if (!found_parent) {
9758 os << ", unregistered parent of type "
9759 << loader->GetParent()->GetClass()->PrettyDescriptor();
9760 }
9761 } else {
9762 os << ", no parent";
9763 }
9764 os << "\n";
9765 }
9766 }
9767 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009768 Runtime* runtime = Runtime::Current();
9769 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9770 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009771}
9772
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009773class CountClassesVisitor : public ClassLoaderVisitor {
9774 public:
9775 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9776
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009777 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009778 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009779 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009780 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009781 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9782 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009783 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009784 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009785
9786 size_t num_zygote_classes;
9787 size_t num_non_zygote_classes;
9788};
9789
9790size_t ClassLinker::NumZygoteClasses() const {
9791 CountClassesVisitor visitor;
9792 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009793 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009794}
9795
9796size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009797 CountClassesVisitor visitor;
9798 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009799 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009800}
9801
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009802size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009803 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009804 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009805 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009806}
9807
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009808pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009809 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009810}
9811
9812pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009813 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009814}
9815
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009816void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009817 DCHECK(!init_done_);
9818
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009819 DCHECK(klass != nullptr);
9820 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009821
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009822 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009823 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009824 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9825 int32_t index = static_cast<int32_t>(class_root);
9826 DCHECK(class_roots->Get(index) == nullptr);
9827 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009828}
9829
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009830ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9831 Thread* self,
9832 const std::vector<const DexFile*>& dex_files,
9833 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009834 Handle<mirror::ClassLoader> parent_loader,
9835 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009836
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009837 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009838
Mathieu Chartierc7853442015-03-27 14:35:38 -07009839 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009840 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009841
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009842 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009843 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009844 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009845 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009846 mirror::ObjectArray<mirror::Object>::Alloc(self,
9847 dex_elements_class.Get(),
9848 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009849 Handle<mirror::Class> h_dex_element_class =
9850 hs.NewHandle(dex_elements_class->GetComponentType());
9851
Mathieu Chartierc7853442015-03-27 14:35:38 -07009852 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009853 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009854 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009855
Andreas Gampe08883de2016-11-08 13:20:52 -08009856 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009857 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009858
Andreas Gampe08883de2016-11-08 13:20:52 -08009859 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009860 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009861
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009862 // Fill the elements array.
9863 int32_t index = 0;
9864 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009865 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009866
Calin Juravle7865ac72017-06-28 11:03:12 -07009867 // CreateWellKnownClassLoader is only used by gtests and compiler.
9868 // 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 -07009869 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9870 self,
9871 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009872 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009873 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009874
Mathieu Chartier3738e982017-05-12 16:07:28 -07009875 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9876 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009877 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009878 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009879 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009880 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009881
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009882 Handle<mirror::String> h_file_name = hs2.NewHandle(
9883 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009884 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009885 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9886
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009887 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009888 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009889 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009890
9891 h_dex_elements->Set(index, h_element.Get());
9892 index++;
9893 }
9894 DCHECK_EQ(index, h_dex_elements->GetLength());
9895
9896 // Create DexPathList.
9897 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009898 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009899 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009900 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009901 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009902 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9903 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9904 // elements.
9905 {
9906 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9907 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9908 DCHECK(native_lib_dirs != nullptr);
9909 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9910 DCHECK(list_class != nullptr);
9911 {
9912 StackHandleScope<1> h_list_scope(self);
9913 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9914 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9915 DCHECK(list_init);
9916 list_class = h_list_class.Get();
9917 }
9918 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9919 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9920 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9921 // normally never null), as long as one does not try to add elements, this will still
9922 // work.
9923 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9924 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009925
Calin Juravle7865ac72017-06-28 11:03:12 -07009926 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009927 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9928 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009929 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009930 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009931 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009932 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009933 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009934 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009935
9936 // Make a pretend boot-classpath.
9937 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009938 ArtField* const parent_field =
Vladimir Markoe300c4e2021-06-08 16:00:05 +01009939 jni::DecodeArtField(WellKnownClasses::java_lang_ClassLoader_parent);
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009940 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009941 if (parent_loader.Get() == nullptr) {
9942 ScopedObjectAccessUnchecked soa(self);
9943 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9944 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9945 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9946 } else {
9947 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9948 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009949
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009950 ArtField* shared_libraries_field =
9951 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9952 DCHECK(shared_libraries_field != nullptr);
9953 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9954
9955 return h_class_loader.Get();
9956}
9957
9958jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9959 const std::vector<const DexFile*>& dex_files,
9960 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009961 jobject parent_loader,
9962 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009963 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9964 WellKnownClasses::dalvik_system_PathClassLoader) ||
9965 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009966 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9967 self->GetJniEnv()->IsSameObject(loader_class,
9968 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009969
9970 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9971 // We could move the jobject to the callers, but all call-sites do this...
9972 ScopedObjectAccessUnchecked soa(self);
9973
9974 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009975 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009976
9977 Handle<mirror::Class> h_loader_class =
9978 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009979 Handle<mirror::ClassLoader> h_parent =
9980 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9981 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9982 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009983
9984 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9985 self,
9986 dex_files,
9987 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009988 h_parent,
9989 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009990
9991 // Make it a global ref and return.
9992 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009993 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009994 return soa.Env()->NewGlobalRef(local_ref.get());
9995}
9996
Calin Juravle7865ac72017-06-28 11:03:12 -07009997jobject ClassLinker::CreatePathClassLoader(Thread* self,
9998 const std::vector<const DexFile*>& dex_files) {
9999 return CreateWellKnownClassLoader(self,
10000 dex_files,
10001 WellKnownClasses::dalvik_system_PathClassLoader,
10002 nullptr);
10003}
10004
Andreas Gampe8ac75952015-06-02 21:01:45 -070010005void ClassLinker::DropFindArrayClassCache() {
10006 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
10007 find_array_class_cache_next_victim_ = 0;
10008}
10009
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010010void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010011 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010012 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -070010013 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010014 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
10015 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010016 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +010010017 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010018 }
10019 }
10020}
10021
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010022void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10023 for (const ClassLoaderData& data : class_loaders_) {
10024 LinearAlloc* alloc = data.allocator;
10025 if (alloc != nullptr && !visitor->Visit(alloc)) {
10026 break;
10027 }
10028 }
10029}
10030
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010031void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10032 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010033 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010034 Thread* const self = Thread::Current();
10035 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010036 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010037 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010038 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010039 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10040 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010041 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010042 }
10043}
10044
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010045void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010046 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010047 std::vector<ClassLoaderData> to_delete;
10048 // Do the delete outside the lock to avoid lock violation in jit code cache.
10049 {
10050 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10051 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10052 const ClassLoaderData& data = *it;
10053 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010054 ObjPtr<mirror::ClassLoader> class_loader =
10055 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010056 if (class_loader != nullptr) {
10057 ++it;
10058 } else {
10059 VLOG(class_linker) << "Freeing class loader";
10060 to_delete.push_back(data);
10061 it = class_loaders_.erase(it);
10062 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010063 }
10064 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010065 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010066 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010067 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010068 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010069}
10070
Mathieu Chartier65975772016-08-05 10:46:36 -070010071class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10072 public:
10073 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10074 : method_(method),
10075 pointer_size_(pointer_size) {}
10076
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010077 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010078 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10079 holder_ = klass;
10080 }
10081 // Return false to stop searching if holder_ is not null.
10082 return holder_ == nullptr;
10083 }
10084
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010085 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010086 const ArtMethod* const method_;
10087 const PointerSize pointer_size_;
10088};
10089
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010090ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010091 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10092 CHECK(method->IsCopied());
10093 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10094 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010095 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010096}
10097
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010098ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
10099 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010100 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +010010101 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010102 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010103}
10104
Vladimir Markod1f73512020-04-02 10:50:35 +010010105bool ClassLinker::IsUpdatableBootClassPathDescriptor(const char* descriptor ATTRIBUTE_UNUSED) {
10106 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10107 LOG(FATAL) << "UNREACHABLE";
10108 UNREACHABLE();
10109}
10110
Calin Juravle33787682019-07-26 14:27:18 -070010111bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10112 REQUIRES_SHARED(Locks::mutator_lock_) {
10113 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10114 LOG(FATAL) << "UNREACHABLE";
10115 UNREACHABLE();
10116}
10117
10118bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10119 REQUIRES_SHARED(Locks::mutator_lock_) {
10120 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10121 LOG(FATAL) << "UNREACHABLE";
10122 UNREACHABLE();
10123}
10124
10125bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10126 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10127 LOG(FATAL) << "UNREACHABLE";
10128 UNREACHABLE();
10129}
10130
Calin Juravle2c2724c2021-01-14 19:54:23 -080010131void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10132 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10133 LOG(FATAL) << "UNREACHABLE";
10134 UNREACHABLE();
10135}
10136
Roland Levillain0e840272018-08-23 19:55:30 +010010137// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +010010138template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010139 uint32_t method_idx,
10140 Handle<mirror::DexCache> dex_cache,
10141 Handle<mirror::ClassLoader> class_loader,
10142 ArtMethod* referrer,
10143 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +010010144template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010145 uint32_t method_idx,
10146 Handle<mirror::DexCache> dex_cache,
10147 Handle<mirror::ClassLoader> class_loader,
10148 ArtMethod* referrer,
10149 InvokeType type);
10150
Roland Levillain0e840272018-08-23 19:55:30 +010010151// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010152template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010153 Thread* self,
10154 ObjPtr<mirror::Class> java_lang_Class,
10155 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010156template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010157 Thread* self,
10158 ObjPtr<mirror::Class> java_lang_Class,
10159 uint32_t class_size);
10160
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010161} // namespace art