blob: acc17e1084c4a6b94fe183730431ea901bcaa2b9 [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
Nicolas Geoffray00391822019-12-10 10:17:23 +0000154#include "interpreter/interpreter_mterp_impl.h"
155
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700156namespace art {
157
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800158using android::base::StringPrintf;
159
Orion Hodson5880c772020-07-28 20:12:08 +0100160static constexpr bool kCheckImageObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700161static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700162
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700163static void ThrowNoClassDefFoundError(const char* fmt, ...)
164 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700165 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700166static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700167 va_list args;
168 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800169 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000170 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800171 va_end(args);
172}
173
Andreas Gampe99babb62015-11-02 16:20:00 -0800174static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700175 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700176 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700177 StackHandleScope<1> hs(self);
178 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700179 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700180 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700181
182 if (exception_class == nullptr) {
183 // No exc class ~ no <init>-with-string.
184 CHECK(self->IsExceptionPending());
185 self->ClearException();
186 return false;
187 }
188
Vladimir Markoba118822017-06-12 15:41:56 +0100189 ArtMethod* exception_init_method = exception_class->FindConstructor(
190 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700191 return exception_init_method != nullptr;
192}
193
Vladimir Markobb206de2019-03-28 10:30:32 +0000194static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700195 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700196 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
197 if (ext == nullptr) {
198 return nullptr;
199 } else {
200 return ext->GetVerifyError();
201 }
202}
203
204// Helper for ThrowEarlierClassFailure. Throws the stored error.
205static void HandleEarlierVerifyError(Thread* self,
206 ClassLinker* class_linker,
207 ObjPtr<mirror::Class> c)
208 REQUIRES_SHARED(Locks::mutator_lock_) {
209 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800210 DCHECK(obj != nullptr);
211 self->AssertNoPendingException();
212 if (obj->IsClass()) {
213 // Previous error has been stored as class. Create a new exception of that type.
214
215 // It's possible the exception doesn't have a <init>(String).
216 std::string temp;
217 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
218
219 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700220 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800221 } else {
222 self->ThrowNewException(descriptor, nullptr);
223 }
224 } else {
225 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100226 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700227 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800228 CHECK(throwable_class->IsAssignableFrom(error_class));
229 self->SetException(obj->AsThrowable());
230 }
231 self->AssertPendingException();
232}
233
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000234static void ChangeInterpreterBridgeToNterp(ArtMethod* method, ClassLinker* class_linker)
235 REQUIRES_SHARED(Locks::mutator_lock_) {
236 Runtime* runtime = Runtime::Current();
237 if (class_linker->IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode()) &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000238 CanMethodUseNterp(method)) {
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000239 if (method->GetDeclaringClass()->IsVisiblyInitialized() ||
240 !NeedsClinitCheckBeforeCall(method)) {
241 runtime->GetInstrumentation()->UpdateMethodsCode(method, interpreter::GetNterpEntryPoint());
242 } else {
243 // Put the resolution stub, which will initialize the class and then
244 // call the method with nterp.
245 runtime->GetInstrumentation()->UpdateMethodsCode(method, GetQuickResolutionStub());
246 }
247 }
248}
249
Andreas Gampe5b20b352018-10-11 19:03:20 -0700250// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
251// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
252// before.
Andreas Gampe5b20b352018-10-11 19:03:20 -0700253static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
254 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000255 Runtime* runtime = Runtime::Current();
256 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampe5b20b352018-10-11 19:03:20 -0700257 if (!klass->WasVerificationAttempted()) {
258 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
259 klass->SetVerificationAttempted();
Nicolas Geoffray00391822019-12-10 10:17:23 +0000260 // Now that the class has passed verification, try to set nterp entrypoints
261 // to methods that currently use the switch interpreter.
262 if (interpreter::CanRuntimeUseNterp()) {
263 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000264 ChangeInterpreterBridgeToNterp(&m, class_linker);
Nicolas Geoffray00391822019-12-10 10:17:23 +0000265 }
266 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700267 }
268}
269
Vladimir Markobf121912019-06-04 13:49:05 +0100270// Callback responsible for making a batch of classes visibly initialized
271// after all threads have called it from a checkpoint, ensuring visibility.
272class ClassLinker::VisiblyInitializedCallback final
273 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
274 public:
275 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
276 : class_linker_(class_linker),
277 num_classes_(0u),
278 thread_visibility_counter_(0),
279 barriers_() {
280 std::fill_n(classes_, kMaxClasses, nullptr);
281 }
282
283 bool IsEmpty() const {
284 DCHECK_LE(num_classes_, kMaxClasses);
285 return num_classes_ == 0u;
286 }
287
288 bool IsFull() const {
289 DCHECK_LE(num_classes_, kMaxClasses);
290 return num_classes_ == kMaxClasses;
291 }
292
293 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
294 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
295 DCHECK(!IsFull());
296 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
297 ++num_classes_;
298 }
299
300 void AddBarrier(Barrier* barrier) {
301 barriers_.push_front(barrier);
302 }
303
304 std::forward_list<Barrier*> GetAndClearBarriers() {
305 std::forward_list<Barrier*> result;
306 result.swap(barriers_);
307 result.reverse(); // Return barriers in insertion order.
308 return result;
309 }
310
311 void MakeVisible(Thread* self) {
312 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
313 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
314 AdjustThreadVisibilityCounter(self, count);
315 }
316
317 void Run(Thread* self) override {
318 self->ClearMakeVisiblyInitializedCounter();
319 AdjustThreadVisibilityCounter(self, -1);
320 }
321
322 private:
323 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
324 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
325 if (old + adjustment == 0) {
326 // All threads passed the checkpoint. Mark classes as visibly initialized.
327 {
328 ScopedObjectAccess soa(self);
329 StackHandleScope<1u> hs(self);
330 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
331 JavaVMExt* vm = self->GetJniEnv()->GetVm();
332 for (size_t i = 0, num = num_classes_; i != num; ++i) {
333 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
334 vm->DeleteWeakGlobalRef(self, classes_[i]);
335 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100336 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100337 class_linker_->FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100338 }
339 }
340 num_classes_ = 0u;
341 }
342 class_linker_->VisiblyInitializedCallbackDone(self, this);
343 }
344 }
345
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100346 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100347
348 ClassLinker* const class_linker_;
349 size_t num_classes_;
350 jweak classes_[kMaxClasses];
351
352 // The thread visibility counter starts at 0 and it is incremented by the number of
353 // threads that need to run this callback (by the thread that request the callback
354 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
355 // whether after the increment or after a decrement, we know that `Run()` was executed
356 // for all threads and therefore we can mark the classes as visibly initialized.
357 std::atomic<ssize_t> thread_visibility_counter_;
358
359 // List of barries to `Pass()` for threads that wait for the callback to complete.
360 std::forward_list<Barrier*> barriers_;
361};
362
363void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
364 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
365 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
366 }
367 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
368 if (wait) {
369 maybe_barrier.emplace(0);
370 }
371 int wait_count = 0;
372 VisiblyInitializedCallback* callback = nullptr;
373 {
374 MutexLock lock(self, visibly_initialized_callback_lock_);
375 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
376 callback = visibly_initialized_callback_.release();
377 running_visibly_initialized_callbacks_.push_front(*callback);
378 }
379 if (wait) {
380 DCHECK(maybe_barrier.has_value());
381 Barrier* barrier = std::addressof(*maybe_barrier);
382 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
383 cb.AddBarrier(barrier);
384 ++wait_count;
385 }
386 }
387 }
388 if (callback != nullptr) {
389 callback->MakeVisible(self);
390 }
391 if (wait_count != 0) {
392 DCHECK(maybe_barrier.has_value());
393 maybe_barrier->Increment(self, wait_count);
394 }
395}
396
397void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
398 VisiblyInitializedCallback* callback) {
399 MutexLock lock(self, visibly_initialized_callback_lock_);
400 // Pass the barriers if requested.
401 for (Barrier* barrier : callback->GetAndClearBarriers()) {
402 barrier->Pass(self);
403 }
404 // Remove the callback from the list of running callbacks.
405 auto before = running_visibly_initialized_callbacks_.before_begin();
406 auto it = running_visibly_initialized_callbacks_.begin();
407 DCHECK(it != running_visibly_initialized_callbacks_.end());
408 while (std::addressof(*it) != callback) {
409 before = it;
410 ++it;
411 DCHECK(it != running_visibly_initialized_callbacks_.end());
412 }
413 running_visibly_initialized_callbacks_.erase_after(before);
414 // Reuse or destroy the callback object.
415 if (visibly_initialized_callback_ == nullptr) {
416 visibly_initialized_callback_.reset(callback);
417 } else {
418 delete callback;
419 }
420}
421
Alex Lightfb119572019-09-18 15:04:53 -0700422void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
423 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
424 if (cb != nullptr) {
425 cb->MakeVisible(self);
426 }
427 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
428 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
429}
430
Vladimir Markobf121912019-06-04 13:49:05 +0100431ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
432 Thread* self, Handle<mirror::Class> klass) {
433 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
434 // Thanks to the x86 memory model, we do not need any memory fences and
435 // we can immediately mark the class as visibly initialized.
436 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100437 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100438 return nullptr;
439 }
440 if (Runtime::Current()->IsActiveTransaction()) {
441 // Transactions are single-threaded, so we can mark the class as visibly intialized.
442 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
443 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100444 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100445 return nullptr;
446 }
447 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
448 MutexLock lock(self, visibly_initialized_callback_lock_);
449 if (visibly_initialized_callback_ == nullptr) {
450 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
451 }
452 DCHECK(!visibly_initialized_callback_->IsFull());
453 visibly_initialized_callback_->AddClass(self, klass.Get());
454
455 if (visibly_initialized_callback_->IsFull()) {
456 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
457 running_visibly_initialized_callbacks_.push_front(*callback);
458 return callback;
459 } else {
460 return nullptr;
461 }
462}
463
Vladimir Marko86c87522020-05-11 16:55:55 +0100464const void* ClassLinker::RegisterNative(
465 Thread* self, ArtMethod* method, const void* native_method) {
466 CHECK(method->IsNative()) << method->PrettyMethod();
467 CHECK(native_method != nullptr) << method->PrettyMethod();
468 void* new_native_method = nullptr;
469 Runtime* runtime = Runtime::Current();
470 runtime->GetRuntimeCallbacks()->RegisterNativeMethod(method,
471 native_method,
472 /*out*/&new_native_method);
473 if (method->IsCriticalNative()) {
474 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
475 // Remove old registered method if any.
476 auto it = critical_native_code_with_clinit_check_.find(method);
477 if (it != critical_native_code_with_clinit_check_.end()) {
478 critical_native_code_with_clinit_check_.erase(it);
479 }
480 // To ensure correct memory visibility, we need the class to be visibly
481 // initialized before we can set the JNI entrypoint.
482 if (method->GetDeclaringClass()->IsVisiblyInitialized()) {
483 method->SetEntryPointFromJni(new_native_method);
484 } else {
485 critical_native_code_with_clinit_check_.emplace(method, new_native_method);
486 }
487 } else {
488 method->SetEntryPointFromJni(new_native_method);
489 }
490 return new_native_method;
491}
492
493void ClassLinker::UnregisterNative(Thread* self, ArtMethod* method) {
494 CHECK(method->IsNative()) << method->PrettyMethod();
495 // Restore stub to lookup native pointer via dlsym.
496 if (method->IsCriticalNative()) {
497 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
498 auto it = critical_native_code_with_clinit_check_.find(method);
499 if (it != critical_native_code_with_clinit_check_.end()) {
500 critical_native_code_with_clinit_check_.erase(it);
501 }
502 method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
503 } else {
504 method->SetEntryPointFromJni(GetJniDlsymLookupStub());
505 }
506}
507
508const void* ClassLinker::GetRegisteredNative(Thread* self, ArtMethod* method) {
509 if (method->IsCriticalNative()) {
510 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
511 auto it = critical_native_code_with_clinit_check_.find(method);
512 if (it != critical_native_code_with_clinit_check_.end()) {
513 return it->second;
514 }
515 const void* native_code = method->GetEntryPointFromJni();
516 return IsJniDlsymLookupCriticalStub(native_code) ? nullptr : native_code;
517 } else {
518 const void* native_code = method->GetEntryPointFromJni();
519 return IsJniDlsymLookupStub(native_code) ? nullptr : native_code;
520 }
521}
522
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800523void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
524 bool wrap_in_no_class_def,
525 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700526 // The class failed to initialize on a previous attempt, so we want to throw
527 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
528 // failed in verification, in which case v2 5.4.1 says we need to re-throw
529 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800530 Runtime* const runtime = Runtime::Current();
531 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700532 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000533 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
534 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800535 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700536 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800537 } else {
538 extra = verify_error->AsThrowable()->Dump();
539 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700540 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800541 if (log) {
542 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
543 << ": " << extra;
544 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700545 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700546
David Sehr709b0702016-10-13 09:12:37 -0700547 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800548 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800549 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700550 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700551 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000552 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700553 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000554 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
555 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800556 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800557 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800558 }
Alex Lightd6251582016-10-31 11:12:30 -0700559 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
560 // might have meant to go down the earlier if statement with the original error but it got
561 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000562 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800563 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
564 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
565 // exception will be a cause.
566 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700567 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700568 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700569 }
570}
571
Brian Carlstromb23eab12014-10-08 17:55:21 -0700572static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700573 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700574 if (VLOG_IS_ON(class_linker)) {
575 std::string temp;
576 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000577 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700578 }
579}
580
581static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700582 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700583 Thread* self = Thread::Current();
584 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700585
586 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700587 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700588
David Srbecky346fd962020-07-27 16:51:00 +0100589 // Boot classpath classes should not fail initialization. This is a consistency debug check.
590 // This cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800591 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800592 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800593 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
594 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
595 // could have caused the error.
596 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
597 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
598 << " failed initialization: "
599 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800600 }
601
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700602 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700603 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
604 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700605
Elliott Hughesa4f94742012-05-29 16:28:38 -0700606 // We only wrap non-Error exceptions; an Error can just be used as-is.
607 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000608 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700609 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700610 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700611}
612
Andreas Gampe87658f32019-04-18 18:39:02 +0000613ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700614 : boot_class_table_(new ClassTable()),
615 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800616 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800617 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700618 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000619 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700620 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000621 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000622 jni_dlsym_lookup_trampoline_(nullptr),
Vladimir Markofa458ac2020-02-12 14:08:07 +0000623 jni_dlsym_lookup_critical_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800624 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800625 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100626 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800627 quick_to_interpreter_bridge_trampoline_(nullptr),
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000628 nterp_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700629 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100630 visibly_initialized_callback_lock_("visibly initialized callback lock"),
631 visibly_initialized_callback_(nullptr),
Vladimir Marko86c87522020-05-11 16:55:55 +0100632 critical_native_code_with_clinit_check_lock_("critical native code with clinit check lock"),
633 critical_native_code_with_clinit_check_(),
Andreas Gampe7dface32017-07-25 21:32:59 -0700634 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
635 // For CHA disabled during Aot, see b/34193647.
636
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700637 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700638 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
639 "Array cache size wrong.");
640 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700641}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700642
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800643void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700644 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800645 if (c2 == nullptr) {
646 LOG(FATAL) << "Could not find class " << descriptor;
647 UNREACHABLE();
648 }
649 if (c1.Get() != c2) {
650 std::ostringstream os1, os2;
651 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
652 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
653 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
654 << ". This is most likely the result of a broken build. Make sure that "
655 << "libcore and art projects match.\n\n"
656 << os1.str() << "\n\n" << os2.str();
657 UNREACHABLE();
658 }
659}
660
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800661bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
662 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800663 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700664
Mathieu Chartiere401d142015-04-22 13:56:20 -0700665 Thread* const self = Thread::Current();
666 Runtime* const runtime = Runtime::Current();
667 gc::Heap* const heap = runtime->GetHeap();
668
Jeff Haodcdc85b2015-12-04 14:06:18 -0800669 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700670 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700671
Mathieu Chartiere401d142015-04-22 13:56:20 -0700672 // Use the pointer size from the runtime since we are probably creating the image.
673 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
674
Elliott Hughes30646832011-10-13 16:59:46 -0700675 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700676 // 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 -0800677 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700678 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700679 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700680 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
681 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000682 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100683 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800684 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100685 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700686 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700687 if (kUseBakerReadBarrier) {
688 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800689 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700690 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700691 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800692 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700693 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700694
Elliott Hughes418d20f2011-09-22 14:00:39 -0700695 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700696 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700697 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700698 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700699 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700700
Ian Rogers23435d02012-09-24 11:23:12 -0700701 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700702 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700703 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800704 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700705 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700706 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000707 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700708
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700709 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800710 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
711 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100712 runtime->SetSentinel(heap->AllocNonMovableObject(self,
713 java_lang_Object.Get(),
714 java_lang_Object->GetObjectSize(),
715 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700716
Igor Murashkin86083f72017-10-27 10:59:04 -0700717 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000718 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700719 // It might seem the lock here is unnecessary, however all the SubtypeCheck
720 // functions are annotated to require locks all the way down.
721 //
722 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
723 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000724 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
725 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700726 }
727
Ian Rogers23435d02012-09-24 11:23:12 -0700728 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700729 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700730 AllocClass(self, java_lang_Class.Get(),
731 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700732 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700733
Roland Levillain0e840272018-08-23 19:55:30 +0100734 // Setup java.lang.String.
735 //
736 // We make this class non-movable for the unlikely case where it were to be
737 // moved by a sticky-bit (minor) collection when using the Generational
738 // Concurrent Copying (CC) collector, potentially creating a stale reference
739 // in the `klass_` field of one of its instances allocated in the Large-Object
740 // Space (LOS) -- see the comment about the dirty card scanning logic in
741 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700742 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700743 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100744 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700745 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000746 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400747
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700748 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700749 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700750 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700751 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000752 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700753
Ian Rogers23435d02012-09-24 11:23:12 -0700754 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700755 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100756 mirror::ObjectArray<mirror::Class>::Alloc(self,
757 object_array_class.Get(),
758 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700759 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100760 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
761 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
762 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
763 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100764 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
765 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700766
Mathieu Chartier6beced42016-11-15 15:51:31 -0800767 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
768 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
769
Vladimir Marko02610552018-06-04 14:38:00 +0100770 // Create array interface entries to populate once we can load system classes.
771 object_array_class->SetIfTable(AllocIfTable(self, 2));
772 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
773
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700774 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100775 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
776 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
777 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
778 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
779 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
780 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
781 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
782 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
783 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700784
Vladimir Marko70e2a762019-07-12 16:49:00 +0100785 // Allocate the primitive array classes. We need only the native pointer
786 // array at this point (int[] or long[], depending on architecture) but
787 // we shall perform the same setup steps for all primitive array classes.
788 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
789 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
790 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
791 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
792 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
793 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
794 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
795 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700796
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700797 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700798
Ian Rogers52813c92012-10-11 11:50:38 -0700799 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700800 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700801 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100802 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100803 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700804 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000805 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700806
Alex Lightd6251582016-10-31 11:12:30 -0700807
808 // Setup dalvik.system.ClassExt
809 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
810 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100811 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000812 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700813
Mathieu Chartier66f19252012-09-18 08:57:04 -0700814 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700815 Handle<mirror::Class> object_array_string(hs.NewHandle(
816 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700817 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700818 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100819 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700820
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000821 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700822 // Create runtime resolution and imt conflict methods.
823 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000824 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
825 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700826
Ian Rogers23435d02012-09-24 11:23:12 -0700827 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
828 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
829 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800830 if (boot_class_path.empty()) {
831 *error_msg = "Boot classpath is empty.";
832 return false;
833 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800834 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800835 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800836 *error_msg = "Null dex file.";
837 return false;
838 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800839 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800840 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700841 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700842
843 // now we can use FindSystemClass
844
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700845 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
846 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700847 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800848 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700849 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000850 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Vladimir Markofa458ac2020-02-12 14:08:07 +0000851 jni_dlsym_lookup_critical_trampoline_ = GetJniDlsymLookupCriticalStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700852 quick_resolution_trampoline_ = GetQuickResolutionStub();
853 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000854 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700855 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000856 nterp_trampoline_ = interpreter::GetNterpEntryPoint();
Alex Light64ad14d2014-08-19 14:23:13 -0700857 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700858
Alex Lightd6251582016-10-31 11:12:30 -0700859 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000860 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800861 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700862 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000863 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800864 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000865 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800866 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700867 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000868 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700869 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
870 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700871
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800872 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
873 // in class_table_.
874 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700875
Vladimir Marko70e2a762019-07-12 16:49:00 +0100876 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
877 // arrays - can't be done until Object has a vtable and component classes are loaded.
878 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
879 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
880 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
881 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
882 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
883 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
884 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
885 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
886 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
887 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
888 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700889
Ian Rogers23435d02012-09-24 11:23:12 -0700890 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700891 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800892 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700893 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800894 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700895 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
896 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100897 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
898 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700899
Vladimir Markob10668c2021-06-10 09:52:53 +0100900 // Check Class[] and Object[]'s interfaces.
901 CHECK_EQ(java_lang_Cloneable.Get(), class_array_class->GetDirectInterface(0));
902 CHECK_EQ(java_io_Serializable.Get(), class_array_class->GetDirectInterface(1));
903 CHECK_EQ(java_lang_Cloneable.Get(), object_array_class->GetDirectInterface(0));
904 CHECK_EQ(java_io_Serializable.Get(), object_array_class->GetDirectInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700905
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700906 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100907 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700908
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800909 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700910
Ian Rogers23435d02012-09-24 11:23:12 -0700911 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100912 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
913 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700914
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700915 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100916 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700917 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100918 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700919
920 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700921 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
922 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100923 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700924
925 // Create java.lang.reflect.Constructor.class root and array root.
926 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
927 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100928 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700929 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
930 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100931 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700932
933 // Create java.lang.reflect.Method.class root and array root.
934 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
935 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100936 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700937 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
938 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100939 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700940
Orion Hodson005ac512017-10-24 15:43:43 +0100941 // Create java.lang.invoke.CallSite.class root
942 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
943 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100944 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100945
Narayan Kamathafa48272016-08-03 12:46:58 +0100946 // Create java.lang.invoke.MethodType.class root
947 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
948 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100949 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100950
951 // Create java.lang.invoke.MethodHandleImpl.class root
952 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
953 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100954 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100955 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100956
Orion Hodsonc069a302017-01-18 09:23:12 +0000957 // Create java.lang.invoke.MethodHandles.Lookup.class root
958 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
959 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100960 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000961
Orion Hodson005ac512017-10-24 15:43:43 +0100962 // Create java.lang.invoke.VarHandle.class root
963 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000964 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100965 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100966
967 // Create java.lang.invoke.FieldVarHandle.class root
968 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
969 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100970 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100971
972 // Create java.lang.invoke.ArrayElementVarHandle.class root
973 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
974 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100975 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100976
977 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
978 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
979 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100980 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100981
982 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
983 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
984 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100985 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000986
Narayan Kamath000e1882016-10-24 17:14:25 +0100987 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
988 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100989 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100990
Brian Carlstrom1f870082011-08-23 16:02:11 -0700991 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700992 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000993 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800994 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700995 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700996 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
997 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700998 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700999 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001000 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001001 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001002 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001003 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001004 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001005 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001006 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001007 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001008 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001009 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001010
Ian Rogers23435d02012-09-24 11:23:12 -07001011 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001012 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001013 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001014 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001015 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001016
jeffhao8cd6dda2012-02-22 10:15:34 -08001017 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -07001018 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001019 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001020 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -07001021 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001022 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
1023 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
1024 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001025 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001026 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1027 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001028
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001029 // Create conflict tables that depend on the class linker.
1030 runtime->FixupConflictTables();
1031
Ian Rogers98379392014-02-24 16:53:16 -08001032 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001033
Brian Carlstroma004aa92012-02-08 18:05:09 -08001034 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001035
1036 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001037}
1038
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001039static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1040 REQUIRES_SHARED(Locks::mutator_lock_) {
1041 // Find String.<init> -> StringFactory bindings.
1042 ObjPtr<mirror::Class> string_factory_class =
1043 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1044 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001045 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001046 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1047 // Update the primordial thread.
1048 self->InitStringEntryPoints();
1049}
1050
Ian Rogers98379392014-02-24 16:53:16 -08001051void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001052 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001053
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001054 CreateStringInitBindings(self, this);
1055
Brian Carlstrom16192862011-09-12 17:50:06 -07001056 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001057 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001058 // as the types of the field can't be resolved prior to the runtime being
1059 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001060 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001061 Handle<mirror::Class> java_lang_ref_Reference =
1062 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001063 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1064 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001065
Mathieu Chartierc7853442015-03-27 14:35:38 -07001066 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001067 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1068 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001069
Mathieu Chartierc7853442015-03-27 14:35:38 -07001070 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001071 CHECK_STREQ(queue->GetName(), "queue");
1072 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001073
Mathieu Chartierc7853442015-03-27 14:35:38 -07001074 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001075 CHECK_STREQ(queueNext->GetName(), "queueNext");
1076 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001077
Mathieu Chartierc7853442015-03-27 14:35:38 -07001078 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001079 CHECK_STREQ(referent->GetName(), "referent");
1080 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001081
Mathieu Chartierc7853442015-03-27 14:35:38 -07001082 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001083 CHECK_STREQ(zombie->GetName(), "zombie");
1084 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001085
Brian Carlstroma663ea52011-08-19 23:33:41 -07001086 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001087 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001088 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001089 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001090 CHECK(klass != nullptr);
1091 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001092 // note SetClassRoot does additional validation.
1093 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001094 }
1095
Vladimir Marko02610552018-06-04 14:38:00 +01001096 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001097
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001098 // disable the slow paths in FindClass and CreatePrimitiveClass now
1099 // that Object, Class, and Object[] are setup
1100 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001101
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001102 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1103 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1104 // ensure that the class will be initialized.
1105 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001106 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001107
1108 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1109 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1110 // Strange, but don't crash.
1111 LOG(WARNING) << "Could not prepare StackOverflowError.";
1112 self->ClearException();
1113 }
1114 }
1115
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001116 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001117}
1118
Vladimir Markodcfcce42018-06-27 10:00:28 +00001119void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001120 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1121 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001122 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001123 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001124 Handle<mirror::Class> h_class(hs.NewHandle(c));
David Srbecky08110ef2020-05-20 19:33:43 +01001125 if (!EnsureInitialized(self, h_class, true, true)) {
1126 LOG(FATAL) << "Exception when initializing " << h_class->PrettyClass()
1127 << ": " << self->GetException()->Dump();
1128 }
Vladimir Markodcfcce42018-06-27 10:00:28 +00001129 } else {
1130 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001131 }
1132 }
1133}
1134
Vladimir Marko43354742021-02-03 15:37:01 +00001135static void InitializeObjectVirtualMethodHashes(ObjPtr<mirror::Class> java_lang_Object,
1136 PointerSize pointer_size,
1137 /*out*/ ArrayRef<uint32_t> virtual_method_hashes)
1138 REQUIRES_SHARED(Locks::mutator_lock_) {
1139 ArraySlice<ArtMethod> virtual_methods = java_lang_Object->GetVirtualMethods(pointer_size);
1140 DCHECK_EQ(virtual_method_hashes.size(), virtual_methods.size());
1141 for (size_t i = 0; i != virtual_method_hashes.size(); ++i) {
1142 const char* name = virtual_methods[i].GetName();
1143 virtual_method_hashes[i] = ComputeModifiedUtf8Hash(name);
1144 }
1145}
1146
Jeff Haodcdc85b2015-12-04 14:06:18 -08001147struct TrampolineCheckData {
1148 const void* quick_resolution_trampoline;
1149 const void* quick_imt_conflict_trampoline;
1150 const void* quick_generic_jni_trampoline;
1151 const void* quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001152 const void* nterp_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001153 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001154 ArtMethod* m;
1155 bool error;
1156};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001157
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001158bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1159 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001160 CHECK(!init_done_);
1161
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001162 Runtime* const runtime = Runtime::Current();
1163 Thread* const self = Thread::Current();
1164 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001165 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1166 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001167 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1168 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001169 if (!ValidPointerSize(pointer_size_unchecked)) {
1170 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001171 return false;
1172 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001173 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001174 if (!runtime->IsAotCompiler()) {
1175 // Only the Aot compiler supports having an image with a different pointer size than the
1176 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1177 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001178 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001179 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001180 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001181 sizeof(void*));
1182 return false;
1183 }
1184 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001185 DCHECK(!runtime->HasResolutionMethod());
1186 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1187 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1188 runtime->SetImtUnimplementedMethod(
1189 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1190 runtime->SetCalleeSaveMethod(
1191 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1192 CalleeSaveType::kSaveAllCalleeSaves);
1193 runtime->SetCalleeSaveMethod(
1194 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1195 CalleeSaveType::kSaveRefsOnly);
1196 runtime->SetCalleeSaveMethod(
1197 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1198 CalleeSaveType::kSaveRefsAndArgs);
1199 runtime->SetCalleeSaveMethod(
1200 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1201 CalleeSaveType::kSaveEverything);
1202 runtime->SetCalleeSaveMethod(
1203 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1204 CalleeSaveType::kSaveEverythingForClinit);
1205 runtime->SetCalleeSaveMethod(
1206 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1207 CalleeSaveType::kSaveEverythingForSuspendCheck);
1208
Jeff Haodcdc85b2015-12-04 14:06:18 -08001209 std::vector<const OatFile*> oat_files =
1210 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1211 DCHECK(!oat_files.empty());
1212 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001213 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001214 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001215 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1216 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1217 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1218 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001219 nterp_trampoline_ = default_oat_header.GetNterpTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001220 if (kIsDebugBuild) {
1221 // Check that the other images use the same trampoline.
1222 for (size_t i = 1; i < oat_files.size(); ++i) {
1223 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001224 const void* ith_jni_dlsym_lookup_trampoline_ =
1225 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001226 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1227 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001228 const void* ith_quick_resolution_trampoline =
1229 ith_oat_header.GetQuickResolutionTrampoline();
1230 const void* ith_quick_imt_conflict_trampoline =
1231 ith_oat_header.GetQuickImtConflictTrampoline();
1232 const void* ith_quick_generic_jni_trampoline =
1233 ith_oat_header.GetQuickGenericJniTrampoline();
1234 const void* ith_quick_to_interpreter_bridge_trampoline =
1235 ith_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001236 const void* ith_nterp_trampoline =
1237 ith_oat_header.GetNterpTrampoline();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001238 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001239 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001240 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001241 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1242 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001243 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_ ||
1244 ith_nterp_trampoline != nterp_trampoline_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001245 // Make sure that all methods in this image do not contain those trampolines as
1246 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1247 TrampolineCheckData data;
1248 data.error = false;
1249 data.pointer_size = GetImagePointerSize();
1250 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1251 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1252 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1253 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001254 data.nterp_trampoline = ith_nterp_trampoline;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001255 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001256 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1257 if (obj->IsClass()) {
1258 ObjPtr<mirror::Class> klass = obj->AsClass();
1259 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1260 const void* entrypoint =
1261 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1262 if (entrypoint == data.quick_resolution_trampoline ||
1263 entrypoint == data.quick_imt_conflict_trampoline ||
1264 entrypoint == data.quick_generic_jni_trampoline ||
1265 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1266 data.m = &m;
1267 data.error = true;
1268 return;
1269 }
1270 }
1271 }
1272 };
1273 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001274 if (data.error) {
1275 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001276 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001277 *error_msg = "Found an ArtMethod with a bad entrypoint";
1278 return false;
1279 }
1280 }
1281 }
1282 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001283
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001284 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001285 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001286 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001287 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001288
Vladimir Marko024d69f2019-06-13 10:52:32 +01001289 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1290 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1291 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1292 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1293 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1294 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001295
Vladimir Markod1908512018-11-22 14:57:28 +00001296 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001297 // Boot class loader, use a null handle.
1298 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001299 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001300 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001301 /*out*/&dex_files,
1302 error_msg)) {
1303 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001304 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001305 // Append opened dex files at the end.
1306 boot_dex_files_.insert(boot_dex_files_.end(),
1307 std::make_move_iterator(dex_files.begin()),
1308 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001309 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001310 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1311 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1312 }
Vladimir Marko43354742021-02-03 15:37:01 +00001313 InitializeObjectVirtualMethodHashes(GetClassRoot<mirror::Object>(this),
1314 image_pointer_size_,
1315 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Ian Rogers98379392014-02-24 16:53:16 -08001316 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001317
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001318 VLOG(startup) << __FUNCTION__ << " exiting";
1319 return true;
1320}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001321
Vladimir Marko4433c432018-12-04 14:57:47 +00001322void ClassLinker::AddExtraBootDexFiles(
1323 Thread* self,
1324 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1325 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001326 AppendToBootClassPath(self, dex_file.get());
Orion Hodson771708f2021-01-06 15:45:16 +00001327 if (kIsDebugBuild) {
1328 for (const auto& boot_dex_file : boot_dex_files_) {
1329 DCHECK_NE(boot_dex_file->GetLocation(), dex_file->GetLocation());
1330 }
1331 }
Vladimir Marko4433c432018-12-04 14:57:47 +00001332 boot_dex_files_.push_back(std::move(dex_file));
1333 }
1334}
1335
Jeff Hao5872d7c2016-04-27 11:07:41 -07001336bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001337 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001338 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001339 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1340 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001341}
1342
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001343class CHAOnDeleteUpdateClassVisitor {
1344 public:
1345 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1346 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1347 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1348 self_(Thread::Current()) {}
1349
1350 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1351 // This class is going to be unloaded. Tell CHA about it.
1352 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1353 return true;
1354 }
1355 private:
1356 const LinearAlloc* allocator_;
1357 const ClassHierarchyAnalysis* cha_;
1358 const PointerSize pointer_size_;
1359 const Thread* self_;
1360};
1361
Chris Wailes0c61be42018-09-26 17:27:34 -07001362/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001363 * A class used to ensure that all references to strings interned in an AppImage have been
1364 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001365 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001366class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001367 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001368 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1369 const InternTable::UnorderedSet& image_interns)
1370 : space_(space),
1371 image_interns_(image_interns),
1372 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001373
Chris Wailes0c61be42018-09-26 17:27:34 -07001374 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001375 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001376 if (referred_obj != nullptr &&
1377 space_.HasAddress(referred_obj.Ptr()) &&
1378 referred_obj->IsString()) {
1379 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001380 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1381 if (it != image_interns_.end() && it->Read() == referred_str) {
1382 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001383 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001384 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001385 }
1386
Chris Wailes0c61be42018-09-26 17:27:34 -07001387 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001388 mirror::CompressedReference<mirror::Object>* root) const
1389 REQUIRES_SHARED(Locks::mutator_lock_) {
1390 if (!root->IsNull()) {
1391 VisitRoot(root);
1392 }
1393 }
1394
Chris Wailes0c61be42018-09-26 17:27:34 -07001395 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001396 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001397 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001398 }
1399
1400 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001401 void operator()(ObjPtr<mirror::Object> obj,
1402 MemberOffset offset,
1403 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001404 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001405 // References within image or across images don't need a read barrier.
1406 ObjPtr<mirror::Object> referred_obj =
1407 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1408 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001409 }
1410
1411 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1412 ObjPtr<mirror::Reference> ref) const
1413 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001414 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001415 }
1416
Vladimir Marko8e05f092019-06-10 11:10:38 +01001417 size_t GetCount() const {
1418 return count_;
1419 }
1420
1421 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001422 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001423 const InternTable::UnorderedSet& image_interns_;
1424 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001425};
1426
Chris Wailes0c61be42018-09-26 17:27:34 -07001427/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001428 * This function counts references to strings interned in the AppImage.
1429 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001430 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001431size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1432 const InternTable::UnorderedSet& image_interns)
1433 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001434 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1435 const ImageHeader& image_header = space.GetImageHeader();
1436 const uint8_t* target_base = space.GetMemMap()->Begin();
1437 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001438
1439 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1440 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001441
Vladimir Marko8e05f092019-06-10 11:10:38 +01001442 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001443 bitmap->VisitMarkedRange(objects_begin,
1444 objects_end,
1445 [&space, &visitor](mirror::Object* obj)
1446 REQUIRES_SHARED(Locks::mutator_lock_) {
1447 if (space.HasAddress(obj)) {
1448 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001449 obj->VisitReferences</* kVisitNativeRoots= */ true,
1450 kVerifyNone,
1451 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001452 } else {
1453 // Don't visit native roots for non-dex-cache as they can't contain
1454 // native references to strings. This is verified during compilation
1455 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001456 obj->VisitReferences</* kVisitNativeRoots= */ false,
1457 kVerifyNone,
1458 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001459 }
1460 }
1461 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001462 return visitor.GetCount();
1463}
1464
1465template <typename Visitor>
1466static void VisitInternedStringReferences(
1467 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001468 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1469 const uint8_t* target_base = space->Begin();
1470 const ImageSection& sro_section =
1471 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1472 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1473
1474 VLOG(image)
1475 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1476 << num_string_offsets;
1477
1478 const auto* sro_base =
1479 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1480
1481 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1482 uint32_t base_offset = sro_base[offset_index].first;
1483
David Srbecky86d6cd52020-12-02 18:13:10 +00001484 uint32_t raw_member_offset = sro_base[offset_index].second;
1485 DCHECK_ALIGNED(base_offset, 2);
1486 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001487
David Srbecky86d6cd52020-12-02 18:13:10 +00001488 ObjPtr<mirror::Object> obj_ptr =
1489 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1490 MemberOffset member_offset(raw_member_offset);
1491 ObjPtr<mirror::String> referred_string =
1492 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001493 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001494 kWithoutReadBarrier,
1495 /* kIsVolatile= */ false>(member_offset);
1496 DCHECK(referred_string != nullptr);
1497
1498 ObjPtr<mirror::String> visited = visitor(referred_string);
1499 if (visited != referred_string) {
1500 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1501 /* kCheckTransaction= */ false,
1502 kVerifyNone,
1503 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001504 }
1505 }
1506}
1507
1508static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1509 REQUIRES_SHARED(Locks::mutator_lock_) {
1510 InternTable::UnorderedSet image_interns;
1511 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1512 if (section.Size() > 0) {
1513 size_t read_count;
1514 const uint8_t* data = space->Begin() + section.Offset();
1515 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1516 image_set.swap(image_interns);
1517 }
1518 size_t num_recorded_refs = 0u;
1519 VisitInternedStringReferences(
1520 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001521 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1522 REQUIRES_SHARED(Locks::mutator_lock_) {
1523 auto it = image_interns.find(GcRoot<mirror::String>(str));
1524 CHECK(it != image_interns.end());
1525 CHECK(it->Read() == str);
1526 ++num_recorded_refs;
1527 return str;
1528 });
1529 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1530 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001531}
1532
Andreas Gampe2af99022017-04-25 08:32:59 -07001533// new_class_set is the set of classes that were read from the class table section in the image.
1534// If there was no class table section, it is null.
1535// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001536class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001537 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001538 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001539 ClassLinker* class_linker,
1540 gc::space::ImageSpace* space,
1541 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001542 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001543 REQUIRES(!Locks::dex_lock_)
1544 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001545
Chris Wailesfbeef462018-10-19 14:16:35 -07001546 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001547 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001548};
1549
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001550void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001551 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001552 gc::space::ImageSpace* space,
1553 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001554 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001555 REQUIRES(!Locks::dex_lock_)
1556 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001557 ScopedTrace app_image_timing("AppImage:Updating");
1558
Vladimir Marko8e05f092019-06-10 11:10:38 +01001559 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1560 // In debug build, verify the string references before applying
1561 // the Runtime::LoadAppImageStartupCache() option.
1562 VerifyInternedStringReferences(space);
1563 }
1564
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001565 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001566 Runtime* const runtime = Runtime::Current();
1567 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001568 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001569 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001570 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001571 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001572 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001573 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001574 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001575 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001576 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001577 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001578 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001579 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001580 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001581
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001582 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001583 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001584 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001585
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001586 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001587 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001588 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001589 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1590 header.VisitPackedArtMethods([&](ArtMethod& method)
1591 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1592 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1593 if (klass != nullptr) {
1594 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1595 }
1596 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001597 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001598}
1599
Chris Wailesfbeef462018-10-19 14:16:35 -07001600void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001601 // Iterate over the string reference offsets stored in the image and intern
1602 // the strings they point to.
1603 ScopedTrace timing("AppImage:InternString");
1604
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001605 Runtime* const runtime = Runtime::Current();
1606 InternTable* const intern_table = runtime->GetInternTable();
1607
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001608 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1609 // for faster lookup.
1610 // TODO: Optimize with a bitmap or bloom filter
1611 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001612 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001613 REQUIRES_SHARED(Locks::mutator_lock_)
1614 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001615 const size_t non_boot_image_strings = intern_table->CountInterns(
1616 /*visit_boot_images=*/false,
1617 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001618 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001619 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1620 // Visit the smaller of the two sets to compute the intersection.
1621 if (interns.size() < non_boot_image_strings) {
1622 for (auto it = interns.begin(); it != interns.end(); ) {
1623 ObjPtr<mirror::String> string = it->Read();
1624 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1625 if (existing == nullptr) {
1626 existing = intern_table->LookupStrongLocked(string);
1627 }
1628 if (existing != nullptr) {
1629 intern_remap.Put(string.Ptr(), existing.Ptr());
1630 it = interns.erase(it);
1631 } else {
1632 ++it;
1633 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001634 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001635 } else {
1636 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1637 REQUIRES_SHARED(Locks::mutator_lock_)
1638 REQUIRES(Locks::intern_table_lock_) {
1639 auto it = interns.find(root);
1640 if (it != interns.end()) {
1641 ObjPtr<mirror::String> existing = root.Read();
1642 intern_remap.Put(it->Read(), existing.Ptr());
1643 it = interns.erase(it);
1644 }
1645 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1646 }
David Srbecky346fd962020-07-27 16:51:00 +01001647 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001648 if (kIsDebugBuild) {
1649 for (GcRoot<mirror::String>& root : interns) {
1650 ObjPtr<mirror::String> string = root.Read();
1651 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1652 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001653 }
1654 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001655 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001656 intern_table->AddImageStringsToTable(space, func);
1657 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001658 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001659 VisitInternedStringReferences(
1660 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001661 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1662 auto it = intern_remap.find(str.Ptr());
1663 if (it != intern_remap.end()) {
1664 return ObjPtr<mirror::String>(it->second);
1665 }
1666 return str;
1667 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001668 }
1669}
1670
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001671static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1672 const char* location,
1673 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001674 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001675 DCHECK(error_msg != nullptr);
1676 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001677 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001678 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001679 return std::unique_ptr<const DexFile>();
1680 }
1681 std::string inner_error_msg;
1682 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1683 if (dex_file == nullptr) {
1684 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1685 location,
1686 oat_file->GetLocation().c_str(),
1687 inner_error_msg.c_str());
1688 return std::unique_ptr<const DexFile>();
1689 }
1690
1691 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1692 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1693 location,
1694 dex_file->GetLocationChecksum(),
1695 oat_dex_file->GetDexFileLocationChecksum());
1696 return std::unique_ptr<const DexFile>();
1697 }
1698 return dex_file;
1699}
1700
1701bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1702 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1703 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001704 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001705 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001706 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001707 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001708 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001709 dex_caches_object->AsObjectArray<mirror::DexCache>();
1710 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001711 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001712 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1713 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1714 dex_file_location.c_str(),
1715 error_msg);
1716 if (dex_file == nullptr) {
1717 return false;
1718 }
1719 dex_cache->SetDexFile(dex_file.get());
1720 out_dex_files->push_back(std::move(dex_file));
1721 }
1722 return true;
1723}
1724
Andreas Gampe0793bec2016-12-01 11:37:33 -08001725// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1726// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001727class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001728 public:
1729 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1730 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001731 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001732 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1733 DCHECK(obj != nullptr);
1734 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1735 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1736 if (obj->IsClass()) {
1737 auto klass = obj->AsClass();
1738 for (ArtField& field : klass->GetIFields()) {
1739 CHECK_EQ(field.GetDeclaringClass(), klass);
1740 }
1741 for (ArtField& field : klass->GetSFields()) {
1742 CHECK_EQ(field.GetDeclaringClass(), klass);
1743 }
Orion Hodson5880c772020-07-28 20:12:08 +01001744 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001745 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001746 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001747 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001748 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001749 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001750 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001751 }
1752 if (klass->ShouldHaveImt()) {
1753 ImTable* imt = klass->GetImt(pointer_size);
1754 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001755 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001756 }
1757 }
1758 if (klass->ShouldHaveEmbeddedVTable()) {
1759 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001760 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001761 }
1762 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001763 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001764 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1765 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001766 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001767 }
1768 }
1769 }
1770 };
1771 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001772 }
1773
Andreas Gampe0793bec2016-12-01 11:37:33 -08001774 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001775 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001776 : spaces_(heap->GetBootImageSpaces()),
1777 pointer_size_(class_linker->GetImagePointerSize()) {
1778 space_begin_.reserve(spaces_.size());
1779 method_sections_.reserve(spaces_.size());
1780 runtime_method_sections_.reserve(spaces_.size());
1781 for (gc::space::ImageSpace* space : spaces_) {
1782 space_begin_.push_back(space->Begin());
1783 auto& header = space->GetImageHeader();
1784 method_sections_.push_back(&header.GetMethodsSection());
1785 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1786 }
1787 }
1788
Orion Hodson5880c772020-07-28 20:12:08 +01001789 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001790 REQUIRES_SHARED(Locks::mutator_lock_) {
1791 if (m->IsRuntimeMethod()) {
1792 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1793 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1794 } else if (m->IsCopied()) {
1795 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1796 } else if (expected_class != nullptr) {
1797 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1798 }
1799 if (!spaces_.empty()) {
1800 bool contains = false;
1801 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1802 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1803 contains = method_sections_[i]->Contains(offset) ||
1804 runtime_method_sections_[i]->Contains(offset);
1805 }
1806 CHECK(contains) << m << " not found";
1807 }
1808 }
1809
Orion Hodson5880c772020-07-28 20:12:08 +01001810 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1811 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001812 REQUIRES_SHARED(Locks::mutator_lock_) {
1813 CHECK(arr != nullptr);
1814 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1815 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1816 // expected_class == null means we are a dex cache.
1817 if (expected_class != nullptr) {
1818 CHECK(method != nullptr);
1819 }
1820 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001821 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001822 }
1823 }
1824 }
1825
Andreas Gampe0793bec2016-12-01 11:37:33 -08001826 const std::vector<gc::space::ImageSpace*>& spaces_;
1827 const PointerSize pointer_size_;
1828
1829 // Cached sections from the spaces.
1830 std::vector<const uint8_t*> space_begin_;
1831 std::vector<const ImageSection*> method_sections_;
1832 std::vector<const ImageSection*> runtime_method_sections_;
1833};
1834
Andreas Gampebe7af222017-07-25 09:57:28 -07001835static void VerifyAppImage(const ImageHeader& header,
1836 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001837 ClassTable* class_table,
1838 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001839 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001840 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1841 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1842 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1843 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1844 << mirror::Class::PrettyClass(klass);
1845 }
1846 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001847 {
1848 // Verify that all direct interfaces of classes in the class table are also resolved.
1849 std::vector<ObjPtr<mirror::Class>> classes;
1850 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1851 REQUIRES_SHARED(Locks::mutator_lock_) {
1852 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1853 classes.push_back(klass);
1854 }
1855 return true;
1856 };
1857 class_table->Visit(verify_direct_interfaces_in_table);
Andreas Gampebe7af222017-07-25 09:57:28 -07001858 for (ObjPtr<mirror::Class> klass : classes) {
1859 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +01001860 CHECK(klass->GetDirectInterface(i) != nullptr)
Andreas Gampebe7af222017-07-25 09:57:28 -07001861 << klass->PrettyDescriptor() << " iface #" << i;
1862 }
1863 }
1864 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001865}
1866
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001867bool ClassLinker::AddImageSpace(
1868 gc::space::ImageSpace* space,
1869 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001870 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1871 std::string* error_msg) {
1872 DCHECK(out_dex_files != nullptr);
1873 DCHECK(error_msg != nullptr);
1874 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001875 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001876 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001877 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001878 DCHECK(dex_caches_object != nullptr);
1879 Runtime* const runtime = Runtime::Current();
1880 gc::Heap* const heap = runtime->GetHeap();
1881 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001882 // Check that the image is what we are expecting.
1883 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1884 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1885 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1886 image_pointer_size_);
1887 return false;
1888 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001889 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1890 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1891 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1892 expected_image_roots,
1893 header.GetImageRoots()->GetLength());
1894 return false;
1895 }
1896 StackHandleScope<3> hs(self);
1897 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1898 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1899 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1900 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001901 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001902 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1903 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001904 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001905 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001906 *error_msg = StringPrintf("Expected %d class roots but got %d",
1907 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001908 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001909 return false;
1910 }
1911 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001912 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1913 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1914 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001915 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1916 return false;
1917 }
1918 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001919 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001920 if (oat_file->GetOatHeader().GetDexFileCount() !=
1921 static_cast<uint32_t>(dex_caches->GetLength())) {
1922 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1923 "image";
1924 return false;
1925 }
1926
Alex Lighta9bbc082019-11-14 14:51:41 -08001927 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001928 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001929 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1930 dex_file_location.c_str(),
1931 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001932 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001933 return false;
1934 }
1935
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001936 LinearAlloc* linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader.Get());
1937 DCHECK(linear_alloc != nullptr);
1938 DCHECK_EQ(linear_alloc == Runtime::Current()->GetLinearAlloc(), !app_image);
David Srbecky86d6cd52020-12-02 18:13:10 +00001939 {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001940 // Native fields are all null. Initialize them and allocate native memory.
David Srbecky86d6cd52020-12-02 18:13:10 +00001941 WriterMutexLock mu(self, *Locks::dex_lock_);
Orion Hodsonb9b7d912021-02-24 09:24:47 +00001942 dex_cache->InitializeNativeFields(dex_file.get(), linear_alloc);
David Srbecky86d6cd52020-12-02 18:13:10 +00001943 }
1944 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001945 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001946 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001947 }
1948 out_dex_files->push_back(std::move(dex_file));
1949 }
1950
1951 if (app_image) {
1952 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001953 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001954 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1955 *error_msg = "Unexpected BootClassLoader in app image";
1956 return false;
1957 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001958 }
1959
Orion Hodson5880c772020-07-28 20:12:08 +01001960 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001961 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001962 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 }
1964 }
1965
1966 // Set entry point to interpreter if in InterpretOnly mode.
1967 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001968 // Set image methods' entry point to interpreter.
1969 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1970 if (!method.IsRuntimeMethod()) {
1971 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001972 if (!method.IsNative() && !method.IsResolutionMethod()) {
1973 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1974 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001975 }
1976 }
1977 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001978 }
1979
Nicolas Geoffray47171752020-08-31 15:03:20 +01001980 if (!runtime->IsAotCompiler()) {
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001981 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001982 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001983 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01001984 // In the image, the `data` pointer field of the ArtMethod contains the code
1985 // item offset. Change this to the actual pointer to the code item.
1986 if (method.HasCodeItem()) {
1987 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
1988 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01001989 method.SetCodeItem(code_item);
Nicolas Geoffray47171752020-08-31 15:03:20 +01001990 }
1991 // Set image methods' entry point that point to the interpreter bridge to the
1992 // nterp entry point.
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001993 if (method.GetEntryPointFromQuickCompiledCode() == nterp_trampoline_) {
1994 if (can_use_nterp) {
Nicolas Geoffrayb1cf8372021-02-02 13:32:20 +00001995 DCHECK(!NeedsClinitCheckBeforeCall(&method) ||
1996 method.GetDeclaringClass()->IsVisiblyInitialized());
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001997 method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
1998 } else {
1999 method.SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2000 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01002001 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002002 }, space->Begin(), image_pointer_size_);
2003 }
2004
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00002005 if (runtime->IsVerificationSoftFail()) {
2006 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2007 if (!method.IsNative() && method.IsInvokable()) {
2008 method.ClearSkipAccessChecks();
2009 }
2010 }, space->Begin(), image_pointer_size_);
2011 }
2012
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002013 ClassTable* class_table = nullptr;
2014 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002015 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002016 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002017 }
2018 // If we have a class table section, read it and use it for verification in
2019 // UpdateAppImageClassLoadersAndDexCaches.
2020 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002021 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002022 const bool added_class_table = class_table_section.Size() > 0u;
2023 if (added_class_table) {
2024 const uint64_t start_time2 = NanoTime();
2025 size_t read_count = 0;
2026 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2027 /*make copy*/false,
2028 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002029 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002030 }
2031 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002032 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002033
2034 {
2035 ScopedTrace trace("AppImage:UpdateClassLoaders");
2036 // Update class loader and resolved strings. If added_class_table is false, the resolved
2037 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002038 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002039 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002040 // Note: We probably don't need the read barrier unless we copy the app image objects into
2041 // the region space.
2042 ObjPtr<mirror::Class> klass(root.Read());
2043 // Do not update class loader for boot image classes where the app image
2044 // class loader is only the initiating loader but not the defining loader.
2045 // Avoid read barrier since we are comparing against null.
2046 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002047 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002048 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002049 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002050 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002051
Vladimir Marko305c38b2018-02-14 11:50:07 +00002052 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002053 // Every class in the app image has initially SubtypeCheckInfo in the
2054 // Uninitialized state.
2055 //
2056 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2057 // after class initialization is complete. The app image ClassStatus as-is
2058 // are almost all ClassStatus::Initialized, and being in the
2059 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2060 //
2061 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2062 //
2063 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002064 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002065 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2066 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002067 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002068 }
2069 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002070 }
2071 if (!oat_file->GetBssGcRoots().empty()) {
2072 // Insert oat file to class table for visiting .bss GC roots.
2073 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002074 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002075
Mathieu Chartier69731002016-03-02 16:08:31 -08002076 if (added_class_table) {
2077 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2078 class_table->AddClassSet(std::move(temp_set));
2079 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002080
Mathieu Chartier69731002016-03-02 16:08:31 -08002081 if (kIsDebugBuild && app_image) {
2082 // This verification needs to happen after the classes have been added to the class loader.
2083 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002084 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002085 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002086 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002087
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002088 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002089 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002090}
2091
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002092void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002093 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2094 // enabling tracing requires the mutator lock, there are no race conditions here.
2095 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002096 Thread* const self = Thread::Current();
2097 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002098 if (kUseReadBarrier) {
2099 // We do not track new roots for CC.
2100 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2101 kVisitRootFlagClearRootLog |
2102 kVisitRootFlagStartLoggingNewRoots |
2103 kVisitRootFlagStopLoggingNewRoots));
2104 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002105 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002106 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2107 // There is 3 GC cases to handle:
2108 // Non moving concurrent:
2109 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002110 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002111 //
2112 // Moving non-concurrent:
2113 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2114 // To prevent missing roots, this case needs to ensure that there is no
2115 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2116 // class which is in the class table.
2117 //
2118 // Moving concurrent:
2119 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2120 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002121 //
2122 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2123 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2124 // these objects.
2125 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002126 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002127 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002128 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002129 for (const ClassLoaderData& data : class_loaders_) {
2130 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2131 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2132 }
2133 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002134 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002135 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002136 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002137 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002138 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002139 // Concurrent moving GC marked new roots through the to-space invariant.
2140 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002141 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002142 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2143 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2144 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2145 if (old_ref != nullptr) {
2146 DCHECK(old_ref->IsClass());
2147 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2148 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2149 // Concurrent moving GC marked new roots through the to-space invariant.
2150 CHECK_EQ(new_ref, old_ref);
2151 }
2152 }
2153 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002154 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002155 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002156 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002157 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002158 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002159 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002160 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002161 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002162 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002163 }
2164 // We deliberately ignore the class roots in the image since we
2165 // handle image roots by using the MS/CMS rescanning of dirty cards.
2166}
2167
Brian Carlstroma663ea52011-08-19 23:33:41 -07002168// Keep in sync with InitCallback. Anything we visit, we need to
2169// reinit references to when reinitializing a ClassLinker from a
2170// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002171void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002172 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002173 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002174 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2175 // unloading if we are marking roots.
2176 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002177}
2178
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002179class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2180 public:
2181 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2182 : visitor_(visitor),
2183 done_(false) {}
2184
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002185 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002186 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002187 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002188 if (!done_ && class_table != nullptr) {
2189 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2190 if (!class_table->Visit(visitor)) {
2191 // If the visitor ClassTable returns false it means that we don't need to continue.
2192 done_ = true;
2193 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002194 }
2195 }
2196
2197 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002198 // Class visitor that limits the class visits from a ClassTable to the classes with
2199 // the provided defining class loader. This filter is used to avoid multiple visits
2200 // of the same class which can be recorded for multiple initiating class loaders.
2201 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2202 public:
2203 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2204 ClassVisitor* visitor)
2205 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2206
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002207 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002208 if (klass->GetClassLoader() != defining_class_loader_) {
2209 return true;
2210 }
2211 return (*visitor_)(klass);
2212 }
2213
Vladimir Marko0984e482019-03-27 16:41:41 +00002214 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002215 ClassVisitor* const visitor_;
2216 };
2217
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002218 ClassVisitor* const visitor_;
2219 // If done is true then we don't need to do any more visiting.
2220 bool done_;
2221};
2222
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002223void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002224 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002225 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2226 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002227 }
2228}
2229
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002230void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002231 Thread* const self = Thread::Current();
2232 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2233 // Not safe to have thread suspension when we are holding a lock.
2234 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002235 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002236 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002237 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002238 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002239 }
2240}
2241
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002242class GetClassesInToVector : public ClassVisitor {
2243 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002244 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002245 classes_.push_back(klass);
2246 return true;
2247 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002248 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002249};
2250
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002251class GetClassInToObjectArray : public ClassVisitor {
2252 public:
2253 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2254 : arr_(arr), index_(0) {}
2255
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002256 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002257 ++index_;
2258 if (index_ <= arr_->GetLength()) {
2259 arr_->Set(index_ - 1, klass);
2260 return true;
2261 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002262 return false;
2263 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002264
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002265 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002266 return index_ <= arr_->GetLength();
2267 }
2268
2269 private:
2270 mirror::ObjectArray<mirror::Class>* const arr_;
2271 int32_t index_;
2272};
2273
2274void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002275 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2276 // is avoiding duplicates.
2277 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002278 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002279 GetClassesInToVector accumulator;
2280 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002281 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002282 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002283 return;
2284 }
2285 }
2286 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002287 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002288 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002289 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002290 // We size the array assuming classes won't be added to the class table during the visit.
2291 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002292 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002293 size_t class_table_size;
2294 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002295 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002296 // Add 100 in case new classes get loaded when we are filling in the object array.
2297 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002298 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002299 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002300 classes.Assign(
2301 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002302 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002303 GetClassInToObjectArray accumulator(classes.Get());
2304 VisitClasses(&accumulator);
2305 if (accumulator.Succeeded()) {
2306 break;
2307 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002308 }
2309 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2310 // If the class table shrank during creation of the clases array we expect null elements. If
2311 // the class table grew then the loop repeats. If classes are created after the loop has
2312 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002313 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002314 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002315 return;
2316 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002317 }
2318 }
2319}
2320
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002321ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002322 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002323 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002324 // CHA unloading analysis is not needed. No negative consequences are expected because
2325 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002326 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002327 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002328 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002329 while (!running_visibly_initialized_callbacks_.empty()) {
2330 std::unique_ptr<VisiblyInitializedCallback> callback(
2331 std::addressof(running_visibly_initialized_callbacks_.front()));
2332 running_visibly_initialized_callbacks_.pop_front();
2333 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002334}
2335
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002336void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002337 Runtime* const runtime = Runtime::Current();
2338 JavaVMExt* const vm = runtime->GetJavaVM();
2339 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002340 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002341 if (runtime->GetJit() != nullptr) {
2342 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2343 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002344 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002345 code_cache->RemoveMethodsIn(self, *data.allocator);
2346 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002347 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002348 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002349 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002350 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002351 // Cleanup references to single implementation ArtMethods that will be deleted.
2352 if (cleanup_cha) {
2353 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2354 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2355 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002356 {
2357 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2358 auto end = critical_native_code_with_clinit_check_.end();
2359 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2360 if (data.allocator->ContainsUnsafe(it->first)) {
2361 it = critical_native_code_with_clinit_check_.erase(it);
2362 } else {
2363 ++it;
2364 }
2365 }
2366 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002367
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002368 delete data.allocator;
2369 delete data.class_table;
2370}
2371
Vladimir Markobcf17522018-06-01 13:14:32 +01002372ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2373 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002374 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002375 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2376 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002377}
2378
David Srbecky86d6cd52020-12-02 18:13:10 +00002379ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002380 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002381 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002382 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002383 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002384 self->AssertPendingOOMException();
2385 return nullptr;
2386 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002387 // Use InternWeak() so that the location String can be collected when the ClassLoader
2388 // with this DexCache is collected.
2389 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002390 if (location == nullptr) {
2391 self->AssertPendingOOMException();
2392 return nullptr;
2393 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002394 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002395 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002396}
2397
Orion Hodsonb9b7d912021-02-24 09:24:47 +00002398ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2399 const DexFile& dex_file,
2400 LinearAlloc* linear_alloc) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002401 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002402 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002403 WriterMutexLock mu(self, *Locks::dex_lock_);
Orion Hodsonb9b7d912021-02-24 09:24:47 +00002404 dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002405 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002406 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002407}
2408
Vladimir Marko70e2a762019-07-12 16:49:00 +01002409template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002410ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2411 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002412 uint32_t class_size,
2413 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002414 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002415 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002416 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002417 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2418 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002419 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002420 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002421 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002422 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002423 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002424}
2425
Vladimir Marko70e2a762019-07-12 16:49:00 +01002426template <bool kMovable>
2427ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2428 ObjPtr<mirror::Class> java_lang_Class,
2429 uint32_t class_size) {
2430 mirror::Class::InitializeClassVisitor visitor(class_size);
2431 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2432}
2433
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002434ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002435 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002436}
2437
Vladimir Marko70e2a762019-07-12 16:49:00 +01002438void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2439 ClassRoot primitive_root,
2440 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002441 // We make this class non-movable for the unlikely case where it were to be
2442 // moved by a sticky-bit (minor) collection when using the Generational
2443 // Concurrent Copying (CC) collector, potentially creating a stale reference
2444 // in the `klass_` field of one of its instances allocated in the Large-Object
2445 // Space (LOS) -- see the comment about the dirty card scanning logic in
2446 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002447 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2448 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2449 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2450 DCHECK(component_type->IsPrimitive());
2451 array_class->SetComponentType(component_type);
2452 SetClassRoot(array_root, array_class);
2453}
2454
2455void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2456 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2457 array_class->SetSuperClass(java_lang_Object);
2458 array_class->SetVTable(java_lang_Object->GetVTable());
2459 array_class->SetPrimitiveType(Primitive::kPrimNot);
2460 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2461 array_class->SetClassFlags(component_type->IsPrimitive()
2462 ? mirror::kClassFlagNoReferenceFields
2463 : mirror::kClassFlagObjectArray);
2464 array_class->SetClassLoader(component_type->GetClassLoader());
2465 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2466 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2467 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2468 array_class->SetImt(object_imt, image_pointer_size_);
2469 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2470 // the kAccVerificationAttempted flag is added below, and there are no
2471 // methods that need the kAccSkipAccessChecks flag.
2472 DCHECK_EQ(array_class->NumMethods(), 0u);
2473
2474 // don't need to set new_class->SetObjectSize(..)
2475 // because Object::SizeOf delegates to Array::SizeOf
2476
2477 // All arrays have java/lang/Cloneable and java/io/Serializable as
2478 // interfaces. We need to set that up here, so that stuff like
2479 // "instanceof" works right.
2480
2481 // Use the single, global copies of "interfaces" and "iftable"
2482 // (remember not to free them for arrays).
2483 {
2484 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2485 CHECK(array_iftable != nullptr);
2486 array_class->SetIfTable(array_iftable);
2487 }
2488
2489 // Inherit access flags from the component type.
2490 int access_flags = component_type->GetAccessFlags();
2491 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2492 access_flags &= kAccJavaFlagsMask;
2493 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2494 // and remove "interface".
2495 access_flags |= kAccAbstract | kAccFinal;
2496 access_flags &= ~kAccInterface;
2497 // Arrays are access-checks-clean and preverified.
2498 access_flags |= kAccVerificationAttempted;
2499
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002500 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002501
Vladimir Markobf121912019-06-04 13:49:05 +01002502 // Array classes are fully initialized either during single threaded startup,
2503 // or from a pre-fence visitor, so visibly initialized.
2504 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002505}
2506
2507void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2508 // Do not hold lock on the array class object, the initialization of
2509 // core array classes is done while the process is still single threaded.
2510 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2511 FinishArrayClassSetup(array_class);
2512
2513 std::string temp;
2514 const char* descriptor = array_class->GetDescriptor(&temp);
2515 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2516 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2517 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002518}
2519
Vladimir Markobcf17522018-06-01 13:14:32 +01002520ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002521 Thread* self,
2522 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002523 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002524 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002525}
2526
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002527ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2528 const char* descriptor,
2529 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002530 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002531 if (kIsDebugBuild) {
2532 StackHandleScope<1> hs(self);
2533 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2534 Thread::PoisonObjectPointersIfDebug();
2535 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002536
2537 // For temporary classes we must wait for them to be retired.
2538 if (init_done_ && klass->IsTemp()) {
2539 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002540 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002541 ThrowEarlierClassFailure(klass);
2542 return nullptr;
2543 }
2544 StackHandleScope<1> hs(self);
2545 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2546 ObjectLock<mirror::Class> lock(self, h_class);
2547 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002548 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002549 lock.WaitIgnoringInterrupts();
2550 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002551 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002552 ThrowEarlierClassFailure(h_class.Get());
2553 return nullptr;
2554 }
2555 CHECK(h_class->IsRetired());
2556 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002557 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002558 }
2559
Brian Carlstromaded5f72011-10-07 17:15:04 -07002560 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002561 size_t index = 0;
2562 // Maximum number of yield iterations until we start sleeping.
2563 static const size_t kNumYieldIterations = 1000;
2564 // How long each sleep is in us.
2565 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002566 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002567 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002568 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002569 {
2570 ObjectTryLock<mirror::Class> lock(self, h_class);
2571 // Can not use a monitor wait here since it may block when returning and deadlock if another
2572 // thread has locked klass.
2573 if (lock.Acquired()) {
2574 // Check for circular dependencies between classes, the lock is required for SetStatus.
2575 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2576 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002577 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002578 return nullptr;
2579 }
2580 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002581 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002582 {
2583 // Handle wrapper deals with klass moving.
2584 ScopedThreadSuspension sts(self, kSuspended);
2585 if (index < kNumYieldIterations) {
2586 sched_yield();
2587 } else {
2588 usleep(kSleepDurationUS);
2589 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002590 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002591 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002592 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002593
Vladimir Marko72ab6842017-01-20 19:32:50 +00002594 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002595 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002596 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 }
2598 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002599 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002600 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002601 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002602}
2603
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002604using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002605
2606// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002607ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002608 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002609 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002610 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002611 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002612 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002613 return ClassPathEntry(dex_file, dex_class_def);
2614 }
2615 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002616 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002617}
2618
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002619bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2620 Thread* self,
2621 const char* descriptor,
2622 size_t hash,
2623 Handle<mirror::ClassLoader> class_loader,
2624 /*out*/ ObjPtr<mirror::Class>* result) {
2625 ArtField* field =
2626 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2627 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2628 if (raw_shared_libraries == nullptr) {
2629 return true;
2630 }
2631
2632 StackHandleScope<2> hs(self);
2633 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2634 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2635 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002636 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2637 temp_loader.Assign(loader);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002638 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2639 return false; // One of the shared libraries is not supported.
2640 }
2641 if (*result != nullptr) {
2642 return true; // Found the class up the chain.
2643 }
2644 }
2645 return true;
2646}
2647
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002648bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2649 Thread* self,
2650 const char* descriptor,
2651 size_t hash,
2652 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002653 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002654 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002655 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002656 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002657 return true;
2658 }
2659
David Brazdil05909d82018-12-06 16:25:16 +00002660 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002661 // For regular path or dex class loader the search order is:
2662 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002663 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002664 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002665
Calin Juravlecdd49122017-07-05 20:09:53 -07002666 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2667 StackHandleScope<1> hs(self);
2668 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2669 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2670 return false; // One of the parents is not supported.
2671 }
2672 if (*result != nullptr) {
2673 return true; // Found the class up the chain.
2674 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002675
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002676 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2677 return false; // One of the shared library loader is not supported.
2678 }
2679 if (*result != nullptr) {
2680 return true; // Found the class in a shared library.
2681 }
2682
Calin Juravlecdd49122017-07-05 20:09:53 -07002683 // Search the current class loader classpath.
2684 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002685 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002686 }
2687
Calin Juravlecdd49122017-07-05 20:09:53 -07002688 if (IsDelegateLastClassLoader(soa, class_loader)) {
2689 // For delegate last, the search order is:
2690 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002691 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002692 // - class loader dex files
2693 // - parent
2694 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2695 if (*result != nullptr) {
2696 return true; // The class is part of the boot class path.
2697 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002698 if (self->IsExceptionPending()) {
2699 // Pending exception means there was an error other than ClassNotFound that must be returned
2700 // to the caller.
2701 return false;
2702 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002703
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002704 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2705 return false; // One of the shared library loader is not supported.
2706 }
2707 if (*result != nullptr) {
2708 return true; // Found the class in a shared library.
2709 }
2710
Calin Juravlecdd49122017-07-05 20:09:53 -07002711 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2712 if (*result != nullptr) {
2713 return true; // Found the class in the current class loader
2714 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002715 if (self->IsExceptionPending()) {
2716 // Pending exception means there was an error other than ClassNotFound that must be returned
2717 // to the caller.
2718 return false;
2719 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002720
2721 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2722 StackHandleScope<1> hs(self);
2723 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2724 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2725 }
2726
2727 // Unsupported class loader.
2728 *result = nullptr;
2729 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002730}
2731
Andreas Gampe501c3b02019-04-17 21:54:27 +00002732namespace {
2733
2734// Matches exceptions caught in DexFile.defineClass.
2735ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2736 ClassLinker* class_linker)
2737 REQUIRES_SHARED(Locks::mutator_lock_) {
2738 return
2739 // ClassNotFoundException.
2740 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2741 class_linker))
2742 ||
2743 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2744 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2745}
2746
2747// Clear exceptions caught in DexFile.defineClass.
2748ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2749 REQUIRES_SHARED(Locks::mutator_lock_) {
2750 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2751 self->ClearException();
2752 }
2753}
2754
2755} // namespace
2756
Calin Juravle415dc3d2017-06-28 11:03:12 -07002757// Finds the class in the boot class loader.
2758// If the class is found the method returns the resolved class. Otherwise it returns null.
2759ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2760 const char* descriptor,
2761 size_t hash) {
2762 ObjPtr<mirror::Class> result = nullptr;
2763 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2764 if (pair.second != nullptr) {
2765 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2766 if (klass != nullptr) {
2767 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002768 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002769 result = DefineClass(self,
2770 descriptor,
2771 hash,
2772 ScopedNullHandle<mirror::ClassLoader>(),
2773 *pair.first,
2774 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002775 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002776 if (result == nullptr) {
2777 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002778 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002779 }
2780 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002781 return result;
2782}
Andreas Gampef865ea92015-04-13 22:14:19 -07002783
Calin Juravle415dc3d2017-06-28 11:03:12 -07002784ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2785 ScopedObjectAccessAlreadyRunnable& soa,
2786 const char* descriptor,
2787 size_t hash,
2788 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002789 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2790 IsInMemoryDexClassLoader(soa, class_loader) ||
2791 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002792 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002793
Vladimir Marko68c07582021-04-19 16:01:15 +00002794 const DexFile* dex_file = nullptr;
2795 const dex::ClassDef* class_def = nullptr;
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002796 ObjPtr<mirror::Class> ret;
Vladimir Marko68c07582021-04-19 16:01:15 +00002797 auto find_class_def = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
2798 const dex::ClassDef* cp_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
2799 if (cp_class_def != nullptr) {
2800 dex_file = cp_dex_file;
2801 class_def = cp_class_def;
2802 return false; // Found a class definition, stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002803 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002804 return true; // Continue with the next DexFile.
2805 };
Vladimir Marko68c07582021-04-19 16:01:15 +00002806 VisitClassLoaderDexFiles(soa, class_loader, find_class_def);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002807
Vladimir Marko68c07582021-04-19 16:01:15 +00002808 ObjPtr<mirror::Class> klass = nullptr;
2809 if (class_def != nullptr) {
2810 klass = DefineClass(soa.Self(), descriptor, hash, class_loader, *dex_file, *class_def);
2811 if (UNLIKELY(klass == nullptr)) {
2812 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2813 FilterDexFileCaughtExceptions(soa.Self(), this);
2814 } else {
2815 DCHECK(!soa.Self()->IsExceptionPending());
2816 }
2817 }
2818 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002819}
2820
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002821ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2822 const char* descriptor,
2823 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002824 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002825 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002826 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002827 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002828 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002829 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2830 // for primitive classes that aren't backed by dex files.
2831 return FindPrimitiveClass(descriptor[0]);
2832 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002833 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002834 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002835 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002836 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002837 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002838 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002839 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002840 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002841 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002842 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002843 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002844 return DefineClass(self,
2845 descriptor,
2846 hash,
2847 ScopedNullHandle<mirror::ClassLoader>(),
2848 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002849 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002850 } else {
2851 // The boot class loader is searched ahead of the application class loader, failures are
2852 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2853 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002854 ObjPtr<mirror::Throwable> pre_allocated =
2855 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002856 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002857 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002858 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002859 }
2860 ObjPtr<mirror::Class> result_ptr;
2861 bool descriptor_equals;
2862 if (descriptor[0] == '[') {
2863 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2864 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2865 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2866 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002867 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002868 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002869 bool known_hierarchy =
2870 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2871 if (result_ptr != nullptr) {
2872 // The chain was understood and we found the class. We still need to add the class to
2873 // the class table to protect from racy programs that can try and redefine the path list
2874 // which would change the Class<?> returned for subsequent evaluation of const-class.
2875 DCHECK(known_hierarchy);
2876 DCHECK(result_ptr->DescriptorEquals(descriptor));
2877 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002878 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002879 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002880 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2881 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002882 //
2883 // If the chain was understood but we did not find the class, let the Java-side
2884 // rediscover all this and throw the exception with the right stack trace. Note that
2885 // the Java-side could still succeed for racy programs if another thread is actively
2886 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002887
Alex Light185a4612018-10-04 15:54:25 -07002888 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002889 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002890 // Oops, we can't call into java so we can't run actual class-loader code.
2891 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002892 ObjPtr<mirror::Throwable> pre_allocated =
2893 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2894 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002895 return nullptr;
2896 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002897
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002898 // Inlined DescriptorToDot(descriptor) with extra validation.
2899 //
2900 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2901 // the DescriptorEquals() check below and give a confusing error message. For example,
2902 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2903 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2904 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2905 size_t descriptor_length = strlen(descriptor);
2906 if (UNLIKELY(descriptor[0] != 'L') ||
2907 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2908 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2909 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2910 return nullptr;
2911 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002912
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002913 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2914 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002915 if (known_hierarchy &&
2916 fast_class_not_found_exceptions_ &&
2917 !Runtime::Current()->IsJavaDebuggable()) {
2918 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2919 // debuggable, optimize this path by throwing directly here without going back to Java
2920 // language. This reduces how many ClassNotFoundExceptions happen.
2921 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2922 "%s",
2923 class_name_string.c_str());
2924 } else {
2925 ScopedLocalRef<jobject> class_loader_object(
2926 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2927 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2928 {
2929 ScopedThreadStateChange tsc(self, kNative);
2930 ScopedLocalRef<jobject> class_name_object(
2931 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2932 if (class_name_object.get() == nullptr) {
2933 DCHECK(self->IsExceptionPending()); // OOME.
2934 return nullptr;
2935 }
2936 CHECK(class_loader_object.get() != nullptr);
2937 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2938 WellKnownClasses::java_lang_ClassLoader_loadClass,
2939 class_name_object.get()));
2940 }
2941 if (result.get() == nullptr && !self->IsExceptionPending()) {
2942 // broken loader - throw NPE to be compatible with Dalvik
2943 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2944 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002945 return nullptr;
2946 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002947 result_ptr = soa.Decode<mirror::Class>(result.get());
2948 // Check the name of the returned class.
2949 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002950 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002951 } else {
2952 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002953 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002954 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002955
2956 if (self->IsExceptionPending()) {
2957 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2958 // However, to comply with the RI behavior, first check if another thread succeeded.
2959 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2960 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2961 self->ClearException();
2962 return EnsureResolved(self, descriptor, result_ptr);
2963 }
2964 return nullptr;
2965 }
2966
2967 // Try to insert the class to the class table, checking for mismatch.
2968 ObjPtr<mirror::Class> old;
2969 {
2970 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2971 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2972 old = class_table->Lookup(descriptor, hash);
2973 if (old == nullptr) {
2974 old = result_ptr; // For the comparison below, after releasing the lock.
2975 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002976 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002977 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002978 } // else throw below, after releasing the lock.
2979 }
2980 }
2981 if (UNLIKELY(old != result_ptr)) {
2982 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2983 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01002984 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002985 const char* loader_class_name =
2986 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2987 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2988 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2989 << DescriptorToDot(descriptor) << "\").";
2990 return EnsureResolved(self, descriptor, old);
2991 }
2992 if (UNLIKELY(!descriptor_equals)) {
2993 std::string result_storage;
2994 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2995 std::string loader_storage;
2996 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2997 ThrowNoClassDefFoundError(
2998 "Initiating class loader of type %s returned class %s instead of %s.",
2999 DescriptorToDot(loader_class_name).c_str(),
3000 DescriptorToDot(result_name).c_str(),
3001 DescriptorToDot(descriptor).c_str());
3002 return nullptr;
3003 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003004 // Success.
3005 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003006}
3007
Alex Light270db1c2019-12-03 12:20:01 +00003008// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3009// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3010// like pausing class definition.
3011struct ScopedDefiningClass {
3012 public:
3013 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3014 : self_(self), returned_(false) {
3015 Locks::mutator_lock_->AssertSharedHeld(self_);
3016 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3017 self_->IncrDefineClassCount();
3018 }
3019 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3020 Locks::mutator_lock_->AssertSharedHeld(self_);
3021 CHECK(returned_);
3022 }
3023
3024 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3025 REQUIRES_SHARED(Locks::mutator_lock_) {
3026 CHECK(!returned_);
3027 self_->DecrDefineClassCount();
3028 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3029 Thread::PoisonObjectPointersIfDebug();
3030 returned_ = true;
3031 return h_klass.Get();
3032 }
3033
3034 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3035 REQUIRES_SHARED(Locks::mutator_lock_) {
3036 StackHandleScope<1> hs(self_);
3037 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3038 return Finish(h_klass);
3039 }
3040
3041 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3042 REQUIRES_SHARED(Locks::mutator_lock_) {
3043 ScopedNullHandle<mirror::Class> snh;
3044 return Finish(snh);
3045 }
3046
3047 private:
3048 Thread* self_;
3049 bool returned_;
3050};
3051
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003052ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3053 const char* descriptor,
3054 size_t hash,
3055 Handle<mirror::ClassLoader> class_loader,
3056 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003057 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003058 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003059 StackHandleScope<3> hs(self);
Eric Holk74584e62021-02-18 14:39:17 -08003060 metrics::AutoTimer timer{GetMetrics()->ClassLoadingTotalTime()};
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003061 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003062
Brian Carlstromaded5f72011-10-07 17:15:04 -07003063 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003064 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003065 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003066 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003067 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003068 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003069 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003070 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003071 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003072 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003073 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003074 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003075 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003076 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003077 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003078 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003079 }
3080
Vladimir Markob9c29f62019-03-20 14:22:51 +00003081 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3082 // some runtime modules. Prevent definition of classes in app class loader that could clash
3083 // with these modules as these classes could be resolved differently during execution.
3084 if (class_loader != nullptr &&
3085 Runtime::Current()->IsAotCompiler() &&
Vladimir Markod1f73512020-04-02 10:50:35 +01003086 IsUpdatableBootClassPathDescriptor(descriptor)) {
Vladimir Markob9c29f62019-03-20 14:22:51 +00003087 ObjPtr<mirror::Throwable> pre_allocated =
3088 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3089 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003090 return sdc.Finish(nullptr);
Vladimir Markob9c29f62019-03-20 14:22:51 +00003091 }
3092
Calin Juravle33787682019-07-26 14:27:18 -07003093 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3094 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3095 // public class path then we prevent the definition of the class.
3096 //
3097 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3098 // classpath is not checked.
3099 if (class_loader == nullptr &&
3100 Runtime::Current()->IsAotCompiler() &&
3101 DenyAccessBasedOnPublicSdk(descriptor)) {
3102 ObjPtr<mirror::Throwable> pre_allocated =
3103 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3104 self->SetException(pre_allocated);
3105 return sdc.Finish(nullptr);
3106 }
3107
Alex Lighte9f61032018-09-24 16:04:51 -07003108 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3109 // code to be executed. We put it up here so we can avoid all the allocations associated with
3110 // creating the class. This can happen with (eg) jit threads.
3111 if (!self->CanLoadClasses()) {
3112 // Make sure we don't try to load anything, potentially causing an infinite loop.
3113 ObjPtr<mirror::Throwable> pre_allocated =
3114 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3115 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003116 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003117 }
3118
Andreas Gampefa4333d2017-02-14 11:10:34 -08003119 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003120 // Allocate a class with the status of not ready.
3121 // Interface object should get the right size here. Regular class will
3122 // figure out the right size later and be replaced with one of the right
3123 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003124 if (CanAllocClass()) {
3125 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3126 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003127 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003128 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003129 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003130 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003131 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003132 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003133 }
Alex Lightb0f11922017-01-23 14:25:17 -08003134 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3135 // nothing.
3136 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003137 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003138 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3139 // will only be called once.
3140 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3141 klass,
3142 class_loader,
3143 dex_file,
3144 dex_class_def,
3145 &new_dex_file,
3146 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003147 // Check to see if an exception happened during runtime callbacks. Return if so.
3148 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003149 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003150 }
Alex Lightb0f11922017-01-23 14:25:17 -08003151 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003152 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003153 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003154 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003155 }
3156 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003157 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003158
Jeff Hao848f70a2014-01-15 13:49:50 -08003159 // Mark the string class by setting its access flag.
3160 if (UNLIKELY(!init_done_)) {
3161 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3162 klass->SetStringClass();
3163 }
3164 }
3165
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003166 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003167 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003168 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003169 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003170
Mathieu Chartier590fee92013-09-13 13:46:47 -07003171 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003172 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003173 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003174 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3175 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003176 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003177 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003178
Mathieu Chartierc7853442015-03-27 14:35:38 -07003179 // Load the fields and other things after we are inserted in the table. This is so that we don't
3180 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3181 // other reason is that the field roots are only visited from the class table. So we need to be
3182 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003183 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003184 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003185 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003186 // An exception occured during load, set status to erroneous while holding klass' lock in case
3187 // notification is necessary.
3188 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003189 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003190 }
Alex Light270db1c2019-12-03 12:20:01 +00003191 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003192 }
3193
Brian Carlstromaded5f72011-10-07 17:15:04 -07003194 // Finish loading (if necessary) by finding parents
3195 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003196 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003197 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003198 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003199 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003200 }
Alex Light270db1c2019-12-03 12:20:01 +00003201 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003202 }
3203 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003204
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003205 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003206 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003207 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003208
Brian Carlstromaded5f72011-10-07 17:15:04 -07003209 // Link the class (if necessary)
3210 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003211 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003212 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003213
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003214 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003215 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003216 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003217 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003218 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003219 }
Alex Light270db1c2019-12-03 12:20:01 +00003220 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003221 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003222 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003223 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003224 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003225
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003226 // Instrumentation may have updated entrypoints for all methods of all
3227 // classes. However it could not update methods of this class while we
3228 // were loading it. Now the class is resolved, we can update entrypoints
3229 // as required by instrumentation.
3230 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3231 // We must be in the kRunnable state to prevent instrumentation from
3232 // suspending all threads to update entrypoints while we are doing it
3233 // for this class.
3234 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003235 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003236 }
3237
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003238 /*
3239 * We send CLASS_PREPARE events to the debugger from here. The
3240 * definition of "preparation" is creating the static fields for a
3241 * class and initializing them to the standard default values, but not
3242 * executing any code (that comes later, during "initialization").
3243 *
3244 * We did the static preparation in LinkClass.
3245 *
3246 * The class has been prepared and resolved but possibly not yet verified
3247 * at this point.
3248 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003249 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003250
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003251 // Notify native debugger of the new class and its layout.
3252 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3253
Alex Light270db1c2019-12-03 12:20:01 +00003254 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003255}
3256
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003257uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003258 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003259 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003260 size_t num_8 = 0;
3261 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003262 size_t num_32 = 0;
3263 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003264 ClassAccessor accessor(dex_file, dex_class_def);
3265 // We allow duplicate definitions of the same field in a class_data_item
3266 // but ignore the repeated indexes here, b/21868015.
3267 uint32_t last_field_idx = dex::kDexNoIndex;
3268 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3269 uint32_t field_idx = field.GetIndex();
3270 // Ordering enforced by DexFileVerifier.
3271 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3272 if (UNLIKELY(field_idx == last_field_idx)) {
3273 continue;
3274 }
3275 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003276 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003277 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3278 char c = descriptor[0];
3279 switch (c) {
3280 case 'L':
3281 case '[':
3282 num_ref++;
3283 break;
3284 case 'J':
3285 case 'D':
3286 num_64++;
3287 break;
3288 case 'I':
3289 case 'F':
3290 num_32++;
3291 break;
3292 case 'S':
3293 case 'C':
3294 num_16++;
3295 break;
3296 case 'B':
3297 case 'Z':
3298 num_8++;
3299 break;
3300 default:
3301 LOG(FATAL) << "Unknown descriptor: " << c;
3302 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003303 }
3304 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003305 return mirror::Class::ComputeClassSize(false,
3306 0,
3307 num_8,
3308 num_16,
3309 num_32,
3310 num_64,
3311 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003312 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003313}
3314
Alex Lightfc49fec2018-01-16 22:28:36 +00003315// Special case to get oat code without overwriting a trampoline.
3316const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003317 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003318 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003319 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003320 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003321 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003322 if (code != nullptr) {
3323 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003324 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003325
3326 jit::Jit* jit = Runtime::Current()->GetJit();
3327 if (jit != nullptr) {
3328 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3329 if (code != nullptr) {
3330 return code;
3331 }
3332 }
3333
Alex Lightfc49fec2018-01-16 22:28:36 +00003334 if (method->IsNative()) {
3335 // No code and native? Use generic trampoline.
3336 return GetQuickGenericJniStub();
3337 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003338
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003339 if (interpreter::CanRuntimeUseNterp() && CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003340 return interpreter::GetNterpEntryPoint();
3341 }
3342
Alex Lightfc49fec2018-01-16 22:28:36 +00003343 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003344}
3345
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003346bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003347 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003348 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3349 return false;
3350 }
3351
Elliott Hughes956af0f2014-12-11 14:34:28 -08003352 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003353 return true;
3354 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003355
3356 Runtime* runtime = Runtime::Current();
3357 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3358 if (instr->InterpretOnly()) {
3359 return true;
3360 }
3361
3362 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3363 // Doing this check avoids doing compiled/interpreter transitions.
3364 return true;
3365 }
3366
Alex Lightfc588092020-01-23 15:39:08 -08003367 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003368 // Force the use of interpreter when it is required by the debugger.
3369 return true;
3370 }
3371
Alex Light8f34aba2017-10-09 13:46:32 -07003372 if (Thread::Current()->IsAsyncExceptionPending()) {
3373 // Force use of interpreter to handle async-exceptions
3374 return true;
3375 }
3376
Alex Light2d441b12018-06-08 15:33:21 -07003377 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3378 const void* instr_target = instr->GetCodeForInvoke(method);
3379 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3380 return ShouldUseInterpreterEntrypoint(method, instr_target);
3381 }
3382
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003383 if (runtime->IsJavaDebuggable()) {
3384 // For simplicity, we ignore precompiled code and go to the interpreter
3385 // assuming we don't already have jitted code.
3386 // We could look at the oat file where `quick_code` is being defined,
3387 // and check whether it's been compiled debuggable, but we decided to
3388 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003389 jit::Jit* jit = Runtime::Current()->GetJit();
3390 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3391 }
3392
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003393 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003394 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003395 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003396 // since we want to JIT it (at first use) with extra stackmaps for native
3397 // debugging. We keep however all AOT code from the boot image,
3398 // since the JIT-at-first-use is blocking and would result in non-negligible
3399 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003400 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003401 }
3402
3403 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003404}
3405
Vladimir Marko86c87522020-05-11 16:55:55 +01003406void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003407 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003408 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003409 size_t num_direct_methods = klass->NumDirectMethods();
3410 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003411 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003412 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003413 if (UNLIKELY(klass->IsProxyClass())) {
3414 return;
3415 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003416 PointerSize pointer_size = image_pointer_size_;
3417 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3418 klass->GetDirectMethods(pointer_size).end(),
3419 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3420 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3421 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3422 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3423 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3424 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3425 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3426 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3427 lb->first->SetEntryPointFromJni(lb->second);
3428 lb = critical_native_code_with_clinit_check_.erase(lb);
3429 }
3430 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003431 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003432 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003433 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003434 return; // OAT file unavailable.
3435 }
Ian Rogers19846512012-02-24 11:42:47 -08003436 }
Alex Light64ad14d2014-08-19 14:23:13 -07003437
Mathieu Chartierf8322842014-05-16 10:59:25 -07003438 const DexFile& dex_file = klass->GetDexFile();
Ian Rogers97b52f82014-08-14 11:34:07 -07003439 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003440 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3441 klass->GetDexClassDefIndex(),
3442 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003443 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003444 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3445 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003446 if (!method->IsStatic()) {
3447 // Only update static methods.
3448 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003449 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003450 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003451
3452 // In order:
3453 // 1) Check if we have AOT Code.
3454 // 2) Check if we have JIT Code.
3455 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003456 if (has_oat_class) {
3457 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003458 quick_code = oat_method.GetQuickCode();
3459 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003460
Vladimir Markocce414f2019-10-07 08:51:33 +01003461 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003462 if (quick_code == nullptr && jit != nullptr) {
3463 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003464 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003465
3466 if (quick_code == nullptr &&
3467 interpreter::CanRuntimeUseNterp() &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003468 CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003469 quick_code = interpreter::GetNterpEntryPoint();
3470 }
3471
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003472 // Check whether the method is native, in which case it's generic JNI.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003473 if (quick_code == nullptr && method->IsNative()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003474 quick_code = GetQuickGenericJniStub();
3475 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003476 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003477 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3478 // If we have the trampoline or the bridge already, no need to update.
3479 // This saves in not dirtying boot image memory.
3480 continue;
3481 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003482 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003483 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003484 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003485 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003486 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003487 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003488}
3489
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003490// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3491// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003492inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3493 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003494 DCHECK(method != nullptr);
3495 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003496 method->SetEntryPointFromQuickCompiledCodePtrSize(
3497 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3498 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003499}
3500
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003501static void LinkCode(ClassLinker* class_linker,
3502 ArtMethod* method,
3503 const OatFile::OatClass* oat_class,
3504 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003505 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003506 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003507 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003508 // The following code only applies to a non-compiler runtime.
3509 return;
3510 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003511
Ian Rogers62d6c772013-02-27 08:32:07 -08003512 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003513 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003514
Alex Light9139e002015-10-09 15:59:48 -07003515 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003516 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003517 return;
3518 }
Ian Rogers19846512012-02-24 11:42:47 -08003519
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003520 const void* quick_code = nullptr;
3521 if (oat_class != nullptr) {
3522 // Every kind of method should at least get an invoke stub from the oat_method.
3523 // non-abstract methods also get their code pointers.
3524 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3525 quick_code = oat_method.GetQuickCode();
3526 }
3527
3528 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3529
3530 // Note: this mimics the logic in image_writer.cc that installs the resolution
3531 // stub only if we have compiled code and the method needs a class initialization
3532 // check.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003533 if (quick_code == nullptr) {
Nicolas Geoffray4ef36492021-06-16 17:26:51 +01003534 if (method->IsNative()) {
3535 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
3536 } else if (interpreter::CanRuntimeUseNterp() && CanMethodUseNterp(method)) {
3537 // The nterp trampoline doesn't do initialization checks, so install the
3538 // resolution stub if needed.
3539 if (NeedsClinitCheckBeforeCall(method)) {
3540 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
3541 } else {
3542 method->SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
3543 }
3544 } else {
3545 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
3546 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003547 } else if (enter_interpreter) {
3548 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003549 } else if (NeedsClinitCheckBeforeCall(method)) {
3550 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3551 // If we do have code but the method needs a class initialization check before calling
3552 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003553 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3554 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003555 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003556 } else {
3557 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003558 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003559
Ian Rogers62d6c772013-02-27 08:32:07 -08003560 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003561 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3562 // as the extra processing for @CriticalNative is not needed yet.
3563 method->SetEntryPointFromJni(
3564 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Andreas Gampe90546832014-03-12 18:07:19 -07003565
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003566 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003567 // We have a native method here without code. Then it should have the generic JNI
3568 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003569 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003570 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003571 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003572 }
3573}
3574
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003575void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003576 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003577 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003578 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003579 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003580 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003581 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003582 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003583 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003584
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003585 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003586 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003587 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003588 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003589 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003590 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003591 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003592
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003593 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003594 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003595}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003596
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003597LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3598 LinearAlloc* allocator,
3599 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003600 if (length == 0) {
3601 return nullptr;
3602 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003603 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3604 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3605 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003606 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003607 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003608 CHECK(ret != nullptr);
3609 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3610 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003611}
3612
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003613LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3614 LinearAlloc* allocator,
3615 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003616 if (length == 0) {
3617 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003618 }
Vladimir Marko14632852015-08-17 12:07:23 +01003619 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3620 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003621 const size_t storage_size =
3622 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003623 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003624 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003625 CHECK(ret != nullptr);
3626 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003627 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003628 }
3629 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003630}
3631
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003632LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003633 if (class_loader == nullptr) {
3634 return Runtime::Current()->GetLinearAlloc();
3635 }
3636 LinearAlloc* allocator = class_loader->GetAllocator();
3637 DCHECK(allocator != nullptr);
3638 return allocator;
3639}
3640
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003641LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003642 if (class_loader == nullptr) {
3643 return Runtime::Current()->GetLinearAlloc();
3644 }
3645 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3646 LinearAlloc* allocator = class_loader->GetAllocator();
3647 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003648 RegisterClassLoader(class_loader);
3649 allocator = class_loader->GetAllocator();
3650 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003651 }
3652 return allocator;
3653}
3654
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003655void ClassLinker::LoadClass(Thread* self,
3656 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003657 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003658 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003659 ClassAccessor accessor(dex_file,
3660 dex_class_def,
3661 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003662 if (!accessor.HasClassData()) {
3663 return;
3664 }
3665 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003666 {
3667 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3668 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003669 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003670 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003671 // We allow duplicate definitions of the same field in a class_data_item
3672 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003673 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003674 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3675 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003676 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003677 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3678 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003679 accessor.NumInstanceFields());
3680 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003681 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003682 uint32_t last_static_field_idx = 0u;
3683 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003684
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003685 // Methods
3686 bool has_oat_class = false;
3687 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3688 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3689 : OatFile::OatClass::Invalid();
3690 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3691 klass->SetMethodsPtr(
3692 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3693 accessor.NumDirectMethods(),
3694 accessor.NumVirtualMethods());
3695 size_t class_def_method_index = 0;
3696 uint32_t last_dex_method_index = dex::kDexNoIndex;
3697 size_t last_class_def_method_index = 0;
3698
3699 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3700 // methods needs to decode all of the fields.
3701 accessor.VisitFieldsAndMethods([&](
3702 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3703 uint32_t field_idx = field.GetIndex();
3704 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3705 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3706 LoadField(field, klass, &sfields->At(num_sfields));
3707 ++num_sfields;
3708 last_static_field_idx = field_idx;
3709 }
3710 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3711 uint32_t field_idx = field.GetIndex();
3712 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3713 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3714 LoadField(field, klass, &ifields->At(num_ifields));
3715 ++num_ifields;
3716 last_instance_field_idx = field_idx;
3717 }
3718 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3719 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3720 image_pointer_size_);
3721 LoadMethod(dex_file, method, klass, art_method);
3722 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3723 uint32_t it_method_index = method.GetIndex();
3724 if (last_dex_method_index == it_method_index) {
3725 // duplicate case
3726 art_method->SetMethodIndex(last_class_def_method_index);
3727 } else {
3728 art_method->SetMethodIndex(class_def_method_index);
3729 last_dex_method_index = it_method_index;
3730 last_class_def_method_index = class_def_method_index;
3731 }
3732 ++class_def_method_index;
3733 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3734 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3735 class_def_method_index - accessor.NumDirectMethods(),
3736 image_pointer_size_);
3737 LoadMethod(dex_file, method, klass, art_method);
3738 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3739 ++class_def_method_index;
3740 });
3741
3742 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003743 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003744 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3745 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3746 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003747 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3748 if (sfields != nullptr) {
3749 sfields->SetSize(num_sfields);
3750 }
3751 if (ifields != nullptr) {
3752 ifields->SetSize(num_ifields);
3753 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003754 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003755 // Set the field arrays.
3756 klass->SetSFieldsPtr(sfields);
3757 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003758 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003759 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003760 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003761 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003762 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003763 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003764}
3765
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003766void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003767 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003768 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003769 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003770 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003771 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003772
David Brazdil85865692018-10-30 17:26:20 +00003773 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3774 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003775}
3776
Mathieu Chartier268764d2016-09-13 12:09:38 -07003777void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003778 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003779 Handle<mirror::Class> klass,
3780 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003781 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003782 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003783 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003784
Mathieu Chartier268764d2016-09-13 12:09:38 -07003785 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003786 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003787 dst->SetDeclaringClass(klass.Get());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003788
David Brazdil85865692018-10-30 17:26:20 +00003789 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3790 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003791
Ian Rogersdfb325e2013-10-30 01:00:44 -07003792 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003793 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003794 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3795 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003796 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003797 klass->SetFinalizable();
3798 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003799 std::string temp;
3800 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003801 // The Enum class declares a "final" finalize() method to prevent subclasses from
3802 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3803 // subclasses, so we exclude it here.
3804 // We also want to avoid setting the flag on Object, where we know that finalize() is
3805 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003806 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3807 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003808 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003809 }
3810 }
3811 }
3812 } else if (method_name[0] == '<') {
3813 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003814 bool is_init = (strcmp("<init>", method_name) == 0);
3815 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003816 if (UNLIKELY(!is_init && !is_clinit)) {
3817 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3818 } else {
3819 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3820 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003821 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003822 access_flags |= kAccConstructor;
3823 }
3824 }
3825 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003826 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3827 // Check if the native method is annotated with @FastNative or @CriticalNative.
3828 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3829 dex_file, dst->GetClassDef(), dex_method_idx);
3830 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003831 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003832 // Must be done after SetAccessFlags since IsAbstract depends on it.
3833 if (klass->IsInterface() && dst->IsAbstract()) {
3834 dst->CalculateAndSetImtIndex();
3835 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01003836 if (dst->HasCodeItem()) {
3837 DCHECK_NE(method.GetCodeItemOffset(), 0u);
3838 if (Runtime::Current()->IsAotCompiler()) {
3839 dst->SetDataPtrSize(reinterpret_cast32<void*>(method.GetCodeItemOffset()), image_pointer_size_);
3840 } else {
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01003841 dst->SetCodeItem(dst->GetDexFile()->GetCodeItem(method.GetCodeItemOffset()));
Nicolas Geoffray47171752020-08-31 15:03:20 +01003842 }
3843 } else {
3844 dst->SetDataPtrSize(nullptr, image_pointer_size_);
3845 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3846 }
Nicolas Geoffray43c9cd72021-03-10 15:09:19 +00003847
3848 // Set optimization flags related to the shorty.
3849 const char* shorty = dst->GetShorty();
3850 bool all_parameters_are_reference = true;
3851 bool all_parameters_are_reference_or_int = true;
3852 bool return_type_is_fp = (shorty[0] == 'F' || shorty[0] == 'D');
3853
3854 for (size_t i = 1, e = strlen(shorty); i < e; ++i) {
3855 if (shorty[i] != 'L') {
3856 all_parameters_are_reference = false;
3857 if (shorty[i] == 'F' || shorty[i] == 'D' || shorty[i] == 'J') {
3858 all_parameters_are_reference_or_int = false;
3859 break;
3860 }
3861 }
3862 }
3863
3864 if (!dst->IsNative() && all_parameters_are_reference) {
3865 dst->SetNterpEntryPointFastPathFlag();
3866 }
3867
3868 if (!return_type_is_fp && all_parameters_are_reference_or_int) {
3869 dst->SetNterpInvokeFastPathFlag();
3870 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003871}
3872
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003873void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00003874 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
3875 self,
3876 *dex_file,
3877 Runtime::Current()->GetLinearAlloc());
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003878 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003879 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003880}
3881
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003882void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003883 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003884 CHECK(dex_file != nullptr);
3885 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3886 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003887 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003888 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003889}
3890
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003891void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003892 ObjPtr<mirror::DexCache> dex_cache,
3893 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003894 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003895 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003896 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003897 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003898 // For app images, the dex cache location may be a suffix of the dex file location since the
3899 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003900 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3901 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003902 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3903 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003904 // The following paths checks don't work on preopt when using boot dex files, where the dex
3905 // cache location is the one on device, and the dex_file's location is the one on host.
3906 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3907 CHECK_GE(dex_file_location.length(), dex_cache_length)
3908 << dex_cache_location << " " << dex_file.GetLocation();
3909 const std::string dex_file_suffix = dex_file_location.substr(
3910 dex_file_location.length() - dex_cache_length,
3911 dex_cache_length);
3912 // Example dex_cache location is SettingsProvider.apk and
3913 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3914 CHECK_EQ(dex_cache_location, dex_file_suffix);
3915 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003916 const OatFile* oat_file =
3917 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003918 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3919 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3920 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3921 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003922 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003923 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3924 DexCacheData data = *it;
3925 if (self->IsJWeakCleared(data.weak_root)) {
3926 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003927 it = dex_caches_.erase(it);
3928 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003929 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003930 it->dex_file->GetOatDexFile() != nullptr &&
3931 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003932 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003933 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003934 ++it;
3935 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003936 }
Vladimir Markob066d432018-01-03 13:14:37 +00003937 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003938 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003939 }
David Brazdila5c3a802019-03-08 14:59:41 +00003940 // Let hiddenapi assign a domain to the newly registered dex file.
3941 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3942
Vladimir Markocd556b02017-02-03 11:47:34 +00003943 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003944 DexCacheData data;
3945 data.weak_root = dex_cache_jweak;
3946 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003947 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003948 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003949 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003950 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3951 // path dex caches without an image.
3952 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003953 // Make sure that the dex cache holds the classloader live.
3954 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003955 if (class_loader != nullptr) {
3956 // Since we added a strong root to the class table, do the write barrier as required for
3957 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003958 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003959 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003960 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003961}
3962
Alex Light725da8f2020-02-19 14:46:33 -08003963ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3964 return data != nullptr
3965 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003966 : nullptr;
3967}
3968
Alex Light725da8f2020-02-19 14:46:33 -08003969bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003970 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003971 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003972 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003973 CHECK(data != nullptr);
3974 DCHECK_EQ(dex_cache->GetDexFile(), data->dex_file);
3975 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003976}
3977
Alex Light07f06212017-06-01 14:01:43 -07003978void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3979 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003980 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003981 Thread* self = Thread::Current();
3982 StackHandleScope<2> hs(self);
3983 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3984 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3985 const DexFile* dex_file = dex_cache->GetDexFile();
3986 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3987 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003988 ReaderMutexLock mu(self, *Locks::dex_lock_);
3989 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3990 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003991 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3992 << "been registered on dex file " << dex_file->GetLocation();
3993 }
3994 ClassTable* table;
3995 {
3996 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3997 table = InsertClassTableForClassLoader(h_class_loader.Get());
3998 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003999 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4000 // a thread holding the dex lock and blocking on a condition variable regarding
4001 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004002 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07004003 WriterMutexLock mu(self, *Locks::dex_lock_);
4004 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
4005 table->InsertStrongRoot(h_dex_cache.Get());
4006 if (h_class_loader.Get() != nullptr) {
4007 // Since we added a strong root to the class table, do the write barrier as required for
4008 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004009 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004010 }
4011}
4012
Alex Lightde7f8782020-02-24 10:14:22 -08004013static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
4014 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08004015 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08004016 "Attempt to register dex file %s with multiple class loaders",
4017 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08004018}
4019
Vladimir Markocd556b02017-02-03 11:47:34 +00004020ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4021 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004022 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08004023 ObjPtr<mirror::DexCache> old_dex_cache;
4024 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004025 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004026 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004027 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4028 old_dex_cache = DecodeDexCacheLocked(self, old_data);
4029 if (old_dex_cache != nullptr) {
4030 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
4031 return old_dex_cache;
4032 } else {
4033 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
4034 // be thrown when it's safe to do so to simplify this.
4035 registered_with_another_class_loader = true;
4036 }
4037 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004038 }
Alex Light725da8f2020-02-19 14:46:33 -08004039 // We need to have released the dex_lock_ to allocate safely.
4040 if (registered_with_another_class_loader) {
4041 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4042 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07004043 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004044 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004045 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4046 DCHECK(linear_alloc != nullptr);
4047 ClassTable* table;
4048 {
4049 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4050 table = InsertClassTableForClassLoader(class_loader);
4051 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004052 // Don't alloc while holding the lock, since allocation may need to
4053 // suspend all threads and another thread may need the dex_lock_ to
4054 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004055 StackHandleScope<3> hs(self);
4056 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00004057 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004058 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004059 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4060 // a thread holding the dex lock and blocking on a condition variable regarding
4061 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004062 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004063 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004064 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4065 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004066 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Orion Hodsonb9b7d912021-02-24 09:24:47 +00004067 // Do InitializeNativeFields while holding dex lock to make sure two threads don't call it
David Srbecky86d6cd52020-12-02 18:13:10 +00004068 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
4069 // DCHECK that the arrays are null.
Orion Hodsonb9b7d912021-02-24 09:24:47 +00004070 h_dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Vladimir Markocd556b02017-02-03 11:47:34 +00004071 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004072 }
Alex Light725da8f2020-02-19 14:46:33 -08004073 if (old_dex_cache != nullptr) {
4074 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4075 // If this thread encountered OOME, ignore it.
4076 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
4077 self->ClearException();
4078 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
4079 // dex_lock_.
4080 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
4081 return old_dex_cache;
4082 } else {
4083 registered_with_another_class_loader = true;
4084 }
4085 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004086 }
Alex Light725da8f2020-02-19 14:46:33 -08004087 if (registered_with_another_class_loader) {
4088 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4089 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004090 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004091 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004092 self->AssertPendingOOMException();
4093 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004094 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004095 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004096 if (h_class_loader.Get() != nullptr) {
4097 // Since we added a strong root to the class table, do the write barrier as required for
4098 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004099 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004100 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004101 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
Nicolas Geoffray4f6bb442021-06-02 18:05:51 +01004102 PaletteNotifyDexFileLoaded(dex_file.GetLocation().c_str());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004103 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004104}
4105
Vladimir Markocd556b02017-02-03 11:47:34 +00004106bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004107 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004108 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004109}
4110
Vladimir Markocd556b02017-02-03 11:47:34 +00004111ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4112 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004113 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4114 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004115 if (dex_cache != nullptr) {
4116 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004117 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004118 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004119 for (const DexCacheData& data : dex_caches_) {
Alex Light725da8f2020-02-19 14:46:33 -08004120 if (DecodeDexCacheLocked(self, &data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004121 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004122 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004123 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004124 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
Alex Light725da8f2020-02-19 14:46:33 -08004125 << " " << &dex_file << " " << dex_cache_data->dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004126 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004127}
4128
Vladimir Markocd556b02017-02-03 11:47:34 +00004129ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4130 const DexFile* dex_file = dex_cache->GetDexFile();
4131 DCHECK(dex_file != nullptr);
4132 ReaderMutexLock mu(self, *Locks::dex_lock_);
4133 // Search assuming unique-ness of dex file.
4134 for (const DexCacheData& data : dex_caches_) {
4135 // Avoid decoding (and read barriers) other unrelated dex caches.
4136 if (data.dex_file == dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004137 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004138 if (registered_dex_cache != nullptr) {
4139 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4140 return data.class_table;
4141 }
4142 }
4143 }
4144 return nullptr;
4145}
4146
Alex Light725da8f2020-02-19 14:46:33 -08004147const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004148 // Search assuming unique-ness of dex file.
4149 for (const DexCacheData& data : dex_caches_) {
4150 // Avoid decoding (and read barriers) other unrelated dex caches.
4151 if (data.dex_file == &dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004152 return &data;
Vladimir Markocd556b02017-02-03 11:47:34 +00004153 }
4154 }
Alex Light725da8f2020-02-19 14:46:33 -08004155 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004156}
4157
Vladimir Marko70e2a762019-07-12 16:49:00 +01004158void ClassLinker::CreatePrimitiveClass(Thread* self,
4159 Primitive::Type type,
4160 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004161 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004162 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004163 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4164 // Do not hold lock on the primitive class object, the initialization of
4165 // primitive classes is done while the process is still single threaded.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004166 primitive_class->SetAccessFlagsDuringLinking(
Vladimir Marko70e2a762019-07-12 16:49:00 +01004167 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4168 primitive_class->SetPrimitiveType(type);
4169 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4170 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4171 // the kAccVerificationAttempted flag was added above, and there are no
4172 // methods that need the kAccSkipAccessChecks flag.
4173 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004174 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4175 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004176 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004177 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004178 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004179 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004180 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004181 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004182}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004183
Vladimir Marko02610552018-06-04 14:38:00 +01004184inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4185 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4186}
4187
Brian Carlstrombe977852011-07-19 14:54:54 -07004188// Create an array class (i.e. the class object for the array, not the
4189// array itself). "descriptor" looks like "[C" or "[[[[B" or
4190// "[Ljava/lang/String;".
4191//
4192// If "descriptor" refers to an array of primitives, look up the
4193// primitive type's internally-generated class object.
4194//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004195// "class_loader" is the class loader of the class that's referring to
4196// us. It's used to ensure that we're looking for the element type in
4197// the right context. It does NOT become the class loader for the
4198// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004199//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004200// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004201ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4202 const char* descriptor,
4203 size_t hash,
4204 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004205 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004206 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004207 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004208
4209 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4210 // code to be executed. We put it up here so we can avoid all the allocations associated with
4211 // creating the class. This can happen with (eg) jit threads.
4212 if (!self->CanLoadClasses()) {
4213 // Make sure we don't try to load anything, potentially causing an infinite loop.
4214 ObjPtr<mirror::Throwable> pre_allocated =
4215 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4216 self->SetException(pre_allocated);
4217 return nullptr;
4218 }
4219
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004220 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4221 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004222 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004223 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004224 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004225 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4226 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004227 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004228 DCHECK(self->IsExceptionPending());
4229 return nullptr;
4230 } else {
4231 self->ClearException();
4232 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004233 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004234 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4235 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4236 return nullptr;
4237 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004238 // See if the component type is already loaded. Array classes are
4239 // always associated with the class loader of their underlying
4240 // element type -- an array of Strings goes with the loader for
4241 // java/lang/String -- so we need to look for it there. (The
4242 // caller should have checked for the existence of the class
4243 // before calling here, but they did so with *their* class loader,
4244 // not the component type's loader.)
4245 //
4246 // If we find it, the caller adds "loader" to the class' initiating
4247 // loader list, which should prevent us from going through this again.
4248 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004249 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004250 // are the same, because our caller (FindClass) just did the
4251 // lookup. (Even if we get this wrong we still have correct behavior,
4252 // because we effectively do this lookup again when we add the new
4253 // class to the hash table --- necessary because of possible races with
4254 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004255 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004256 ObjPtr<mirror::Class> new_class =
4257 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004258 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004259 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004260 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004261 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004262 // Core array classes, i.e. Object[], Class[], String[] and primitive
4263 // arrays, have special initialization and they should be found above.
4264 DCHECK(!component_type->IsObjectClass() ||
4265 // Guard from false positives for errors before setting superclass.
4266 component_type->IsErroneousUnresolved());
4267 DCHECK(!component_type->IsStringClass());
4268 DCHECK(!component_type->IsClassClass());
4269 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004270
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004271 // Fill out the fields in the Class.
4272 //
4273 // It is possible to execute some methods against arrays, because
4274 // all arrays are subclasses of java_lang_Object_, so we need to set
4275 // up a vtable. We can just point at the one in java_lang_Object_.
4276 //
4277 // Array classes are simple enough that we don't need to do a full
4278 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004279 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4280 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4281 size_t usable_size)
4282 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004283 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004284 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4285 init_class(obj, usable_size);
4286 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4287 klass->SetComponentType(component_type.Get());
4288 // Do not hold lock for initialization, the fence issued after the visitor
4289 // returns ensures memory visibility together with the implicit consume
4290 // semantics (for all supported architectures) for any thread that loads
4291 // the array class reference from any memory locations afterwards.
4292 FinishArrayClassSetup(klass);
4293 };
4294 auto new_class = hs.NewHandle<mirror::Class>(
4295 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004296 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004297 self->AssertPendingOOMException();
4298 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004299 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004300
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004301 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004302 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004303 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4304 // duplicate events in case of races. Array classes don't really follow dedicated
4305 // load and prepare, anyways.
4306 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4307 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4308
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004309 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004310 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004311 }
4312 // Another thread must have loaded the class after we
4313 // started but before we finished. Abandon what we've
4314 // done.
4315 //
4316 // (Yes, this happens.)
4317
Vladimir Markobcf17522018-06-01 13:14:32 +01004318 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004319}
4320
Vladimir Marko9186b182018-11-06 14:55:54 +00004321ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4322 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004323 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004324 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4325 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4326 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4327 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4328 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4329 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4330 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4331 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4332 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004333 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004334 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004335 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004336 return GetClassRoot(class_root, this);
4337}
4338
4339ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4340 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4341 if (UNLIKELY(result == nullptr)) {
4342 std::string printable_type(PrintableChar(type));
4343 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4344 }
4345 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004346}
4347
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004348ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4349 ObjPtr<mirror::Class> klass,
4350 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004351 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004352 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004353 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004354 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004355 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004356 source += " from ";
4357 source += dex_cache->GetLocation()->ToModifiedUtf8();
4358 }
4359 LOG(INFO) << "Loaded class " << descriptor << source;
4360 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004361 {
4362 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004363 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004364 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004365 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004366 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004367 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004368 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004369 VerifyObject(klass);
4370 class_table->InsertWithHash(klass, hash);
4371 if (class_loader != nullptr) {
4372 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004373 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004374 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004375 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004376 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004377 }
4378 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004379 if (kIsDebugBuild) {
4380 // Test that copied methods correctly can find their holder.
4381 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4382 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4383 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004384 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004385 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004386}
4387
Vladimir Marko1998cd02017-01-13 13:02:58 +00004388void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004389 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4390 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4391 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4392 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004393 }
4394}
4395
Alex Lighte64300b2015-12-15 15:02:47 -08004396// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004397void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004398 LengthPrefixedArray<ArtMethod>* new_methods) {
4399 klass->SetMethodsPtrUnchecked(new_methods,
4400 klass->NumDirectMethods(),
4401 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004402 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004403 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004404}
4405
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004406ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4407 const char* descriptor,
4408 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004409 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4410}
4411
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004412ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4413 const char* descriptor,
4414 size_t hash,
4415 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004416 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4417 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4418 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004419 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004420 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004421 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004422 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004423 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004424 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004425}
4426
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004427class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4428 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004429 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004430
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004431 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004432 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004433 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004434 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004435 if (class_table != nullptr) {
4436 class_table->FreezeSnapshot();
4437 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004438 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004439};
4440
4441void ClassLinker::MoveClassTableToPreZygote() {
4442 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004443 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004444 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004445 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004446}
4447
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004448// Look up classes by hash and descriptor and put all matching ones in the result array.
4449class LookupClassesVisitor : public ClassLoaderVisitor {
4450 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004451 LookupClassesVisitor(const char* descriptor,
4452 size_t hash,
4453 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004454 : descriptor_(descriptor),
4455 hash_(hash),
4456 result_(result) {}
4457
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004458 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004459 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004460 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004461 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004462 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4463 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004464 result_->push_back(klass);
4465 }
4466 }
4467
4468 private:
4469 const char* const descriptor_;
4470 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004471 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004472};
4473
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004474void ClassLinker::LookupClasses(const char* descriptor,
4475 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004476 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004477 Thread* const self = Thread::Current();
4478 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004479 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004480 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004481 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004482 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004483 result.push_back(klass);
4484 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004485 LookupClassesVisitor visitor(descriptor, hash, &result);
4486 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004487}
4488
Alex Lightf1f10492015-10-07 16:08:36 -07004489bool ClassLinker::AttemptSupertypeVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004490 verifier::VerifierDeps* verifier_deps,
Alex Lightf1f10492015-10-07 16:08:36 -07004491 Handle<mirror::Class> klass,
4492 Handle<mirror::Class> supertype) {
4493 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004494 DCHECK(klass != nullptr);
4495 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004496
Alex Lightf1f10492015-10-07 16:08:36 -07004497 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004498 VerifyClass(self, verifier_deps, supertype);
Alex Lightf1f10492015-10-07 16:08:36 -07004499 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004500
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004501 if (supertype->IsVerified()
4502 || supertype->ShouldVerifyAtRuntime()
4503 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004504 // The supertype is either verified, or we soft failed at AOT time.
4505 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004506 return true;
4507 }
4508 // If we got this far then we have a hard failure.
4509 std::string error_msg =
4510 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004511 klass->PrettyDescriptor().c_str(),
4512 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004513 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004514 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004515 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004516 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004517 // Set during VerifyClass call (if at all).
4518 self->ClearException();
4519 }
4520 // Change into a verify error.
4521 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004522 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004523 self->GetException()->SetCause(cause.Get());
4524 }
4525 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4526 if (Runtime::Current()->IsAotCompiler()) {
4527 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4528 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004529 // Need to grab the lock to change status.
4530 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004531 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004532 return false;
4533}
4534
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004535verifier::FailureKind ClassLinker::VerifyClass(Thread* self,
4536 verifier::VerifierDeps* verifier_deps,
4537 Handle<mirror::Class> klass,
4538 verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004539 {
4540 // TODO: assert that the monitor on the Class is held
4541 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004542
Andreas Gampe884f3b82016-03-30 19:52:58 -07004543 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004544 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004545 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004546 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004547 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4548 // case we may see the same status again. b/62912904. This is why the check is
4549 // greater or equal.
4550 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004551 << "Class '" << klass->PrettyClass()
4552 << "' performed an illegal verification state transition from " << old_status
4553 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004554 old_status = klass->GetStatus();
4555 }
jeffhao98eacac2011-09-14 16:11:53 -07004556
Andreas Gampe884f3b82016-03-30 19:52:58 -07004557 // The class might already be erroneous, for example at compile time if we attempted to verify
4558 // this class as a parent to another.
4559 if (klass->IsErroneous()) {
4560 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004561 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004562 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004563
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004564 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004565 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004566 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Nicolas Geoffray80789962021-04-30 16:50:39 +01004567 if (verifier_deps != nullptr &&
4568 verifier_deps->ContainsDexFile(klass->GetDexFile()) &&
4569 !verifier_deps->HasRecordedVerifiedStatus(klass->GetDexFile(), *klass->GetClassDef()) &&
4570 !Runtime::Current()->IsAotCompiler()) {
4571 // If the klass is verified, but `verifier_deps` did not record it, this
4572 // means we are running background verification of a secondary dex file.
4573 // Re-run the verifier to populate `verifier_deps`.
4574 // No need to run the verification when running on the AOT Compiler, as
4575 // the driver handles those multithreaded cases already.
4576 std::string error_msg;
4577 verifier::FailureKind failure =
4578 PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
4579 // We could have soft failures, so just check that we don't have a hard
4580 // failure.
4581 DCHECK_NE(failure, verifier::FailureKind::kHardFailure) << error_msg;
4582 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004583 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004584 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004585
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004586 if (klass->IsVerifiedNeedsAccessChecks()) {
4587 if (!Runtime::Current()->IsAotCompiler()) {
4588 // Mark the class as having a verification attempt to avoid re-running
4589 // the verifier and avoid calling EnsureSkipAccessChecksMethods.
4590 klass->SetVerificationAttempted();
4591 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4592 }
4593 return verifier::FailureKind::kAccessChecksFailure;
4594 }
4595
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004596 // For AOT, don't attempt to re-verify if we have already found we should
4597 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004598 if (klass->ShouldVerifyAtRuntime()) {
4599 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004600 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004601 }
jeffhao98eacac2011-09-14 16:11:53 -07004602
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004603 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4604 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004605
4606 // Skip verification if disabled.
4607 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004608 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004609 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004610 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004611 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004612 }
4613
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004614 VLOG(class_linker) << "Beginning verification for class: "
4615 << klass->PrettyDescriptor()
4616 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4617
Ian Rogers9ffb0392012-09-10 11:56:50 -07004618 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004619 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004620 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4621 // If we have a superclass and we get a hard verification failure we can return immediately.
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004622 if (supertype != nullptr &&
4623 !AttemptSupertypeVerification(self, verifier_deps, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004624 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004625 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004626 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004627
Alex Lightf1f10492015-10-07 16:08:36 -07004628 // Verify all default super-interfaces.
4629 //
4630 // (1) Don't bother if the superclass has already had a soft verification failure.
4631 //
4632 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4633 // recursive initialization by themselves. This is because when an interface is initialized
4634 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4635 // but choose not to for an optimization. If the interfaces is being verified due to a class
4636 // initialization (which would need all the default interfaces to be verified) the class code
4637 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004638 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004639 && !klass->IsInterface()) { // See (2)
4640 int32_t iftable_count = klass->GetIfTableCount();
4641 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4642 // Loop through all interfaces this class has defined. It doesn't matter the order.
4643 for (int32_t i = 0; i < iftable_count; i++) {
4644 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004645 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004646 // We only care if we have default interfaces and can skip if we are already verified...
4647 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4648 continue;
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004649 } else if (UNLIKELY(!AttemptSupertypeVerification(self, verifier_deps, klass, iface))) {
Alex Lightf1f10492015-10-07 16:08:36 -07004650 // We had a hard failure while verifying this interface. Just return immediately.
4651 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004652 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004653 } else if (UNLIKELY(!iface->IsVerified())) {
4654 // We softly failed to verify the iface. Stop checking and clean up.
4655 // Put the iface into the supertype handle so we know what caused us to fail.
4656 supertype.Assign(iface.Get());
4657 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004658 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004659 }
4660 }
4661
Alex Lightf1f10492015-10-07 16:08:36 -07004662 // At this point if verification failed, then supertype is the "first" supertype that failed
4663 // verification (without a specific order). If verification succeeded, then supertype is either
4664 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004665 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004666 supertype.Get() == klass->GetSuperClass() ||
4667 !supertype->IsVerified());
4668
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004669 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004670 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004671 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004672 bool preverified = VerifyClassUsingOatFile(self, dex_file, klass, oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004673
4674 VLOG(class_linker) << "Class preverified status for class "
4675 << klass->PrettyDescriptor()
4676 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4677 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004678 << preverified
4679 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004680
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004681 // If the oat file says the class had an error, re-run the verifier. That way we will either:
4682 // 1) Be successful at runtime, or
4683 // 2) Get a precise error message.
Vladimir Marko72ab6842017-01-20 19:32:50 +00004684 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004685
Ian Rogers62d6c772013-02-27 08:32:07 -08004686 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004687 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004688 if (!preverified) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004689 verifier_failure = PerformClassVerification(self, verifier_deps, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004690 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004691
4692 // Verification is done, grab the lock again.
4693 ObjectLock<mirror::Class> lock(self, klass);
4694
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004695 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4696 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004697 VLOG(class_linker) << "Soft verification failure in class "
4698 << klass->PrettyDescriptor()
4699 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4700 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004701 }
Ian Rogers1f539342012-10-03 21:09:42 -07004702 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004703 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004704 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004705 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004706 // Even though there were no verifier failures we need to respect whether the super-class and
4707 // super-default-interfaces were verified or requiring runtime reverification.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004708 if (supertype == nullptr
4709 || supertype->IsVerified()
4710 || supertype->IsVerifiedNeedsAccessChecks()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004711 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004712 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004713 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004714 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4715 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004716 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004717 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004718 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004719 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004720 CHECK(verifier_failure == verifier::FailureKind::kSoftFailure ||
Nicolas Geoffrayd1728bf2021-01-12 14:02:29 +00004721 verifier_failure == verifier::FailureKind::kTypeChecksFailure ||
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004722 verifier_failure == verifier::FailureKind::kAccessChecksFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004723 // Soft failures at compile time should be retried at runtime. Soft
4724 // failures at runtime will be handled by slow paths in the generated
4725 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004726 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffrayd1728bf2021-01-12 14:02:29 +00004727 if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4728 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004729 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4730 } else {
4731 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4732 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004733 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004734 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004735 // As this is a fake verified status, make sure the methods are _not_ marked
4736 // kAccSkipAccessChecks later.
4737 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004738 }
4739 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004740 } else {
David Sehr709b0702016-10-13 09:12:37 -07004741 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004742 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4743 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004744 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004745 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004746 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004747 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004748 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004749 if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks ||
4750 UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
Igor Murashkindf707e42016-02-02 16:56:50 -08004751 // Never skip access checks if the verification soft fail is forced.
4752 // Mark the class as having a verification attempt to avoid re-running the verifier.
4753 klass->SetVerificationAttempted();
4754 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004755 // Class is verified so we don't need to do any access check on its methods.
4756 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
4757 // method.
4758 // Note: we're going here during compilation and at runtime. When we set the
4759 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
4760 // in the image and is set when loading the image.
Andreas Gampecc1b5352016-12-01 16:58:38 -08004761 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004762 }
Andreas Gampe48498592014-09-10 19:48:05 -07004763 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004764 // Done verifying. Notify the compiler about the verification status, in case the class
4765 // was verified implicitly (eg super class of a compiled class).
4766 if (Runtime::Current()->IsAotCompiler()) {
4767 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4768 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4769 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004770 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004771}
4772
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004773verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004774 verifier::VerifierDeps* verifier_deps,
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004775 Handle<mirror::Class> klass,
4776 verifier::HardFailLogMode log_level,
4777 std::string* error_msg) {
4778 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004779 return verifier::ClassVerifier::VerifyClass(self,
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00004780 verifier_deps,
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004781 klass.Get(),
4782 runtime->GetCompilerCallbacks(),
4783 runtime->IsAotCompiler(),
4784 log_level,
4785 Runtime::Current()->GetTargetSdkVersion(),
4786 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004787}
4788
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004789bool ClassLinker::VerifyClassUsingOatFile(Thread* self,
4790 const DexFile& dex_file,
4791 Handle<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004792 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004793 // If we're compiling, we can only verify the class using the oat file if
4794 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004795 // the compilation unit (app - dependencies). We will let the compiler callback
4796 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004797 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004798 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004799 // We are compiling an app (not the image).
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004800 if (!callbacks->CanUseOatStatusForVerification(klass.Get())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004801 return false;
4802 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004803 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004804
Andreas Gampeb40d3612018-06-26 15:49:42 -07004805 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004806 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004807 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004808 return false;
4809 }
4810
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004811 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004812 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004813 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004814 return true;
4815 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004816 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4817 // We return that the clas has already been verified, and the caller should
4818 // check the class status to ensure we run with access checks.
4819 return true;
4820 }
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004821
4822 // Check the class status with the vdex file.
4823 const OatFile* oat_file = oat_dex_file->GetOatFile();
4824 if (oat_file != nullptr) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004825 ClassStatus vdex_status = oat_file->GetVdexFile()->ComputeClassStatus(self, klass);
4826 if (vdex_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4827 oat_file_class_status = vdex_status;
Nicolas Geoffray6df45112021-02-07 21:51:58 +00004828 return true;
4829 }
4830 }
4831
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004832 // If we only verified a subset of the classes at compile time, we can end up with classes that
4833 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004834 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004835 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004836 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004837 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4838 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4839 << klass->PrettyClass() << " " << dex_file.GetLocation();
4840
Vladimir Marko72ab6842017-01-20 19:32:50 +00004841 if (mirror::Class::IsErroneous(oat_file_class_status)) {
Nicolas Geoffray44dc8a32021-06-21 15:23:49 +01004842 // Compile time verification failed with a hard error. We'll re-run
4843 // verification, which might be successful at runtime.
jeffhao1ac29442012-03-26 11:37:32 -07004844 return false;
4845 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004846 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004847 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4848 // not loading the class.
4849 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4850 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004851 return false;
4852 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004853 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004854 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004855 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004856 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004857 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004858}
4859
Alex Light5a559862016-01-29 12:24:48 -08004860void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004861 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004862 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004863 }
4864}
4865
Alex Light5a559862016-01-29 12:24:48 -08004866void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004867 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004868 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004869 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004870 return; // native or abstract method
4871 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004872 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004873 return; // nothing to process
4874 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004875 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004876 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004877 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4878 CatchHandlerIterator iterator(handlers_ptr);
4879 for (; iterator.HasNext(); iterator.Next()) {
4880 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4881 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004882 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004883 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004884 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004885 DCHECK(Thread::Current()->IsExceptionPending());
4886 Thread::Current()->ClearException();
4887 }
4888 }
4889 }
4890 handlers_ptr = iterator.EndDataPointer();
4891 }
4892}
4893
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004894ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4895 jstring name,
4896 jobjectArray interfaces,
4897 jobject loader,
4898 jobjectArray methods,
4899 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004900 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004901
4902 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4903 // code to be executed. We put it up here so we can avoid all the allocations associated with
4904 // creating the class. This can happen with (eg) jit-threads.
4905 if (!self->CanLoadClasses()) {
4906 // Make sure we don't try to load anything, potentially causing an infinite loop.
4907 ObjPtr<mirror::Throwable> pre_allocated =
4908 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4909 self->SetException(pre_allocated);
4910 return nullptr;
4911 }
4912
Alex Light133987d2020-03-26 19:22:12 +00004913 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004914 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004915 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004916 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004917 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004918 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004919 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004920 DCHECK(temp_klass->GetClass() != nullptr);
4921 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004922 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4923 // the methods.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004924 temp_klass->SetAccessFlagsDuringLinking(
4925 kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004926 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4927 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4928 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004929 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004930 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004931 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004932 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004933 std::string storage;
4934 const char* descriptor = temp_klass->GetDescriptor(&storage);
4935 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004936
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004937 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004938 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004939
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004940 // Insert the class before loading the fields as the field roots
4941 // (ArtField::declaring_class_) are only visited from the class
4942 // table. There can't be any suspend points between inserting the
4943 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004944 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004945 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004946
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004947 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004948 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004949 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004950 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004951
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004952 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4953 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004954 ArtField& interfaces_sfield = sfields->At(0);
4955 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004956 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004957 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004958
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004959 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004960 ArtField& throws_sfield = sfields->At(1);
4961 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004962 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004963 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004964
Ian Rogers466bb252011-10-14 03:29:56 -07004965 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004966 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004967
Alex Light133987d2020-03-26 19:22:12 +00004968 // The array we get passed contains all methods, including private and static
4969 // ones that aren't proxied. We need to filter those out since only interface
4970 // methods (non-private & virtual) are actually proxied.
4971 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4972 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004973 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004974 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004975 // List of the actual virtual methods this class will have.
4976 std::vector<ArtMethod*> proxied_methods;
4977 std::vector<size_t> proxied_throws_idx;
4978 proxied_methods.reserve(h_methods->GetLength());
4979 proxied_throws_idx.reserve(h_methods->GetLength());
4980 // Filter out to only the non-private virtual methods.
4981 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4982 ArtMethod* m = mirror->GetArtMethod();
4983 if (!m->IsPrivate() && !m->IsStatic()) {
4984 proxied_methods.push_back(m);
4985 proxied_throws_idx.push_back(idx);
4986 }
4987 }
4988 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004989 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4990 // contains an array of all the classes each function is declared to throw.
4991 // This is used to wrap unexpected exceptions in a
4992 // UndeclaredThrowableException exception. This array is in the same order as
4993 // the methods array and like the methods array must be filtered to remove any
4994 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004995 const bool has_filtered_methods =
4996 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4997 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4998 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4999 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
5000 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
5001 (has_filtered_methods)
5002 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
5003 self, original_proxied_throws->GetClass(), num_virtual_methods)
5004 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07005005 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
5006 self->AssertPendingOOMException();
5007 return nullptr;
5008 }
Alex Light133987d2020-03-26 19:22:12 +00005009 if (has_filtered_methods) {
5010 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
5011 DCHECK_LE(new_idx, orig_idx);
5012 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
5013 }
5014 }
Alex Lighte64300b2015-12-15 15:02:47 -08005015
5016 // Create the methods array.
5017 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
5018 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005019 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
5020 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08005021 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005022 self->AssertPendingOOMException();
5023 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005024 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005025 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005026
5027 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005028 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005029
5030 // Create virtual method using specified prototypes.
5031 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005032 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005033 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005034 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005035 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005036 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5037 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005038 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005039
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005040 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005041 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005042 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005043 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005044 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005045
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005046 // At this point the class is loaded. Publish a ClassLoad event.
5047 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5048 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5049
5050 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005051 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005052 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005053 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005054 // Link the fields and virtual methods, creating vtable and iftables.
5055 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005056 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005057 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005058 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005059 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005060 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005061 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005062 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005063 CHECK(temp_klass->IsRetired());
5064 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005065
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005066 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005067 interfaces_sfield.SetObject<false>(
5068 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005069 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005070 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5071 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005072 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00005073 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005074
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005075 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5076
Vladimir Marko305c38b2018-02-14 11:50:07 +00005077 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5078 // See also ClassLinker::EnsureInitialized().
5079 if (kBitstringSubtypeCheckEnabled) {
5080 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5081 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5082 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5083 }
5084
Vladimir Markobf121912019-06-04 13:49:05 +01005085 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005086 {
5087 // Lock on klass is released. Lock new class object.
5088 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005089 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005090 // Conservatively go through the ClassStatus::kInitialized state.
5091 callback = MarkClassInitialized(self, klass);
5092 }
5093 if (callback != nullptr) {
5094 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005095 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005096
David Srbecky346fd962020-07-27 16:51:00 +01005097 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07005098 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005099 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005100 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5101
Ian Rogersc2b44472011-12-14 21:17:17 -08005102 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005103 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005104 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08005105 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005106
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005107 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005108 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005109 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005110 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005111 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005112
5113 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005114 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005115 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005116
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005117 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005118 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005119 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005120 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005121 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005122 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005123}
5124
Mathieu Chartiere401d142015-04-22 13:56:20 -07005125void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5126 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005127 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5128 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005129
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005130 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5131 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005132 ArtMethod* proxy_constructor =
5133 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005134 DCHECK(proxy_constructor != nullptr)
5135 << "Could not find <init> method in java.lang.reflect.Proxy";
5136
Jeff Haodb8a6642014-08-14 17:18:52 -07005137 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5138 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005139 DCHECK(out != nullptr);
5140 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005141 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005142 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005143 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005144 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5145 kAccPublic |
5146 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005147 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005148
5149 // Set the original constructor method.
5150 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005151}
5152
Mathieu Chartiere401d142015-04-22 13:56:20 -07005153void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005154 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005155 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5156 CHECK_STREQ(np->GetName(), "<init>");
5157 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005158 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005159}
5160
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005161void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005162 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005163 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005164 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005165 DCHECK(out != nullptr);
5166 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005167
Alex Lighte9dd04f2016-03-16 16:09:45 -07005168 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005169 out->SetDeclaringClass(klass.Get());
Vladimir Markode0d0de2021-03-18 14:12:35 +00005170 // Clear the abstract and default flags to ensure that defaults aren't picked in
Alex Lighte9dd04f2016-03-16 16:09:45 -07005171 // preference to the invocation handler.
Vladimir Markode0d0de2021-03-18 14:12:35 +00005172 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005173 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005174 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5175 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005176 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5177
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005178 // Set the original interface method.
5179 out->SetDataPtrSize(prototype, image_pointer_size_);
5180
Ian Rogers466bb252011-10-14 03:29:56 -07005181 // At runtime the method looks like a reference and argument saving method, clone the code
5182 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005183 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005184}
Jesse Wilson95caa792011-10-12 18:14:17 -04005185
Mathieu Chartiere401d142015-04-22 13:56:20 -07005186void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005187 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005188 CHECK(!prototype->IsFinal());
5189 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005190 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005191
5192 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5193 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005194 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005195 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005196}
5197
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005198bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005199 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005200 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005201 return true;
5202 }
5203 if (!can_init_statics) {
5204 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005205 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005206 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005207 return false;
5208 }
5209 // Check if there are encoded static values needing initialization.
5210 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005211 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005212 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005213 if (dex_class_def->static_values_off_ != 0) {
5214 return false;
5215 }
5216 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005217 }
5218 // If we are a class we need to initialize all interfaces with default methods when we are
5219 // initialized. Check all of them.
5220 if (!klass->IsInterface()) {
5221 size_t num_interfaces = klass->GetIfTableCount();
5222 for (size_t i = 0; i < num_interfaces; i++) {
5223 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5224 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5225 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005226 return false;
5227 }
5228 }
5229 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005230 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005231 if (klass->IsInterface() || !klass->HasSuperClass()) {
5232 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005233 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005234 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005235 if (super_class->IsInitialized()) {
5236 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005237 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005238 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005239}
5240
Mathieu Chartier23369542020-03-04 08:24:11 -08005241bool ClassLinker::InitializeClass(Thread* self,
5242 Handle<mirror::Class> klass,
5243 bool can_init_statics,
5244 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005245 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5246
5247 // Are we already initialized and therefore done?
5248 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5249 // an initialized class will never change its state.
5250 if (klass->IsInitialized()) {
5251 return true;
5252 }
5253
5254 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005255 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005256 return false;
5257 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005258
Ian Rogers7b078e82014-09-10 14:44:24 -07005259 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005260 Runtime* const runtime = Runtime::Current();
5261 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005262 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005263 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005264 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005265
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005266 // Re-check under the lock in case another thread initialized ahead of us.
5267 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005268 return true;
5269 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005270
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005271 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005272 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005273 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005274 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005275 return false;
5276 }
5277
Vladimir Marko72ab6842017-01-20 19:32:50 +00005278 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5279 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005280
5281 if (!klass->IsVerified()) {
Nicolas Geoffray5b0b2e12021-03-19 14:48:40 +00005282 VerifyClass(self, /*verifier_deps= */ nullptr, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005283 if (!klass->IsVerified()) {
5284 // We failed to verify, expect either the klass to be erroneous or verification failed at
5285 // compile time.
5286 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005287 // The class is erroneous. This may be a verifier error, or another thread attempted
5288 // verification and/or initialization and failed. We can distinguish those cases by
5289 // whether an exception is already pending.
5290 if (self->IsExceptionPending()) {
5291 // Check that it's a VerifyError.
5292 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005293 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005294 } else {
5295 // Check that another thread attempted initialization.
5296 DCHECK_NE(0, klass->GetClinitThreadId());
5297 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5298 // Need to rethrow the previous failure now.
5299 ThrowEarlierClassFailure(klass.Get(), true);
5300 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005301 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005302 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005303 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005304 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005305 self->AssertNoPendingException();
5306 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005307 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005308 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005309 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005310 } else {
5311 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005312 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005313
5314 // A separate thread could have moved us all the way to initialized. A "simple" example
5315 // involves a subclass of the current class being initialized at the same time (which
5316 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005317 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005318 if (klass->IsInitialized()) {
5319 return true;
5320 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005321 }
5322
Vladimir Marko2c64a832018-01-04 11:31:56 +00005323 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005324 // initializing higher up the stack or another thread has beat us
5325 // to initializing and we need to wait. Either way, this
5326 // invocation of InitializeClass will not be responsible for
5327 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005328 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005329 // Could have got an exception during verification.
5330 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005331 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005332 return false;
5333 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005334 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005335 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005336 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005337 return true;
5338 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005339 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005340 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005341 }
5342
Jeff Haoe2e40342017-07-19 10:45:18 -07005343 // Try to get the oat class's status for this class if the oat file is present. The compiler
5344 // tries to validate superclass descriptors, and writes the result into the oat file.
5345 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5346 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5347 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005348 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005349 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5350 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5351 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005352 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005353 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005354 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005355 return false;
5356 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005357 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005358
Vladimir Marko2c64a832018-01-04 11:31:56 +00005359 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005360 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005361
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005362 // From here out other threads may observe that we're initializing and so changes of state
5363 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005364 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005365 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005366
Mathieu Chartier23369542020-03-04 08:24:11 -08005367 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005368 }
5369
Andreas Gampeaf864702019-07-23 14:05:35 -07005370 uint64_t t_sub = 0;
5371
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005372 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005373 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005374 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005375 if (!super_class->IsInitialized()) {
5376 CHECK(!super_class->IsInterface());
5377 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005378 StackHandleScope<1> hs(self);
5379 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005380 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005381 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005382 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005383 if (!super_initialized) {
5384 // The super class was verified ahead of entering initializing, we should only be here if
5385 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005386 // For the case of aot compiler, the super class might also be initializing but we don't
5387 // want to process circular dependencies in pre-compile.
5388 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005389 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005390 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005391 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005392 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005393 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005394 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005395 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005396 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005397 return false;
5398 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005399 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005400 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005401 }
5402
Alex Lighteb7c1442015-08-31 13:17:42 -07005403 if (!klass->IsInterface()) {
5404 // Initialize interfaces with default methods for the JLS.
5405 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005406 // Only setup the (expensive) handle scope if we actually need to.
5407 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005408 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005409 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5410 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005411 handle_scope_iface.Assign(klass->GetDirectInterface(i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005412 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005413 CHECK(handle_scope_iface->IsInterface());
5414 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5415 // We have already done this for this interface. Skip it.
5416 continue;
5417 }
5418 // We cannot just call initialize class directly because we need to ensure that ALL
5419 // interfaces with default methods are initialized. Non-default interface initialization
5420 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005421 // This is not very precise, misses all walking.
5422 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005423 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5424 handle_scope_iface,
5425 can_init_statics,
5426 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005427 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005428 if (!iface_initialized) {
5429 ObjectLock<mirror::Class> lock(self, klass);
5430 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005431 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005432 return false;
5433 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005434 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005435 }
5436 }
5437 }
5438
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005439 const size_t num_static_fields = klass->NumStaticFields();
5440 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005441 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005442 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005443 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005444 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005445 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005446
5447 // Eagerly fill in static fields so that the we don't have to do as many expensive
5448 // Class::FindStaticField in ResolveField.
5449 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005450 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005451 const uint32_t field_idx = field->GetDexFieldIndex();
David Srbecky5de5efe2021-02-15 21:23:00 +00005452 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005453 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005454 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005455 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5456 field,
5457 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5458 hiddenapi::AccessMethod::kNone));
David Srbecky5de5efe2021-02-15 21:23:00 +00005459 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005460 } else {
5461 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005462 }
5463 }
5464
Vladimir Markoe11dd502017-12-08 14:09:45 +00005465 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5466 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005467 this,
5468 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005469 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005470
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005471 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005472 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005473 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005474 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5475 if (!value_it.HasNext()) {
5476 break;
5477 }
5478 ArtField* art_field = ResolveField(field.GetIndex(),
5479 dex_cache,
5480 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005481 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005482 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005483 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005484 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005485 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005486 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005487 if (self->IsExceptionPending()) {
5488 break;
5489 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005490 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005491 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005492 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005493 }
5494 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005495
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005496
Mathieu Chartierda595be2016-08-10 13:57:39 -07005497 if (!self->IsExceptionPending()) {
5498 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5499 if (clinit != nullptr) {
5500 CHECK(can_init_statics);
5501 JValue result;
5502 clinit->Invoke(self, nullptr, 0, &result, "V");
5503 }
5504 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005505 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005506 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005507
Vladimir Markobf121912019-06-04 13:49:05 +01005508 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005509 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005510 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005511 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005512
5513 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005514 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005515 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005516 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005517 } else if (Runtime::Current()->IsTransactionAborted()) {
5518 // The exception thrown when the transaction aborted has been caught and cleared
5519 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005520 VLOG(compiler) << "Return from class initializer of "
5521 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005522 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005523 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005524 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005525 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005526 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005527 if (stats_enabled) {
5528 RuntimeStats* global_stats = runtime->GetStats();
5529 RuntimeStats* thread_stats = self->GetStats();
5530 ++global_stats->class_init_count;
5531 ++thread_stats->class_init_count;
5532 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5533 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5534 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005535 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005536 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005537 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005538 std::string temp;
5539 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005540 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005541 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005542 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005543 }
Vladimir Markobf121912019-06-04 13:49:05 +01005544 if (callback != nullptr) {
5545 callback->MakeVisible(self);
5546 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005547 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005548}
5549
Alex Lighteb7c1442015-08-31 13:17:42 -07005550// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5551// and perform the initialization only on those interfaces that contain default methods.
5552bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5553 Handle<mirror::Class> iface,
5554 bool can_init_statics,
5555 bool can_init_parents) {
5556 CHECK(iface->IsInterface());
5557 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005558 // Only create the (expensive) handle scope if we need it.
5559 if (UNLIKELY(num_direct_ifaces > 0)) {
5560 StackHandleScope<1> hs(self);
5561 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5562 // First we initialize all of iface's super-interfaces recursively.
5563 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01005564 ObjPtr<mirror::Class> super_iface = iface->GetDirectInterface(i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005565 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005566 if (!super_iface->HasBeenRecursivelyInitialized()) {
5567 // Recursive step
5568 handle_super_iface.Assign(super_iface);
5569 if (!InitializeDefaultInterfaceRecursive(self,
5570 handle_super_iface,
5571 can_init_statics,
5572 can_init_parents)) {
5573 return false;
5574 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005575 }
5576 }
5577 }
5578
5579 bool result = true;
5580 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5581 // initialize if we don't have default methods.
5582 if (iface->HasDefaultMethods()) {
5583 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5584 }
5585
5586 // Mark that this interface has undergone recursive default interface initialization so we know we
5587 // can skip it on any later class initializations. We do this even if we are not a default
5588 // interface since we can still avoid the traversal. This is purely a performance optimization.
5589 if (result) {
5590 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005591 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5592 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5593 // initialization is a performance optimization (to avoid another idempotent visit
5594 // for other implementing classes/interfaces), and can be revisited later.
5595 ObjectTryLock<mirror::Class> lock(self, iface);
5596 if (lock.Acquired()) {
5597 iface->SetRecursivelyInitialized();
5598 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005599 }
5600 return result;
5601}
5602
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005603bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5604 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005605 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005606 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005607 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005608 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005609 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005610 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005611
5612 // When we wake up, repeat the test for init-in-progress. If
5613 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005614 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005615 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005616 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005617 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005618 return false;
5619 }
5620 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005621 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005622 continue;
5623 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005624 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005625 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005626 // Compile time initialization failed.
5627 return false;
5628 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005629 if (klass->IsErroneous()) {
5630 // The caller wants an exception, but it was thrown in a
5631 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005632 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005633 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005634 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005635 return false;
5636 }
5637 if (klass->IsInitialized()) {
5638 return true;
5639 }
David Sehr709b0702016-10-13 09:12:37 -07005640 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005641 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005642 }
Ian Rogers07140832014-09-30 15:43:59 -07005643 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005644}
5645
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005646static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5647 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005648 ArtMethod* method,
5649 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005650 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005651 DCHECK(Thread::Current()->IsExceptionPending());
5652 DCHECK(!m->IsProxyMethod());
5653 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005654 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5655 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005656 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005657 std::string return_type = dex_file->PrettyType(return_type_idx);
5658 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005659 ThrowWrappedLinkageError(klass.Get(),
5660 "While checking class %s method %s signature against %s %s: "
5661 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005662 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5663 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005664 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005665 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005666 return_type.c_str(), class_loader.c_str());
5667}
5668
5669static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5670 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005671 ArtMethod* method,
5672 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005673 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005674 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005675 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005676 DCHECK(Thread::Current()->IsExceptionPending());
5677 DCHECK(!m->IsProxyMethod());
5678 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005679 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5680 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005681 ThrowWrappedLinkageError(klass.Get(),
5682 "While checking class %s method %s signature against %s %s: "
5683 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005684 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5685 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005686 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005687 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005688 index, arg_type.c_str(), class_loader.c_str());
5689}
5690
5691static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5692 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005693 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005694 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005695 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005696 ThrowLinkageError(klass.Get(),
5697 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005698 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5699 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005700 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005701 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005702 error_msg.c_str());
5703}
5704
Ian Rogersb5fb2072014-12-02 17:22:02 -08005705static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005706 Handle<mirror::Class> klass,
5707 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005708 ArtMethod* method1,
5709 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005710 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005711 {
5712 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005713 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005714 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005715 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005716 return false;
5717 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005718 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005719 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005720 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005721 return false;
5722 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005723 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005724 ThrowSignatureMismatch(klass, super_klass, method1,
5725 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005726 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005727 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005728 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005729 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005730 return false;
5731 }
5732 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005733 const dex::TypeList* types1 = method1->GetParameterTypeList();
5734 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005735 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005736 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005737 ThrowSignatureMismatch(klass, super_klass, method1,
5738 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005739 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005740 return false;
5741 }
5742 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005743 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005744 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005745 ThrowSignatureMismatch(klass, super_klass, method1,
5746 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005747 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005748 return false;
5749 }
5750 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005751 }
5752 uint32_t num_types = types1->Size();
5753 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005754 ThrowSignatureMismatch(klass, super_klass, method1,
5755 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005756 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005757 return false;
5758 }
5759 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005760 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005761 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005762 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005763 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005764 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005765 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005766 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005767 return false;
5768 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005769 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005770 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005771 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005772 if (UNLIKELY(other_param_type == nullptr)) {
5773 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005774 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005775 return false;
5776 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005777 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005778 ThrowSignatureMismatch(klass, super_klass, method1,
5779 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5780 i,
David Sehr709b0702016-10-13 09:12:37 -07005781 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005782 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005783 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005784 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005785 return false;
5786 }
5787 }
5788 return true;
5789}
5790
5791
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005792bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005793 if (klass->IsInterface()) {
5794 return true;
5795 }
Ian Rogers151f2212014-05-06 11:27:27 -07005796 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005797 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005798 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005799 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005800 if (klass->HasSuperClass() &&
5801 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005802 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005803 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005804 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5805 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5806 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005807 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5808 klass,
5809 super_klass,
5810 m,
5811 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005812 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005813 return false;
5814 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005815 }
5816 }
5817 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005818 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005819 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5820 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5821 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005822 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005823 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5824 j, image_pointer_size_);
5825 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5826 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005827 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5828 klass,
5829 super_klass,
5830 m,
5831 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005832 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005833 return false;
5834 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005835 }
5836 }
5837 }
5838 }
5839 return true;
5840}
5841
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005842bool ClassLinker::EnsureInitialized(Thread* self,
5843 Handle<mirror::Class> c,
5844 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005845 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005846 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005847
Mathieu Chartier524507a2014-08-27 15:28:28 -07005848 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005849 // If we've seen an initialized but not visibly initialized class
5850 // many times, request visible initialization.
5851 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5852 // Thanks to the x86 memory model classes skip the initialized status.
5853 DCHECK(c->IsVisiblyInitialized());
5854 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5855 if (self->IncrementMakeVisiblyInitializedCounter()) {
5856 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5857 }
5858 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005859 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005860 return true;
5861 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005862 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5863 //
5864 // Ensure the bitstring is initialized before any of the class initialization
5865 // logic occurs. Once a class initializer starts running, objects can
5866 // escape into the heap and use the subtype checking code.
5867 //
5868 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5869 // can be used as a source for the IsSubClass check, and that all ancestors
5870 // of the class are Assigned (can be used as a target for IsSubClass check)
5871 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005872 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005873 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005874 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005875 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5876 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005877 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005878 if (!success) {
5879 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005880 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Vladimir Markoac576912021-03-31 11:16:22 +01005881 } else {
5882 // There may or may not be an exception pending. If there is, clear it.
5883 // We propagate the exception only if we can initialize fields and parents.
5884 self->ClearException();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005885 }
5886 } else {
5887 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005888 }
5889 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005890}
5891
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005892void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5893 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005894 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005895 for (ArtField& field : new_class->GetIFields()) {
5896 if (field.GetDeclaringClass() == temp_class) {
5897 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005898 }
5899 }
5900
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005901 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005902 for (ArtField& field : new_class->GetSFields()) {
5903 if (field.GetDeclaringClass() == temp_class) {
5904 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005905 }
5906 }
5907
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005908 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005909 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005910 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005911 if (method.GetDeclaringClass() == temp_class) {
5912 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005913 }
5914 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005915
5916 // Make sure the remembered set and mod-union tables know that we updated some of the native
5917 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005918 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005919}
5920
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005921void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005922 CHECK(class_loader->GetAllocator() == nullptr);
5923 CHECK(class_loader->GetClassTable() == nullptr);
5924 Thread* const self = Thread::Current();
5925 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005926 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005927 // Create and set the class table.
5928 data.class_table = new ClassTable;
5929 class_loader->SetClassTable(data.class_table);
5930 // Create and set the linear allocator.
5931 data.allocator = Runtime::Current()->CreateLinearAlloc();
5932 class_loader->SetAllocator(data.allocator);
5933 // Add to the list so that we know to free the data later.
5934 class_loaders_.push_back(data);
5935}
5936
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005937ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005938 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005939 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005940 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005941 ClassTable* class_table = class_loader->GetClassTable();
5942 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005943 RegisterClassLoader(class_loader);
5944 class_table = class_loader->GetClassTable();
5945 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005946 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005947 return class_table;
5948}
5949
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005950ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005951 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005952}
5953
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005954static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005955 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005956 while (klass->HasSuperClass()) {
5957 klass = klass->GetSuperClass();
5958 if (klass->ShouldHaveImt()) {
5959 return klass->GetImt(pointer_size);
5960 }
5961 }
5962 return nullptr;
5963}
5964
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005965bool ClassLinker::LinkClass(Thread* self,
5966 const char* descriptor,
5967 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005968 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005969 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005970 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005971
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005972 if (!LinkSuperClass(klass)) {
5973 return false;
5974 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005975 ArtMethod* imt_data[ImTable::kSize];
5976 // If there are any new conflicts compared to super class.
5977 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005978 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005979 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005980 return false;
5981 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005982 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005983 return false;
5984 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005985 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005986 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005987 return false;
5988 }
5989 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005990 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005991
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005992 ImTable* imt = nullptr;
5993 if (klass->ShouldHaveImt()) {
5994 // If there are any new conflicts compared to the super class we can not make a copy. There
5995 // can be cases where both will have a conflict method at the same slot without having the same
5996 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5997 // will possibly create a table that is incorrect for either of the classes.
5998 // Same IMT with new_conflict does not happen very often.
5999 if (!new_conflict) {
6000 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
6001 if (super_imt != nullptr) {
6002 bool imt_equals = true;
6003 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
6004 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
6005 }
6006 if (imt_equals) {
6007 imt = super_imt;
6008 }
6009 }
6010 }
6011 if (imt == nullptr) {
6012 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
6013 imt = reinterpret_cast<ImTable*>(
6014 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
6015 if (imt == nullptr) {
6016 return false;
6017 }
6018 imt->Populate(imt_data, image_pointer_size_);
6019 }
6020 }
6021
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006022 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
6023 // We don't need to retire this class as it has no embedded tables or it was created the
6024 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006025 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006026
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006027 if (klass->ShouldHaveEmbeddedVTable()) {
6028 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006029 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006030 if (klass->ShouldHaveImt()) {
6031 klass->SetImt(imt, image_pointer_size_);
6032 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006033
6034 // Update CHA info based on whether we override methods.
6035 // Have to do this before setting the class as resolved which allows
6036 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006037 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006038 cha_->UpdateAfterLoadingOf(klass);
6039 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006040
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006041 // This will notify waiters on klass that saw the not yet resolved
6042 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006043 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006044 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006045 } else {
6046 CHECK(!klass->IsResolved());
6047 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006048 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006049 Handle<mirror::Class> h_new_class =
6050 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006051 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6052 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6053 // may not see any references to the target space and clean the card for a class if another
6054 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006055 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006056 klass->SetSFieldsPtrUnchecked(nullptr);
6057 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006058 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006059 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006060 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006061 return false;
6062 }
6063
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006064 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6065 ObjectLock<mirror::Class> lock(self, h_new_class);
6066 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006067
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006068 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006069 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006070 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006071 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006072 const ObjPtr<mirror::Class> existing =
6073 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006074 if (class_loader != nullptr) {
6075 // We updated the class in the class table, perform the write barrier so that the GC knows
6076 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006077 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006078 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006079 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006080 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006081 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6082 }
6083 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006084
Mingyao Yang063fc772016-08-02 11:02:54 -07006085 // Update CHA info based on whether we override methods.
6086 // Have to do this before setting the class as resolved which allows
6087 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006088 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006089 cha_->UpdateAfterLoadingOf(h_new_class);
6090 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006091
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006092 // This will notify waiters on temp class that saw the not yet resolved class in the
6093 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006094 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006095
Vladimir Marko2c64a832018-01-04 11:31:56 +00006096 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006097 // This will notify waiters on new_class that saw the not yet resolved
6098 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006099 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006100 // Return the new class.
6101 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006102 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006103 return true;
6104}
6105
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006106bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006107 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006108 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006109 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6110 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006111 // Check that a class does not inherit from itself directly.
6112 //
6113 // TODO: This is a cheap check to detect the straightforward case
6114 // of a class extending itself (b/28685551), but we should do a
6115 // proper cycle detection on loaded classes, to detect all cases
6116 // of class circularity errors (b/28830038).
6117 if (super_class_idx == class_def.class_idx_) {
6118 ThrowClassCircularityError(klass.Get(),
6119 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006120 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006121 return false;
6122 }
6123
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006124 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006125 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006126 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006127 return false;
6128 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006129 // Verify
6130 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006131 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006132 super_class->PrettyDescriptor().c_str(),
6133 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006134 return false;
6135 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006136 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006137 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006138 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006139 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006140 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006141 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006142 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006143 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006144 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006145 DCHECK(Thread::Current()->IsExceptionPending());
6146 return false;
6147 }
6148 // Verify
6149 if (!klass->CanAccess(interface)) {
6150 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006151 ThrowIllegalAccessError(klass.Get(),
6152 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006153 interface->PrettyDescriptor().c_str(),
6154 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006155 return false;
6156 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006157 }
6158 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006159 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006160 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006161 return true;
6162}
6163
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006164bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006165 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006166 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006167 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6168 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006169 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006170 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006171 return false;
6172 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006173 return true;
6174 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006175 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006176 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006177 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006178 return false;
6179 }
6180 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006181 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006182 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6183 return false;
6184 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006185 if (super->IsFinal()) {
6186 ThrowVerifyError(klass.Get(),
6187 "Superclass %s of %s is declared final",
6188 super->PrettyDescriptor().c_str(),
6189 klass->PrettyDescriptor().c_str());
6190 return false;
6191 }
6192 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006193 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006194 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006195 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006196 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006197 return false;
6198 }
6199 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006200 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006201 super->PrettyDescriptor().c_str(),
6202 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006203 return false;
6204 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006205
Brian Carlstromf3632832014-05-20 15:36:53 -07006206 // Inherit kAccClassIsFinalizable from the superclass in case this
6207 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006208 if (super->IsFinalizable()) {
6209 klass->SetFinalizable();
6210 }
6211
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006212 // Inherit class loader flag form super class.
6213 if (super->IsClassLoaderClass()) {
6214 klass->SetClassLoaderClass();
6215 }
6216
Elliott Hughes2da50362011-10-10 16:57:08 -07006217 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006218 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006219 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006220 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006221 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006222 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006223 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006224 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006225 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006226 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006227 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006228 return false;
6229 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006230
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006231 if (kIsDebugBuild) {
6232 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006233 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006234 CHECK(super->IsResolved());
6235 super = super->GetSuperClass();
6236 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006237 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006238 return true;
6239}
6240
Vladimir Marko782fb712020-12-23 12:47:31 +00006241// A wrapper class representing the result of a method translation used for linking methods and
6242// updating superclass default methods. For each method in a classes vtable there are 4 states it
6243// could be in:
6244// 1) No translation is necessary. In this case there is no MethodTranslation object for it. This
6245// is the standard case and is true when the method is not overridable by a default method,
6246// the class defines a concrete implementation of the method, the default method implementation
6247// remains the same, or an abstract method stayed abstract.
6248// 2) The method must be translated to a different default method. We note this with
6249// CreateTranslatedMethod.
6250// 3) The method must be replaced with a conflict method. This happens when a superclass
6251// implements an interface with a default method and this class implements an unrelated
6252// interface that also defines that default method. We note this with CreateConflictingMethod.
6253// 4) The method must be replaced with an abstract miranda method. This happens when a superclass
6254// implements an interface with a default method and this class implements a subinterface of
6255// the superclass's interface which declares the default method abstract. We note this with
6256// CreateAbstractMethod.
6257//
6258// When a method translation is unnecessary (case #1), we don't put it into the
6259// default_translation maps. So an instance of MethodTranslation must be in one of #2-#4.
6260class ClassLinker::MethodTranslation {
6261 public:
6262 MethodTranslation() : translation_(nullptr), type_(Type::kInvalid) {}
6263
6264 // This slot must become a default conflict method.
6265 static MethodTranslation CreateConflictingMethod() {
6266 return MethodTranslation(Type::kConflict, /*translation=*/nullptr);
6267 }
6268
6269 // This slot must become an abstract method.
6270 static MethodTranslation CreateAbstractMethod() {
6271 return MethodTranslation(Type::kAbstract, /*translation=*/nullptr);
6272 }
6273
6274 // Use the given method as the current value for this vtable slot during translation.
6275 static MethodTranslation CreateTranslatedMethod(ArtMethod* new_method) {
6276 return MethodTranslation(Type::kTranslation, new_method);
6277 }
6278
6279 // Returns true if this is a method that must become a conflict method.
6280 bool IsInConflict() const {
6281 return type_ == Type::kConflict;
6282 }
6283
6284 // Returns true if this is a method that must become an abstract method.
6285 bool IsAbstract() const {
6286 return type_ == Type::kAbstract;
6287 }
6288
6289 // Returns true if this is a method that must become a different method.
6290 bool IsTranslation() const {
6291 return type_ == Type::kTranslation;
6292 }
6293
6294 // Get the translated version of this method.
6295 ArtMethod* GetTranslation() const {
6296 DCHECK(IsTranslation());
6297 DCHECK(translation_ != nullptr);
6298 return translation_;
6299 }
6300
6301 private:
6302 enum class Type {
6303 kInvalid,
6304 kTranslation,
6305 kConflict,
6306 kAbstract,
6307 };
6308
6309 MethodTranslation(Type type, ArtMethod* translation)
6310 : translation_(translation), type_(type) {}
6311
6312 ArtMethod* translation_;
6313 Type type_;
6314};
6315
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006316// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006317bool ClassLinker::LinkMethods(Thread* self,
6318 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006319 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006320 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006321 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006322 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006323 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6324 // need to have default methods be in the virtuals array of each class but we don't set that up
6325 // until LinkInterfaceMethods.
Vladimir Marko782fb712020-12-23 12:47:31 +00006326 constexpr size_t kBufferSize = 8; // Avoid malloc/free for a few translations.
6327 std::pair<size_t, ClassLinker::MethodTranslation> buffer[kBufferSize];
6328 HashMap<size_t, ClassLinker::MethodTranslation> default_translations(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07006329 // Link virtual methods then interface methods.
6330 // We set up the interface lookup table first because we need it to determine if we need to update
6331 // any vtable entries with new default method implementations.
6332 return SetupInterfaceLookupTable(self, klass, interfaces)
6333 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006334 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006335}
6336
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006337// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6338// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6339// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006340class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006341 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006342 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006343 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006344 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6345 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006346 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006347 }
6348
6349 const char* GetName() {
6350 if (name_ == nullptr) {
6351 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6352 }
6353 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006354 }
6355
Mathieu Chartiere401d142015-04-22 13:56:20 -07006356 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006357 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006358 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006359 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006360 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006361 if (dex_file_ == other_dex_file) {
6362 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6363 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006364 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006365 uint32_t other_name_len;
6366 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6367 &other_name_len);
6368 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6369 return false;
6370 }
6371 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6372 }
6373
6374 private:
6375 // Dex file for the method to compare against.
6376 const DexFile* const dex_file_;
6377 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006378 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006379 // Lazily computed name from the dex file's strings.
6380 const char* name_;
6381 // Lazily computed name length.
6382 uint32_t name_len_;
6383};
6384
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006385class LinkVirtualHashTable {
6386 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006387 LinkVirtualHashTable(Handle<mirror::Class> klass,
6388 size_t hash_size,
6389 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006390 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006391 : klass_(klass),
6392 hash_size_(hash_size),
6393 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006394 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006395 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6396 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006397
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006398 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006399 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6400 virtual_method_index, image_pointer_size_);
6401 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006402 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006403 uint32_t index = hash % hash_size_;
6404 // Linear probe until we have an empty slot.
6405 while (hash_table_[index] != invalid_index_) {
6406 if (++index == hash_size_) {
6407 index = 0;
6408 }
6409 }
6410 hash_table_[index] = virtual_method_index;
6411 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006412
Vladimir Marko43354742021-02-03 15:37:01 +00006413 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator, uint32_t hash)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006414 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko43354742021-02-03 15:37:01 +00006415 DCHECK_EQ(hash, ComputeModifiedUtf8Hash(comparator->GetName()));
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006416 size_t index = hash % hash_size_;
6417 while (true) {
6418 const uint32_t value = hash_table_[index];
6419 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6420 // the block and can safely assume not found.
6421 if (value == invalid_index_) {
6422 break;
6423 }
6424 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006425 ArtMethod* virtual_method =
6426 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6427 if (comparator->HasSameNameAndSignature(
6428 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006429 hash_table_[index] = removed_index_;
6430 return value;
6431 }
6432 }
6433 if (++index == hash_size_) {
6434 index = 0;
6435 }
6436 }
6437 return GetNotFoundIndex();
6438 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006439
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006440 static uint32_t GetNotFoundIndex() {
6441 return invalid_index_;
6442 }
6443
6444 private:
6445 static const uint32_t invalid_index_;
6446 static const uint32_t removed_index_;
6447
6448 Handle<mirror::Class> klass_;
6449 const size_t hash_size_;
6450 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006451 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006452};
6453
6454const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6455const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6456
Stephen Hines1ddd9132017-02-08 01:51:18 -08006457bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006458 Thread* self,
6459 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00006460 /*out*/HashMap<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006461 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006462 if (klass->IsInterface()) {
6463 // No vtable.
6464 if (!IsUint<16>(num_virtual_methods)) {
6465 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6466 return false;
6467 }
6468 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006469 // Assign each method an IMT index and set the default flag.
6470 for (size_t i = 0; i < num_virtual_methods; ++i) {
6471 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6472 m->SetMethodIndex(i);
6473 if (!m->IsAbstract()) {
Vladimir Marko1c993cd2020-05-28 09:30:06 +00006474 // If the dex file does not support default methods, throw ClassFormatError.
6475 // This check is necessary to protect from odd cases, such as native default
6476 // methods, that the dex file verifier permits for old dex file versions. b/157170505
6477 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
6478 // currently running CTS tests for default methods with dex file version 035 which
6479 // does not support default methods. So, we limit this to native methods. b/157718952
6480 if (m->IsNative()) {
6481 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
6482 ThrowClassFormatError(klass.Get(),
6483 "Dex file does not support default method '%s'",
6484 m->PrettyMethod().c_str());
6485 return false;
6486 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006487 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6488 has_defaults = true;
6489 }
6490 }
6491 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6492 // during initialization. This is a performance optimization. We could simply traverse the
6493 // virtual_methods_ array again during initialization.
6494 if (has_defaults) {
6495 klass->SetHasDefaultMethods();
6496 }
6497 return true;
6498 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006499 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6500 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006501 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006502 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006503 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006504 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006505 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006506 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006507 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006508 return false;
6509 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006510 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006511 vtable->SetElementPtrSize(
6512 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006513 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006514 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6515 // might give us new default methods). If no new interfaces then we can skip the rest since
6516 // the class cannot override any of the super-class's methods. This is required for
6517 // correctness since without it we might not update overridden default method vtable entries
6518 // correctly.
6519 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006520 klass->SetVTable(vtable.Get());
6521 return true;
6522 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006523 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006524 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006525 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006526 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006527 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6528 // might give us new default methods). See comment above.
6529 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006530 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006531 return true;
6532 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006533 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6534 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006535 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006536 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006537 return false;
6538 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006539 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006540 // How the algorithm works:
6541 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6542 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6543 // method which has not been matched to a vtable method, and j if the virtual method at the
6544 // index overrode the super virtual method at index j.
6545 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6546 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6547 // the need for the initial vtable which we later shrink back down).
6548 // 3. Add non overridden methods to the end of the vtable.
6549 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006550 // + 1 so that even if we only have new default methods we will still be able to use this hash
6551 // table (i.e. it will never have 0 size).
6552 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006553 uint32_t* hash_table_ptr;
6554 std::unique_ptr<uint32_t[]> hash_heap_storage;
6555 if (hash_table_size <= kMaxStackHash) {
6556 hash_table_ptr = reinterpret_cast<uint32_t*>(
6557 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6558 } else {
6559 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6560 hash_table_ptr = hash_heap_storage.get();
6561 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006562 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006563 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006564 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006565 DCHECK(klass->GetVirtualMethodDuringLinking(
6566 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006567 hash_table.Add(i);
6568 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006569 // 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 -07006570 // the hash table.
6571 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006572 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006573 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006574 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6575 super_method->GetAccessFlags())) {
6576 // Continue on to the next method since this one is package private and canot be overridden.
6577 // Before Android 4.1, the package-private method super_method might have been incorrectly
6578 // overridden.
6579 continue;
6580 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006581 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006582 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006583 // We remove the method so that subsequent lookups will be faster by making the hash-map
6584 // smaller as we go on.
Vladimir Marko43354742021-02-03 15:37:01 +00006585 uint32_t hash = (j < mirror::Object::kVTableLength)
6586 ? object_virtual_method_hashes_[j]
6587 : ComputeModifiedUtf8Hash(super_method_name_comparator.GetName());
6588 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator, hash);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006589 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006590 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6591 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006592 if (super_method->IsFinal()) {
6593 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6594 virtual_method->PrettyMethod().c_str(),
6595 super_method->GetDeclaringClassDescriptor());
6596 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006597 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006598 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6599 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006600 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006601 // We didn't directly override this method but we might through default methods...
6602 // Check for default method update.
6603 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006604 switch (FindDefaultMethodImplementation(self,
6605 super_method,
6606 klass,
6607 /*out*/&default_method)) {
6608 case DefaultMethodSearchResult::kDefaultConflict: {
6609 // A conflict was found looking for default methods. Note this (assuming it wasn't
6610 // pre-existing) in the translations map.
6611 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6612 // Don't generate another conflict method to reduce memory use as an optimization.
6613 default_translations->insert(
6614 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6615 }
6616 break;
6617 }
6618 case DefaultMethodSearchResult::kAbstractFound: {
6619 // No conflict but method is abstract.
6620 // We note that this vtable entry must be made abstract.
6621 if (UNLIKELY(!super_method->IsAbstract())) {
6622 default_translations->insert(
6623 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6624 }
6625 break;
6626 }
6627 case DefaultMethodSearchResult::kDefaultFound: {
6628 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6629 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6630 // Found a default method implementation that is new.
6631 // TODO Refactor this add default methods to virtuals here and not in
6632 // LinkInterfaceMethods maybe.
6633 // The problem is default methods might override previously present
6634 // default-method or miranda-method vtable entries from the superclass.
6635 // Unfortunately we need these to be entries in this class's virtuals. We do not
6636 // give these entries there until LinkInterfaceMethods so we pass this map around
6637 // to let it know which vtable entries need to be updated.
6638 // Make a note that vtable entry j must be updated, store what it needs to be updated
6639 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6640 // then.
6641 default_translations->insert(
6642 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006643 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6644 << " overridden by default "
6645 << default_method->PrettyMethod()
6646 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006647 }
6648 break;
6649 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006650 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006651 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006652 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006653 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006654 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006655 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006656 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006657 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6658 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006659 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006660 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006661 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006662 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006663 local_method->SetMethodIndex(actual_count);
6664 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006665 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006666 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006667 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006668 return false;
6669 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006670 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006671 CHECK_LE(actual_count, max_count);
6672 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006673 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6674 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006675 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006676 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006677 return false;
6678 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006679 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006680 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006681 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006682 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006683 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006684 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6685 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006686 return false;
6687 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006688 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006689 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006690 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006691 return false;
6692 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006693 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006694 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6695 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006696 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006697 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006698 klass->SetVTable(vtable);
Vladimir Marko43354742021-02-03 15:37:01 +00006699 InitializeObjectVirtualMethodHashes(klass.Get(),
6700 image_pointer_size_,
6701 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006702 }
6703 return true;
6704}
6705
Alex Light9139e002015-10-09 15:59:48 -07006706// Determine if the given iface has any subinterface in the given list that declares the method
6707// specified by 'target'.
6708//
6709// Arguments
6710// - self: The thread we are running on
6711// - target: A comparator that will match any method that overrides the method we are checking for
6712// - iftable: The iftable we are searching for an overriding method on.
6713// - ifstart: The index of the interface we are checking to see if anything overrides
6714// - iface: The interface we are checking to see if anything overrides.
6715// - image_pointer_size:
6716// The image pointer size.
6717//
6718// Returns
6719// - True: There is some method that matches the target comparator defined in an interface that
6720// is a subtype of iface.
6721// - False: There is no method that matches the target comparator in any interface that is a subtype
6722// of iface.
6723static bool ContainsOverridingMethodOf(Thread* self,
6724 MethodNameAndSignatureComparator& target,
6725 Handle<mirror::IfTable> iftable,
6726 size_t ifstart,
6727 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006728 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006729 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006730 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006731 DCHECK(iface != nullptr);
6732 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006733 DCHECK_GE(ifstart, 0u);
6734 DCHECK_LT(ifstart, iftable->Count());
6735 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6736 DCHECK(iface->IsInterface());
6737
6738 size_t iftable_count = iftable->Count();
6739 StackHandleScope<1> hs(self);
6740 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6741 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6742 // Skip ifstart since our current interface obviously cannot override itself.
6743 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006744 // Iterate through every method on this interface. The order does not matter.
6745 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006746 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006747 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006748 // Check if the i'th interface is a subtype of this one.
6749 if (iface->IsAssignableFrom(current_iface.Get())) {
6750 return true;
6751 }
6752 break;
6753 }
6754 }
6755 }
6756 return false;
6757}
6758
Alex Lighteb7c1442015-08-31 13:17:42 -07006759// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006760// out_default_method and returns kDefaultFound on success. If no default method was found return
6761// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6762// default_method conflict) it will return kDefaultConflict.
6763ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6764 Thread* self,
6765 ArtMethod* target_method,
6766 Handle<mirror::Class> klass,
6767 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006768 DCHECK(self != nullptr);
6769 DCHECK(target_method != nullptr);
6770 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006771
6772 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006773
6774 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6775 // table. This lets us walk the table backwards when searching for default methods. The first one
6776 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6777 // track of it and then continue checking all other interfaces, since we need to throw an error if
6778 // we encounter conflicting default method implementations (one is not a subtype of the other).
6779 //
6780 // The order of unrelated interfaces does not matter and is not defined.
6781 size_t iftable_count = klass->GetIfTableCount();
6782 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006783 // No interfaces. We have already reset out to null so just return kAbstractFound.
6784 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006785 }
6786
Alex Light9139e002015-10-09 15:59:48 -07006787 StackHandleScope<3> hs(self);
6788 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006789 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006790 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006791 MethodNameAndSignatureComparator target_name_comparator(
6792 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6793 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006794 for (size_t k = iftable_count; k != 0; ) {
6795 --k;
6796
Alex Lighteb7c1442015-08-31 13:17:42 -07006797 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006798
6799 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006800 // Iterate through every declared method on this interface. The order does not matter.
6801 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6802 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006803 // Skip abstract methods and methods with different names.
6804 if (current_method->IsAbstract() ||
6805 !target_name_comparator.HasSameNameAndSignature(
6806 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6807 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006808 } else if (!current_method->IsPublic()) {
6809 // The verifier should have caught the non-public method for dex version 37. Just warn and
6810 // skip it since this is from before default-methods so we don't really need to care that it
6811 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006812 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6813 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006814 << "This will be a fatal error in subsequent versions of android. "
6815 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006816 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006817 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006818 // We have multiple default impls of the same method. This is a potential default conflict.
6819 // We need to check if this possibly conflicting method is either a superclass of the chosen
6820 // default implementation or is overridden by a non-default interface method. In either case
6821 // there is no conflict.
6822 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6823 !ContainsOverridingMethodOf(self,
6824 target_name_comparator,
6825 iftable,
6826 k,
6827 iface,
6828 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006829 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006830 << current_method->PrettyMethod() << " and "
6831 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6832 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006833 *out_default_method = nullptr;
6834 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006835 } else {
6836 break; // Continue checking at the next interface.
6837 }
6838 } else {
Alex Light9139e002015-10-09 15:59:48 -07006839 // chosen_iface == null
6840 if (!ContainsOverridingMethodOf(self,
6841 target_name_comparator,
6842 iftable,
6843 k,
6844 iface,
6845 image_pointer_size_)) {
6846 // Don't set this as the chosen interface if something else is overriding it (because that
6847 // other interface would be potentially chosen instead if it was default). If the other
6848 // interface was abstract then we wouldn't select this interface as chosen anyway since
6849 // the abstract method masks it.
6850 *out_default_method = current_method;
6851 chosen_iface.Assign(iface.Get());
6852 // We should now finish traversing the graph to find if we have default methods that
6853 // conflict.
6854 } else {
David Sehr709b0702016-10-13 09:12:37 -07006855 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6856 << "' was "
6857 << "skipped because it was overridden by an abstract method in a "
6858 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006859 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006860 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006861 break;
6862 }
6863 }
Alex Light9139e002015-10-09 15:59:48 -07006864 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006865 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6866 << "' selected "
6867 << "as the implementation for '" << target_method->PrettyMethod()
6868 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006869 return DefaultMethodSearchResult::kDefaultFound;
6870 } else {
6871 return DefaultMethodSearchResult::kAbstractFound;
6872 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006873}
6874
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006875ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006876 ArtMethod* conflict_method,
6877 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006878 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006879 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006880 Runtime* const runtime = Runtime::Current();
6881 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006882
6883 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006884 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006885 ? runtime->CreateImtConflictMethod(linear_alloc)
6886 : conflict_method;
6887
6888 // Allocate a new table. Note that we will leak this table at the next conflict,
6889 // but that's a tradeoff compared to making the table fixed size.
6890 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006891 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6892 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006893 if (data == nullptr) {
6894 LOG(ERROR) << "Failed to allocate conflict table";
6895 return conflict_method;
6896 }
6897 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6898 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006899 method,
6900 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006901
6902 // Do a fence to ensure threads see the data in the table before it is assigned
6903 // to the conflict method.
6904 // Note that there is a race in the presence of multiple threads and we may leak
6905 // memory from the LinearAlloc, but that's a tradeoff compared to using
6906 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006907 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006908 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006909 return new_conflict_method;
6910}
6911
Vladimir Marko921094a2017-01-12 18:37:06 +00006912bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6913 Handle<mirror::Class> klass,
6914 Handle<mirror::IfTable> iftable) {
6915 DCHECK(!klass->IsInterface());
6916 const bool has_superclass = klass->HasSuperClass();
6917 const bool extend_super_iftable = has_superclass;
6918 const size_t ifcount = klass->GetIfTableCount();
6919 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6920 for (size_t i = 0; i < ifcount; ++i) {
6921 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6922 if (num_methods > 0) {
6923 const bool is_super = i < super_ifcount;
6924 // This is an interface implemented by a super-class. Therefore we can just copy the method
6925 // array from the superclass.
6926 const bool super_interface = is_super && extend_super_iftable;
6927 ObjPtr<mirror::PointerArray> method_array;
6928 if (super_interface) {
6929 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6930 DCHECK(if_table != nullptr);
6931 DCHECK(if_table->GetMethodArray(i) != nullptr);
6932 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006933 StackHandleScope<1u> hs(self);
6934 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6935 method_array =
6936 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006937 } else {
6938 method_array = AllocPointerArray(self, num_methods);
6939 }
6940 if (UNLIKELY(method_array == nullptr)) {
6941 self->AssertPendingOOMException();
6942 return false;
6943 }
6944 iftable->SetMethodArray(i, method_array);
6945 }
6946 }
6947 return true;
6948}
6949
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006950void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6951 ArtMethod* imt_conflict_method,
6952 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006953 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006954 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006955 // Place method in imt if entry is empty, place conflict otherwise.
6956 if (*imt_ref == unimplemented_method) {
6957 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006958 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006959 // If we are not a conflict and we have the same signature and name as the imt
6960 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006961 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6962 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006963 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006964 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006965 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006966 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006967 *imt_ref = current_method;
6968 } else {
Alex Light9139e002015-10-09 15:59:48 -07006969 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006970 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006971 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006972 } else {
6973 // Place the default conflict method. Note that there may be an existing conflict
6974 // method in the IMT, but it could be one tailored to the super class, with a
6975 // specific ImtConflictTable.
6976 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006977 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006978 }
6979}
6980
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006981void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006982 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6983 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006984 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006985 Runtime* const runtime = Runtime::Current();
6986 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6987 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006988 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006989 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006990 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006991 FillIMTFromIfTable(klass->GetIfTable(),
6992 unimplemented_method,
6993 conflict_method,
6994 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006995 /*create_conflict_tables=*/true,
6996 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006997 &new_conflict,
6998 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006999 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007000 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
7001 // we can just use the same pointer.
7002 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007003 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007004 if (super_class != nullptr && super_class->ShouldHaveImt()) {
7005 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7006 bool same = true;
7007 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
7008 ArtMethod* method = imt_data[i];
7009 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
7010 if (method != super_method) {
7011 bool is_conflict_table = method->IsRuntimeMethod() &&
7012 method != unimplemented_method &&
7013 method != conflict_method;
7014 // Verify conflict contents.
7015 bool super_conflict_table = super_method->IsRuntimeMethod() &&
7016 super_method != unimplemented_method &&
7017 super_method != conflict_method;
7018 if (!is_conflict_table || !super_conflict_table) {
7019 same = false;
7020 } else {
7021 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
7022 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
7023 same = same && table1->Equals(table2, image_pointer_size_);
7024 }
7025 }
7026 }
7027 if (same) {
7028 imt = super_imt;
7029 }
7030 }
7031 if (imt == nullptr) {
7032 imt = klass->GetImt(image_pointer_size_);
7033 DCHECK(imt != nullptr);
7034 imt->Populate(imt_data, image_pointer_size_);
7035 } else {
7036 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007037 }
7038}
7039
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007040ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
7041 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07007042 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007043 void* data = linear_alloc->Alloc(Thread::Current(),
7044 ImtConflictTable::ComputeSize(count,
7045 image_pointer_size));
7046 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
7047}
7048
7049ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
7050 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
7051}
7052
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007053void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007054 ArtMethod* unimplemented_method,
7055 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007056 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007057 bool create_conflict_tables,
7058 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007059 /*out*/bool* new_conflict,
7060 /*out*/ArtMethod** imt) {
7061 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007062 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007063 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007064 const size_t num_virtuals = interface->NumVirtualMethods();
7065 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7066 // Virtual methods can be larger than the if table methods if there are default methods.
7067 DCHECK_GE(num_virtuals, method_array_count);
7068 if (kIsDebugBuild) {
7069 if (klass->IsInterface()) {
7070 DCHECK_EQ(method_array_count, 0u);
7071 } else {
7072 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
7073 }
7074 }
7075 if (method_array_count == 0) {
7076 continue;
7077 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007078 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007079 for (size_t j = 0; j < method_array_count; ++j) {
7080 ArtMethod* implementation_method =
7081 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7082 if (ignore_copied_methods && implementation_method->IsCopied()) {
7083 continue;
7084 }
7085 DCHECK(implementation_method != nullptr);
7086 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7087 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7088 // or interface methods in the IMT here they will not create extra conflicts since we compare
7089 // names and signatures in SetIMTRef.
7090 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007091 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007092
7093 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7094 // the same implementation method, keep track of this to avoid creating a conflict table in
7095 // this case.
7096
7097 // Conflict table size for each IMT slot.
7098 ++conflict_counts[imt_index];
7099
7100 SetIMTRef(unimplemented_method,
7101 imt_conflict_method,
7102 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007103 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007104 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007105 }
7106 }
7107
7108 if (create_conflict_tables) {
7109 // Create the conflict tables.
7110 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007111 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007112 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007113 if (imt[i] == imt_conflict_method) {
7114 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7115 if (new_table != nullptr) {
7116 ArtMethod* new_conflict_method =
7117 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7118 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7119 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007120 } else {
7121 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007122 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007123 }
7124 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007125 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007126 }
7127 }
7128
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007129 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007130 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007131 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7132 // Virtual methods can be larger than the if table methods if there are default methods.
7133 if (method_array_count == 0) {
7134 continue;
7135 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007136 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007137 for (size_t j = 0; j < method_array_count; ++j) {
7138 ArtMethod* implementation_method =
7139 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7140 if (ignore_copied_methods && implementation_method->IsCopied()) {
7141 continue;
7142 }
7143 DCHECK(implementation_method != nullptr);
7144 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007145 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007146 if (!imt[imt_index]->IsRuntimeMethod() ||
7147 imt[imt_index] == unimplemented_method ||
7148 imt[imt_index] == imt_conflict_method) {
7149 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007150 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007151 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7152 const size_t num_entries = table->NumEntries(image_pointer_size_);
7153 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7154 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007155 }
7156 }
7157 }
7158}
7159
Alex Lighteb7c1442015-08-31 13:17:42 -07007160// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7161// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007162static bool NotSubinterfaceOfAny(
Vladimir Marko782fb712020-12-23 12:47:31 +00007163 const HashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007164 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007165 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007166 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007167 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007168 for (ObjPtr<mirror::Class> c : classes) {
7169 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007170 return false;
7171 }
7172 }
7173 return true;
7174}
7175
7176// Fills in and flattens the interface inheritance hierarchy.
7177//
7178// By the end of this function all interfaces in the transitive closure of to_process are added to
7179// the iftable and every interface precedes all of its sub-interfaces in this list.
7180//
7181// all I, J: Interface | I <: J implies J precedes I
7182//
7183// (note A <: B means that A is a subtype of B)
7184//
7185// This returns the total number of items in the iftable. The iftable might be resized down after
7186// this call.
7187//
7188// We order this backwards so that we do not need to reorder superclass interfaces when new
7189// interfaces are added in subclass's interface tables.
7190//
7191// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7192// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7193// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7194// iftable must be large enough to hold all interfaces without changing its size.
Vladimir Markob10668c2021-06-10 09:52:53 +01007195static size_t FillIfTable(ObjPtr<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00007196 ObjPtr<mirror::ObjectArray<mirror::Class>> interfaces,
7197 ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007198 size_t super_ifcount,
Vladimir Marko782fb712020-12-23 12:47:31 +00007199 size_t num_interfaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007200 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00007201 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
7202 // This is the set of all classes already in the iftable. Used to make checking
7203 // if a class has already been added quicker.
7204 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
7205 mirror::Class* buffer[kBufferSize];
7206 HashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07007207 // The first super_ifcount elements are from the superclass. We note that they are already added.
7208 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007209 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007210 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007211 classes_in_iftable.insert(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007212 }
7213 size_t filled_ifcount = super_ifcount;
Vladimir Marko782fb712020-12-23 12:47:31 +00007214 const bool have_interfaces = interfaces != nullptr;
7215 for (size_t i = 0; i != num_interfaces; ++i) {
Vladimir Markob10668c2021-06-10 09:52:53 +01007216 ObjPtr<mirror::Class> interface =
7217 have_interfaces ? interfaces->Get(i) : klass->GetDirectInterface(i);
Vladimir Marko782fb712020-12-23 12:47:31 +00007218
Alex Lighteb7c1442015-08-31 13:17:42 -07007219 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7220 // At this point in the loop current-iface-list has the invariant that:
7221 // for every pair of interfaces I,J within it:
7222 // if index_of(I) < index_of(J) then I is not a subtype of J
7223
7224 // If we have already seen this element then all of its super-interfaces must already be in the
7225 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00007226 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007227 // We haven't seen this interface so add all of its super-interfaces onto the
7228 // current-iface-list, skipping those already on it.
7229 int32_t ifcount = interface->GetIfTableCount();
7230 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007231 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007232 if (!ContainsElement(classes_in_iftable, super_interface)) {
7233 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007234 classes_in_iftable.insert(super_interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007235 iftable->SetInterface(filled_ifcount, super_interface);
7236 filled_ifcount++;
7237 }
7238 }
7239 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7240 // Place this interface onto the current-iface-list after all of its super-interfaces.
Vladimir Marko782fb712020-12-23 12:47:31 +00007241 classes_in_iftable.insert(interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007242 iftable->SetInterface(filled_ifcount, interface);
7243 filled_ifcount++;
7244 } else if (kIsDebugBuild) {
7245 // Check all super-interfaces are already in the list.
7246 int32_t ifcount = interface->GetIfTableCount();
7247 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007248 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007249 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007250 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7251 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007252 }
7253 }
7254 }
7255 if (kIsDebugBuild) {
7256 // Check that the iftable is ordered correctly.
7257 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007258 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007259 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007260 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007261 // !(if_a <: if_b)
7262 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007263 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7264 << ") extends "
7265 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007266 << "interface list.";
7267 }
7268 }
7269 }
7270 return filled_ifcount;
7271}
7272
Vladimir Marko782fb712020-12-23 12:47:31 +00007273bool ClassLinker::SetupInterfaceLookupTable(Thread* self,
7274 Handle<mirror::Class> klass,
Alex Lighteb7c1442015-08-31 13:17:42 -07007275 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7276 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007277 const bool has_superclass = klass->HasSuperClass();
7278 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007279 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007280 const size_t num_interfaces =
7281 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007282 if (num_interfaces == 0) {
7283 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007284 if (LIKELY(has_superclass)) {
7285 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7286 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007287 // Class implements no interfaces.
7288 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007289 return true;
7290 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007291 // Class implements same interfaces as parent, are any of these not marker interfaces?
7292 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007293 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007294 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007295 if (super_iftable->GetMethodArrayCount(i) > 0) {
7296 has_non_marker_interface = true;
7297 break;
7298 }
7299 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007300 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007301 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007302 klass->SetIfTable(super_iftable);
7303 return true;
7304 }
7305 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007306 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007307 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007308 for (size_t i = 0; i < num_interfaces; i++) {
Vladimir Markob10668c2021-06-10 09:52:53 +01007309 ObjPtr<mirror::Class> interface =
7310 have_interfaces ? interfaces->GetWithoutChecks(i) : klass->GetDirectInterface(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007311 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007312 if (UNLIKELY(!interface->IsInterface())) {
7313 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007314 ThrowIncompatibleClassChangeError(klass.Get(),
7315 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007316 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007317 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7318 return false;
7319 }
7320 ifcount += interface->GetIfTableCount();
7321 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007322 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007323 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007324 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007325 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007326 return false;
7327 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007328 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007329 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007330 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007331 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007332 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007333 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007334 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007335 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007336
7337 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7338 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7339 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007340 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007341
Vladimir Markob10668c2021-06-10 09:52:53 +01007342 const size_t new_ifcount =
7343 FillIfTable(klass.Get(), interfaces.Get(), iftable.Get(), super_ifcount, num_interfaces);
Alex Lighteb7c1442015-08-31 13:17:42 -07007344
Ian Rogers7b078e82014-09-10 14:44:24 -07007345 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007346
Ian Rogersb52b01a2012-01-12 17:01:38 -08007347 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007348 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007349 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007350 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007351 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007352 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007353 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007354 return false;
7355 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007356 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007357 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007358 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007359 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007360 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007361 return true;
7362}
7363
Alex Light1f3925d2016-09-07 12:04:20 -07007364// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7365// of methods must be unique.
7366static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7367 return nullptr;
7368}
7369
7370template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007371static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007372 const ScopedArenaVector<ArtMethod*>& list,
7373 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007374 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007375 for (ArtMethod* method : list) {
7376 if (cmp.HasSameNameAndSignature(method)) {
7377 return method;
7378 }
7379 }
Alex Light1f3925d2016-09-07 12:04:20 -07007380 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007381}
7382
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007383namespace {
7384
Alex Light1f3925d2016-09-07 12:04:20 -07007385// Check that all vtable entries are present in this class's virtuals or are the same as a
7386// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007387void CheckClassOwnsVTableEntries(Thread* self,
7388 Handle<mirror::Class> klass,
7389 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007390 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007391 StackHandleScope<2> hs(self);
7392 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007393 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007394 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007395 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007396 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7397 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7398 CHECK(m != nullptr);
7399
Alex Lighta41a30782017-03-29 11:33:19 -07007400 if (m->GetMethodIndexDuringLinking() != i) {
7401 LOG(WARNING) << m->PrettyMethod()
7402 << " has an unexpected method index for its spot in the vtable for class"
7403 << klass->PrettyClass();
7404 }
Alex Lighte64300b2015-12-15 15:02:47 -08007405 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7406 auto is_same_method = [m] (const ArtMethod& meth) {
7407 return &meth == m;
7408 };
Alex Light3f980532017-03-17 15:10:32 -07007409 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7410 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7411 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7412 << klass->PrettyClass() << " or any of its superclasses!";
7413 }
Alex Lighte64300b2015-12-15 15:02:47 -08007414 }
7415}
7416
Alex Light1f3925d2016-09-07 12:04:20 -07007417// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7418// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007419template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007420void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007421 REQUIRES_SHARED(Locks::mutator_lock_) {
7422 StackHandleScope<1> hs(self);
7423 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7424 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007425
7426 // Observations:
7427 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7428 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7429 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7430 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7431 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7432 // * The single-pass algorithm will trade memory for speed, but that is OK.
7433
7434 CHECK_GT(num_entries, 0);
7435
7436 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7437 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7438 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7439 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7440 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7441 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7442 << m2->PrettyMethod() << " (0x" << std::hex
7443 << reinterpret_cast<uintptr_t>(m2) << ")";
7444 };
7445 struct BaseHashType {
7446 static size_t HashCombine(size_t seed, size_t val) {
7447 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7448 }
7449 };
7450
7451 // Check assuming all entries come from the same dex file.
7452 {
7453 // Find the first interesting method and its dex file.
7454 int32_t start = 0;
7455 for (; start < num_entries; ++start) {
7456 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7457 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7458 // maybe).
7459 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7460 vtable_entry->GetAccessFlags())) {
7461 continue;
7462 }
7463 break;
7464 }
7465 if (start == num_entries) {
7466 return;
7467 }
7468 const DexFile* dex_file =
7469 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7470 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7471
7472 // Helper function to avoid logging if we have to run the cross-file checks.
7473 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7474 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7475 using PairType = std::pair<uint32_t, uint16_t>;
7476 struct PairHash : BaseHashType {
7477 size_t operator()(const PairType& key) const {
7478 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7479 }
7480 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007481 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007482 seen.reserve(2 * num_entries);
7483 bool need_slow_path = false;
7484 bool found_dup = false;
7485 for (int i = start; i < num_entries; ++i) {
7486 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7487 // wrt/ kPointerSize.
7488 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7489 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7490 vtable_entry->GetAccessFlags())) {
7491 continue;
7492 }
7493 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7494 if (dex_file != m->GetDexFile()) {
7495 need_slow_path = true;
7496 break;
7497 }
7498 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7499 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7500 auto it = seen.find(pair);
7501 if (it != seen.end()) {
7502 found_dup = true;
7503 if (log_warn) {
7504 log_fn(it->second, i);
7505 }
7506 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007507 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007508 }
7509 }
7510 return std::make_pair(need_slow_path, found_dup);
7511 };
7512 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7513 if (!result.first) {
7514 if (result.second) {
7515 check_fn(/* log_warn= */ true);
7516 }
7517 return;
7518 }
7519 }
7520
7521 // Need to check across dex files.
7522 struct Entry {
7523 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00007524 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007525 const char* name = nullptr;
7526 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007527
Vladimir Marko782fb712020-12-23 12:47:31 +00007528 Entry() = default;
7529 Entry(const Entry& other) = default;
7530 Entry& operator=(const Entry& other) = default;
7531
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007532 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00007533 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
7534 // This call writes `name_len` and it is therefore necessary that the
7535 // initializer for `name_len` comes before it, otherwise the value
7536 // from the call would be overwritten by that initializer.
7537 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007538 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00007539 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
7540 if (name[name_len] != 0) {
7541 name_len += strlen(name + name_len);
7542 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007543 }
7544
7545 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00007546 return name_len == other.name_len &&
7547 memcmp(name, other.name, name_len) == 0 &&
7548 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007549 }
7550 };
7551 struct EntryHash {
7552 size_t operator()(const Entry& key) const {
7553 return key.cached_hash;
7554 }
7555 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007556 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007557 for (int32_t i = 0; i < num_entries; ++i) {
7558 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7559 // wrt/ kPointerSize.
7560 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7561 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7562 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007563 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7564 vtable_entry->GetAccessFlags())) {
7565 continue;
7566 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007567 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7568 const DexFile* dex_file = m->GetDexFile();
7569 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7570
7571 Entry e(dex_file, mid);
7572
7573 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7574 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7575 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7576 sig_hash);
7577
7578 auto it = map.find(e);
7579 if (it != map.end()) {
7580 log_fn(it->second, i);
7581 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007582 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07007583 }
7584 }
7585}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007586
7587void CheckVTableHasNoDuplicates(Thread* self,
7588 Handle<mirror::Class> klass,
7589 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007590 REQUIRES_SHARED(Locks::mutator_lock_) {
7591 switch (pointer_size) {
7592 case PointerSize::k64:
7593 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7594 break;
7595 case PointerSize::k32:
7596 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7597 break;
7598 }
7599}
Alex Light1f3925d2016-09-07 12:04:20 -07007600
Orion Hodson5880c772020-07-28 20:12:08 +01007601static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07007602 REQUIRES_SHARED(Locks::mutator_lock_) {
7603 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7604 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7605}
7606
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007607} // namespace
7608
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007609void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7610 ArtMethod* unimplemented_method,
7611 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007612 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007613 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007614 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007615 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007616 if (super_class->ShouldHaveImt()) {
7617 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7618 for (size_t i = 0; i < ImTable::kSize; ++i) {
7619 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007620 }
7621 } else {
7622 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007623 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007624 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007625 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007626 FillIMTFromIfTable(if_table,
7627 unimplemented_method,
7628 imt_conflict_method,
7629 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007630 /*create_conflict_tables=*/false,
7631 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007632 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007633 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007634 }
7635 }
7636}
7637
Vladimir Marko921094a2017-01-12 18:37:06 +00007638class ClassLinker::LinkInterfaceMethodsHelper {
7639 public:
7640 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7641 Handle<mirror::Class> klass,
7642 Thread* self,
7643 Runtime* runtime)
7644 : class_linker_(class_linker),
7645 klass_(klass),
7646 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7647 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7648 self_(self),
7649 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7650 allocator_(&stack_),
7651 default_conflict_methods_(allocator_.Adapter()),
7652 overriding_default_conflict_methods_(allocator_.Adapter()),
7653 miranda_methods_(allocator_.Adapter()),
7654 default_methods_(allocator_.Adapter()),
7655 overriding_default_methods_(allocator_.Adapter()),
7656 move_table_(allocator_.Adapter()) {
7657 }
7658
7659 ArtMethod* FindMethod(ArtMethod* interface_method,
7660 MethodNameAndSignatureComparator& interface_name_comparator,
7661 ArtMethod* vtable_impl)
7662 REQUIRES_SHARED(Locks::mutator_lock_);
7663
7664 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7665 MethodNameAndSignatureComparator& interface_name_comparator)
7666 REQUIRES_SHARED(Locks::mutator_lock_);
7667
7668 bool HasNewVirtuals() const {
7669 return !(miranda_methods_.empty() &&
7670 default_methods_.empty() &&
7671 overriding_default_methods_.empty() &&
7672 overriding_default_conflict_methods_.empty() &&
7673 default_conflict_methods_.empty());
7674 }
7675
7676 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7677
7678 ObjPtr<mirror::PointerArray> UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007679 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007680 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007681
7682 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7683
7684 void UpdateIMT(ArtMethod** out_imt);
7685
7686 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7687 if (kIsDebugBuild) {
7688 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7689 // Check that there are no stale methods are in the dex cache array.
7690 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7691 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
David Srbecky5de5efe2021-02-15 21:23:00 +00007692 auto pair = mirror::DexCache::GetNativePair(resolved_methods, i);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007693 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007694 CHECK(move_table_.find(m) == move_table_.end() ||
7695 // The original versions of copied methods will still be present so allow those too.
7696 // Note that if the first check passes this might fail to GetDeclaringClass().
7697 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7698 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7699 [m] (ArtMethod& meth) {
7700 return &meth == m;
7701 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7702 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7703 }
7704 }
7705 }
7706
7707 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7708 LengthPrefixedArray<ArtMethod>* methods) {
7709 if (kIsDebugBuild) {
7710 CHECK(methods != nullptr);
7711 // Put some random garbage in old methods to help find stale pointers.
7712 if (methods != old_methods && old_methods != nullptr) {
7713 // Need to make sure the GC is not running since it could be scanning the methods we are
7714 // about to overwrite.
7715 ScopedThreadStateChange tsc(self_, kSuspended);
7716 gc::ScopedGCCriticalSection gcs(self_,
7717 gc::kGcCauseClassLinker,
7718 gc::kCollectorTypeClassLinker);
7719 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7720 method_size_,
7721 method_alignment_);
7722 memset(old_methods, 0xFEu, old_size);
7723 }
7724 }
7725 }
7726
7727 private:
7728 size_t NumberOfNewVirtuals() const {
7729 return miranda_methods_.size() +
7730 default_methods_.size() +
7731 overriding_default_conflict_methods_.size() +
7732 overriding_default_methods_.size() +
7733 default_conflict_methods_.size();
7734 }
7735
7736 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7737 return !klass_->IsInterface();
7738 }
7739
7740 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7741 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7742 << "Interfaces should only have default-conflict methods appended to them.";
7743 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7744 << miranda_methods_.size()
7745 << " default_methods=" << default_methods_.size()
7746 << " overriding_default_methods=" << overriding_default_methods_.size()
7747 << " default_conflict_methods=" << default_conflict_methods_.size()
7748 << " overriding_default_conflict_methods="
7749 << overriding_default_conflict_methods_.size();
7750 }
7751
7752 ClassLinker* class_linker_;
7753 Handle<mirror::Class> klass_;
7754 size_t method_alignment_;
7755 size_t method_size_;
7756 Thread* const self_;
7757
7758 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7759 // the virtual methods array.
7760 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7761 // during cross compilation.
7762 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7763 ArenaStack stack_;
7764 ScopedArenaAllocator allocator_;
7765
7766 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7767 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7768 ScopedArenaVector<ArtMethod*> miranda_methods_;
7769 ScopedArenaVector<ArtMethod*> default_methods_;
7770 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7771
7772 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7773};
7774
7775ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7776 ArtMethod* interface_method,
7777 MethodNameAndSignatureComparator& interface_name_comparator,
7778 ArtMethod* vtable_impl) {
7779 ArtMethod* current_method = nullptr;
7780 switch (class_linker_->FindDefaultMethodImplementation(self_,
7781 interface_method,
7782 klass_,
7783 /*out*/&current_method)) {
7784 case DefaultMethodSearchResult::kDefaultConflict: {
7785 // Default method conflict.
7786 DCHECK(current_method == nullptr);
7787 ArtMethod* default_conflict_method = nullptr;
7788 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7789 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7790 default_conflict_method = vtable_impl;
7791 } else {
7792 // See if we already have a conflict method for this method.
7793 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7794 interface_name_comparator,
7795 default_conflict_methods_,
7796 overriding_default_conflict_methods_);
7797 if (LIKELY(preexisting_conflict != nullptr)) {
7798 // We already have another conflict we can reuse.
7799 default_conflict_method = preexisting_conflict;
7800 } else {
7801 // Note that we do this even if we are an interface since we need to create this and
7802 // cannot reuse another classes.
7803 // Create a new conflict method for this to use.
7804 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7805 new(default_conflict_method) ArtMethod(interface_method,
7806 class_linker_->GetImagePointerSize());
7807 if (vtable_impl == nullptr) {
7808 // Save the conflict method. We need to add it to the vtable.
7809 default_conflict_methods_.push_back(default_conflict_method);
7810 } else {
7811 // Save the conflict method but it is already in the vtable.
7812 overriding_default_conflict_methods_.push_back(default_conflict_method);
7813 }
7814 }
7815 }
7816 current_method = default_conflict_method;
7817 break;
7818 } // case kDefaultConflict
7819 case DefaultMethodSearchResult::kDefaultFound: {
7820 DCHECK(current_method != nullptr);
7821 // Found a default method.
7822 if (vtable_impl != nullptr &&
7823 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7824 // We found a default method but it was the same one we already have from our
7825 // superclass. Don't bother adding it to our vtable again.
7826 current_method = vtable_impl;
7827 } else if (LIKELY(FillTables())) {
7828 // Interfaces don't need to copy default methods since they don't have vtables.
7829 // Only record this default method if it is new to save space.
7830 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7831 // would make lookup for interface super much faster. (We would only need to scan
7832 // the iftable to find if there is a NSME or AME.)
7833 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7834 default_methods_,
7835 overriding_default_methods_);
7836 if (old == nullptr) {
7837 // We found a default method implementation and there were no conflicts.
7838 if (vtable_impl == nullptr) {
7839 // Save the default method. We need to add it to the vtable.
7840 default_methods_.push_back(current_method);
7841 } else {
7842 // Save the default method but it is already in the vtable.
7843 overriding_default_methods_.push_back(current_method);
7844 }
7845 } else {
7846 CHECK(old == current_method) << "Multiple default implementations selected!";
7847 }
7848 }
7849 break;
7850 } // case kDefaultFound
7851 case DefaultMethodSearchResult::kAbstractFound: {
7852 DCHECK(current_method == nullptr);
7853 // Abstract method masks all defaults.
7854 if (vtable_impl != nullptr &&
7855 vtable_impl->IsAbstract() &&
7856 !vtable_impl->IsDefaultConflicting()) {
7857 // We need to make this an abstract method but the version in the vtable already is so
7858 // don't do anything.
7859 current_method = vtable_impl;
7860 }
7861 break;
7862 } // case kAbstractFound
7863 }
7864 return current_method;
7865}
7866
7867ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7868 ArtMethod* interface_method,
7869 MethodNameAndSignatureComparator& interface_name_comparator) {
7870 // Find out if there is already a miranda method we can use.
7871 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7872 miranda_methods_);
7873 if (miranda_method == nullptr) {
7874 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7875 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7876 CHECK(miranda_method != nullptr);
7877 // Point the interface table at a phantom slot.
7878 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7879 miranda_methods_.push_back(miranda_method);
7880 }
7881 return miranda_method;
7882}
7883
7884void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7885 LogNewVirtuals();
7886
7887 const size_t old_method_count = klass_->NumMethods();
7888 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7889 DCHECK_NE(old_method_count, new_method_count);
7890
7891 // Attempt to realloc to save RAM if possible.
7892 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7893 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7894 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7895 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7896 // CopyFrom has internal read barriers.
7897 //
7898 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7899 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7900 method_size_,
7901 method_alignment_);
7902 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7903 method_size_,
7904 method_alignment_);
7905 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7906 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007907 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007908 self_, old_methods, old_methods_ptr_size, new_size));
7909 CHECK(methods != nullptr); // Native allocation failure aborts.
7910
7911 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7912 if (methods != old_methods) {
7913 // Maps from heap allocated miranda method to linear alloc miranda method.
7914 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7915 // Copy over the old methods.
7916 for (auto& m : klass_->GetMethods(pointer_size)) {
7917 move_table_.emplace(&m, &*out);
7918 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7919 // barriers when it copies.
7920 out->CopyFrom(&m, pointer_size);
7921 ++out;
7922 }
7923 }
7924 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7925 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7926 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007927 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7928 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007929 ArtMethod& new_method = *out;
7930 new_method.CopyFrom(mir_method, pointer_size);
Vladimir Markode0d0de2021-03-18 14:12:35 +00007931 uint32_t access_flags = new_method.GetAccessFlags();
7932 DCHECK_EQ(access_flags & kAccIntrinsic, 0u) << "Miranda method should not be an intrinsic!";
7933 DCHECK_EQ(access_flags & kAccDefault, 0u) << "Miranda method should not be a default method!";
7934 DCHECK_NE(access_flags & kAccAbstract, 0u) << "Miranda method should be abstract!";
7935 new_method.SetAccessFlags(access_flags | kAccCopied);
Vladimir Marko921094a2017-01-12 18:37:06 +00007936 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007937 // Update the entry in the method array, as the array will be used for future lookups,
7938 // where thread suspension is allowed.
7939 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7940 // would not see them.
7941 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007942 ++out;
7943 }
7944 // We need to copy the default methods into our own method table since the runtime requires that
7945 // every method on a class's vtable be in that respective class's virtual method table.
7946 // NOTE This means that two classes might have the same implementation of a method from the same
7947 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7948 // default method found on a class with one found on the declaring interface directly and must
7949 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007950 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7951 &overriding_default_methods_}) {
7952 for (size_t i = 0; i < methods_vec->size(); ++i) {
7953 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007954 ArtMethod& new_method = *out;
7955 new_method.CopyFrom(def_method, pointer_size);
7956 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7957 // verified yet it shouldn't have methods that are skipping access checks.
7958 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7959 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007960 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007961 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7962 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7963 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7964 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007965 // Update the entry in the method array, as the array will be used for future lookups,
7966 // where thread suspension is allowed.
7967 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7968 // would not see them.
7969 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007970 ++out;
7971 }
7972 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007973 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7974 &overriding_default_conflict_methods_}) {
7975 for (size_t i = 0; i < methods_vec->size(); ++i) {
7976 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007977 ArtMethod& new_method = *out;
7978 new_method.CopyFrom(conf_method, pointer_size);
7979 // This is a type of default method (there are default method impls, just a conflict) so
Vladimir Markode0d0de2021-03-18 14:12:35 +00007980 // mark this as a default. We use the `kAccAbstract` flag to distinguish it from invokable
7981 // copied default method without using a separate access flag but the default conflicting
7982 // method is technically not abstract and ArtMethod::IsAbstract() shall return false.
7983 // Also clear the kAccSkipAccessChecks bit since this class hasn't been verified yet it
7984 // shouldn't have methods that are skipping access checks. Also clear potential
7985 // kAccSingleImplementation to avoid CHA trying to inline the default method.
7986 uint32_t access_flags = new_method.GetAccessFlags();
7987 DCHECK_EQ(access_flags & kAccNative, 0u);
7988 DCHECK_EQ(access_flags & kAccIntrinsic, 0u);
7989 constexpr uint32_t kSetFlags = kAccDefault | kAccAbstract | kAccCopied;
7990 constexpr uint32_t kMaskFlags = ~(kAccSkipAccessChecks | kAccSingleImplementation);
7991 new_method.SetAccessFlags((access_flags | kSetFlags) & kMaskFlags);
Vladimir Marko921094a2017-01-12 18:37:06 +00007992 DCHECK(new_method.IsDefaultConflicting());
Vladimir Markode0d0de2021-03-18 14:12:35 +00007993 DCHECK(!new_method.IsAbstract());
Vladimir Marko921094a2017-01-12 18:37:06 +00007994 // The actual method might or might not be marked abstract since we just copied it from a
7995 // (possibly default) interface method. We need to set it entry point to be the bridge so
7996 // that the compiler will not invoke the implementation of whatever method we copied from.
7997 EnsureThrowsInvocationError(class_linker_, &new_method);
7998 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007999 // Update the entry in the method array, as the array will be used for future lookups,
8000 // where thread suspension is allowed.
8001 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
8002 // would not see them.
8003 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00008004 ++out;
8005 }
8006 }
8007 methods->SetSize(new_method_count);
8008 class_linker_->UpdateClassMethods(klass_.Get(), methods);
8009}
8010
8011ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00008012 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01008013 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008014 // Update the vtable to the new method structures. We can skip this for interfaces since they
8015 // do not have vtables.
8016 const size_t old_vtable_count = old_vtable->GetLength();
8017 const size_t new_vtable_count = old_vtable_count +
8018 miranda_methods_.size() +
8019 default_methods_.size() +
8020 default_conflict_methods_.size();
8021
Vladimir Marko3068d582019-05-28 16:39:29 +01008022 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
8023 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00008024 if (UNLIKELY(vtable == nullptr)) {
8025 self_->AssertPendingOOMException();
8026 return nullptr;
8027 }
8028
8029 size_t vtable_pos = old_vtable_count;
8030 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8031 // Update all the newly copied method's indexes so they denote their placement in the vtable.
8032 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
8033 default_conflict_methods_,
8034 miranda_methods_}) {
8035 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008036 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008037 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
8038 // fields are references into the dex file the method was defined in. Since the ArtMethod
8039 // does not store that information it uses declaring_class_->dex_cache_.
8040 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
8041 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
8042 ++vtable_pos;
8043 }
8044 }
8045 DCHECK_EQ(vtable_pos, new_vtable_count);
8046
8047 // Update old vtable methods. We use the default_translations map to figure out what each
8048 // vtable entry should be updated to, if they need to be at all.
8049 for (size_t i = 0; i < old_vtable_count; ++i) {
8050 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
8051 // Try and find what we need to change this method to.
8052 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008053 if (translation_it != default_translations.end()) {
8054 if (translation_it->second.IsInConflict()) {
8055 // Find which conflict method we are to use for this method.
8056 MethodNameAndSignatureComparator old_method_comparator(
8057 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8058 // We only need to look through overriding_default_conflict_methods since this is an
8059 // overridden method we are fixing up here.
8060 ArtMethod* new_conflict_method = FindSameNameAndSignature(
8061 old_method_comparator, overriding_default_conflict_methods_);
8062 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
8063 translated_method = new_conflict_method;
8064 } else if (translation_it->second.IsAbstract()) {
8065 // Find which miranda method we are to use for this method.
8066 MethodNameAndSignatureComparator old_method_comparator(
8067 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8068 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
8069 miranda_methods_);
8070 DCHECK(miranda_method != nullptr);
8071 translated_method = miranda_method;
8072 } else {
8073 // Normal default method (changed from an older default or abstract interface method).
8074 DCHECK(translation_it->second.IsTranslation());
8075 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008076 auto it = move_table_.find(translated_method);
8077 DCHECK(it != move_table_.end());
8078 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00008079 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008080 } else {
8081 auto it = move_table_.find(translated_method);
8082 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008083 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008084
8085 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008086 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008087 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008088 if (kIsDebugBuild) {
8089 auto* methods = klass_->GetMethodsPtr();
8090 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008091 reinterpret_cast<uintptr_t>(translated_method));
8092 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008093 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8094 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008095 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008096 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008097 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008098 }
8099 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008100 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008101 return vtable;
8102}
8103
8104void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8105 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8106 const size_t ifcount = klass_->GetIfTableCount();
8107 // Go fix up all the stale iftable pointers.
8108 for (size_t i = 0; i < ifcount; ++i) {
8109 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008110 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8111 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008112 DCHECK(m != nullptr) << klass_->PrettyClass();
8113 auto it = move_table_.find(m);
8114 if (it != move_table_.end()) {
8115 auto* new_m = it->second;
8116 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8117 method_array->SetElementPtrSize(j, new_m, pointer_size);
8118 }
8119 }
8120 }
8121}
8122
8123void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8124 // Fix up IMT next.
8125 for (size_t i = 0; i < ImTable::kSize; ++i) {
8126 auto it = move_table_.find(out_imt[i]);
8127 if (it != move_table_.end()) {
8128 out_imt[i] = it->second;
8129 }
8130 }
8131}
8132
Alex Light705ad492015-09-21 11:36:30 -07008133// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008134bool ClassLinker::LinkInterfaceMethods(
8135 Thread* self,
8136 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00008137 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008138 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008139 ArtMethod** out_imt) {
8140 StackHandleScope<3> hs(self);
8141 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008142
8143 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008144 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008145 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008146 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008147 const size_t ifcount = klass->GetIfTableCount();
8148
Vladimir Marko921094a2017-01-12 18:37:06 +00008149 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008150
8151 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8152 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008153 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008154 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008155 const bool extend_super_iftable = has_superclass;
8156 if (has_superclass && fill_tables) {
8157 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008158 unimplemented_method,
8159 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008160 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008161 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008162 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008163 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8164 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008165 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008166 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8167 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008168 }
8169 }
8170
Vladimir Marko921094a2017-01-12 18:37:06 +00008171 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8172
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008173 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008174 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008175 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8176 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8177 // they will already be null. This has the additional benefit that the declarer of a miranda
8178 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008179 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008180 --i;
Alex Light9139e002015-10-09 15:59:48 -07008181 DCHECK_LT(i, ifcount);
8182
Alex Light705ad492015-09-21 11:36:30 -07008183 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008184 if (num_methods > 0) {
8185 StackHandleScope<2> hs2(self);
8186 const bool is_super = i < super_ifcount;
8187 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008188 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8189 // conflict methods. Just set this as nullptr in those cases.
8190 Handle<mirror::PointerArray> method_array(fill_tables
8191 ? hs2.NewHandle(iftable->GetMethodArray(i))
8192 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008193
Alex Lighte64300b2015-12-15 15:02:47 -08008194 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008195 ScopedNullHandle<mirror::PointerArray> null_handle;
8196 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008197 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008198
Alex Light9139e002015-10-09 15:59:48 -07008199 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8200 // and confusing. Default methods should always look through all the superclasses
8201 // because they are the last choice of an implementation. We get around this by looking
8202 // at the super-classes iftable methods (copied into method_array previously) when we are
8203 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008204 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008205 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008206 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008207 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008208 using_virtuals = true;
Alex Lighta467a6e2020-03-23 16:07:29 -07008209 input_virtual_methods = klass->GetDeclaredVirtualMethodsSlice(image_pointer_size_);
Alex Lighte64300b2015-12-15 15:02:47 -08008210 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008211 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008212 // For a new interface, however, we need the whole vtable in case a new
8213 // interface method is implemented in the whole superclass.
8214 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008215 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008216 input_vtable_array = vtable;
8217 input_array_length = input_vtable_array->GetLength();
8218 }
Alex Lighte64300b2015-12-15 15:02:47 -08008219
Alex Lighteb7c1442015-08-31 13:17:42 -07008220 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008221 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008222 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008223 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008224 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008225 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008226 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008227 // For each method listed in the interface's method list, find the
8228 // matching method in our class's method list. We want to favor the
8229 // subclass over the superclass, which just requires walking
8230 // back from the end of the vtable. (This only matters if the
8231 // superclass defines a private method and this class redefines
8232 // it -- otherwise it would use the same vtable slot. In .dex files
8233 // those don't end up in the virtual method table, so it shouldn't
8234 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008235 //
8236 // To find defaults we need to do the same but also go over interfaces.
8237 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008238 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008239 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008240 ArtMethod* vtable_method = using_virtuals ?
8241 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008242 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8243 ArtMethod* vtable_method_for_name_comparison =
8244 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Alex Lighta467a6e2020-03-23 16:07:29 -07008245 DCHECK(!vtable_method->IsStatic()) << vtable_method->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008246 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008247 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008248 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008249 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8250 // allocations.
8251 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008252 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008253 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008254 vtable_method->PrettyMethod().c_str(),
8255 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008256 return false;
Alex Light9139e002015-10-09 15:59:48 -07008257 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008258 // We might have a newer, better, default method for this, so we just skip it. If we
8259 // are still using this we will select it again when scanning for default methods. To
8260 // obviate the need to copy the method again we will make a note that we already found
8261 // a default here.
8262 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008263 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008264 break;
8265 } else {
8266 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008267 if (LIKELY(fill_tables)) {
8268 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8269 // Place method in imt if entry is empty, place conflict otherwise.
8270 SetIMTRef(unimplemented_method,
8271 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008272 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008273 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008274 /*out*/imt_ptr);
8275 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008276 break;
8277 }
8278 }
Alex Light9139e002015-10-09 15:59:48 -07008279 }
8280 // Continue on to the next method if we are done.
8281 if (LIKELY(found_impl)) {
8282 continue;
8283 } else if (LIKELY(super_interface)) {
8284 // Don't look for a default implementation when the super-method is implemented directly
8285 // by the class.
8286 //
8287 // See if we can use the superclasses method and skip searching everything else.
8288 // Note: !found_impl && super_interface
8289 CHECK(extend_super_iftable);
8290 // If this is a super_interface method it is possible we shouldn't override it because a
8291 // superclass could have implemented it directly. We get the method the superclass used
8292 // to implement this to know if we can override it with a default method. Doing this is
8293 // safe since we know that the super_iftable is filled in so we can simply pull it from
8294 // there. We don't bother if this is not a super-classes interface since in that case we
8295 // have scanned the entire vtable anyway and would have found it.
8296 // TODO This is rather dirty but it is faster than searching through the entire vtable
8297 // every time.
8298 ArtMethod* supers_method =
8299 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8300 DCHECK(supers_method != nullptr);
8301 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008302 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008303 // The method is not overridable by a default method (i.e. it is directly implemented
8304 // in some class). Therefore move onto the next interface method.
8305 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008306 } else {
8307 // If the super-classes method is override-able by a default method we need to keep
8308 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8309 // 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 -07008310 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8311 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8312 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008313 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008314 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8315 << " and not 'nullptr' or "
8316 << supers_method->PrettyMethod()
8317 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008318 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008319 }
8320 }
8321 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008322 ArtMethod* current_method = helper.FindMethod(interface_method,
8323 interface_name_comparator,
8324 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008325 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008326 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008327 // We could not find an implementation for this method and since it is a brand new
8328 // interface we searched the entire vtable (and all default methods) for an
8329 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008330 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8331 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008332 }
8333
8334 if (current_method != nullptr) {
8335 // We found a default method implementation. Record it in the iftable and IMT.
8336 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8337 SetIMTRef(unimplemented_method,
8338 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008339 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008340 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008341 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008342 }
8343 }
Alex Light705ad492015-09-21 11:36:30 -07008344 } // For each method in interface end.
8345 } // if (num_methods > 0)
8346 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008347 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008348 if (helper.HasNewVirtuals()) {
8349 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8350 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8351 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8352
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008353 // 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 -07008354 // suspension assert.
8355 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008356
Alex Light705ad492015-09-21 11:36:30 -07008357 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008358 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008359 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008360 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008361 return false;
8362 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008363 helper.UpdateIfTable(iftable);
8364 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008365 }
Alex Light705ad492015-09-21 11:36:30 -07008366
Vladimir Marko921094a2017-01-12 18:37:06 +00008367 helper.CheckNoStaleMethodsInDexCache();
8368 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008369 } else {
8370 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008371 }
Alex Light705ad492015-09-21 11:36:30 -07008372 if (kIsDebugBuild && !is_interface) {
Orion Hodson5880c772020-07-28 20:12:08 +01008373 CheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008374 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008375 return true;
8376}
8377
Vladimir Marko42bee502021-01-28 14:58:35 +00008378class ClassLinker::LinkFieldsHelper {
8379 public:
8380 static bool LinkFields(ClassLinker* class_linker,
8381 Thread* self,
8382 Handle<mirror::Class> klass,
8383 bool is_static,
8384 size_t* class_size)
8385 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008386
Vladimir Marko42bee502021-01-28 14:58:35 +00008387 private:
8388 enum class FieldTypeOrder : uint16_t;
8389 class FieldGaps;
8390
8391 struct FieldTypeOrderAndIndex {
8392 FieldTypeOrder field_type_order;
8393 uint16_t field_index;
8394 };
8395
8396 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8397
8398 template <size_t kSize>
8399 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8400 REQUIRES_SHARED(Locks::mutator_lock_);
8401};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008402
Vladimir Markoc7993d52021-01-27 15:20:56 +00008403// We use the following order of field types for assigning offsets.
8404// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008405enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008406 kReference = 0u,
8407 kLong,
8408 kDouble,
8409 kInt,
8410 kFloat,
8411 kChar,
8412 kShort,
8413 kBoolean,
8414 kByte,
8415
8416 kLast64BitType = kDouble,
8417 kLast32BitType = kFloat,
8418 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008419};
8420
Vladimir Markoc7993d52021-01-27 15:20:56 +00008421ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008422ClassLinker::LinkFieldsHelper::FieldTypeOrder
8423ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008424 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008425 case 'J':
8426 return FieldTypeOrder::kLong;
8427 case 'D':
8428 return FieldTypeOrder::kDouble;
8429 case 'I':
8430 return FieldTypeOrder::kInt;
8431 case 'F':
8432 return FieldTypeOrder::kFloat;
8433 case 'C':
8434 return FieldTypeOrder::kChar;
8435 case 'S':
8436 return FieldTypeOrder::kShort;
8437 case 'Z':
8438 return FieldTypeOrder::kBoolean;
8439 case 'B':
8440 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008441 default:
8442 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8443 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008444 }
8445}
8446
8447// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008448class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008449 public:
8450 template <uint32_t kSize>
8451 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8452 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8453 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8454 uint32_t gap_start = field_offset.Uint32Value();
8455 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8456 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8457 }
8458 return field_offset;
8459 }
8460
8461 template <uint32_t kSize>
8462 bool HasGap() const {
8463 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8464 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8465 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8466 gap4_offset_ != kNoOffset;
8467 }
8468
8469 template <uint32_t kSize>
8470 MemberOffset ReleaseGap() {
8471 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8472 uint32_t result;
8473 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8474 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8475 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8476 result = gap1_offset_;
8477 gap1_offset_ = kNoOffset;
8478 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8479 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8480 result = gap2_offset_;
8481 gap2_offset_ = kNoOffset;
8482 if (kSize < 2u) {
8483 AddGaps<1u>(result + kSize, result + 2u);
8484 }
8485 } else {
8486 DCHECK_NE(gap4_offset_, kNoOffset);
8487 result = gap4_offset_;
8488 gap4_offset_ = kNoOffset;
8489 if (kSize < 4u) {
8490 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8491 }
8492 }
8493 return MemberOffset(result);
8494 }
8495
8496 private:
8497 template <uint32_t kGapsToCheck>
8498 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8499 if ((kGapsToCheck & 1u) != 0u) {
8500 DCHECK_LT(gap_start, gap_end);
8501 DCHECK_ALIGNED(gap_end, 2u);
8502 if ((gap_start & 1u) != 0u) {
8503 DCHECK_EQ(gap1_offset_, kNoOffset);
8504 gap1_offset_ = gap_start;
8505 gap_start += 1u;
8506 if (kGapsToCheck == 1u || gap_start == gap_end) {
8507 DCHECK_EQ(gap_start, gap_end);
8508 return;
8509 }
8510 }
8511 }
8512
8513 if ((kGapsToCheck & 2u) != 0u) {
8514 DCHECK_LT(gap_start, gap_end);
8515 DCHECK_ALIGNED(gap_start, 2u);
8516 DCHECK_ALIGNED(gap_end, 4u);
8517 if ((gap_start & 2u) != 0u) {
8518 DCHECK_EQ(gap2_offset_, kNoOffset);
8519 gap2_offset_ = gap_start;
8520 gap_start += 2u;
8521 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8522 DCHECK_EQ(gap_start, gap_end);
8523 return;
8524 }
8525 }
8526 }
8527
8528 if ((kGapsToCheck & 4u) != 0u) {
8529 DCHECK_LT(gap_start, gap_end);
8530 DCHECK_ALIGNED(gap_start, 4u);
8531 DCHECK_ALIGNED(gap_end, 8u);
8532 DCHECK_EQ(gap_start + 4u, gap_end);
8533 DCHECK_EQ(gap4_offset_, kNoOffset);
8534 gap4_offset_ = gap_start;
8535 return;
8536 }
8537
8538 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8539 << " after checking " << kGapsToCheck;
8540 }
8541
8542 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8543
8544 uint32_t gap4_offset_ = kNoOffset;
8545 uint32_t gap2_offset_ = kNoOffset;
8546 uint32_t gap1_offset_ = kNoOffset;
8547};
8548
8549template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008550ALWAYS_INLINE
8551MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8552 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008553 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8554 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8555 field->SetOffset(field_offset);
8556 return MemberOffset(field_offset.Uint32Value() + kSize);
8557}
8558
Vladimir Marko42bee502021-01-28 14:58:35 +00008559bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8560 Thread* self,
8561 Handle<mirror::Class> klass,
8562 bool is_static,
8563 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008564 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008565 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008566 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8567 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008568
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008569 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008570 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008571 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008572 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8573 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008574 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008575 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008576 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008577 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008578 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008579 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008580 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008581 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008582
David Sehr709b0702016-10-13 09:12:37 -07008583 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008584
Brian Carlstromdbc05252011-09-09 01:59:59 -07008585 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008586 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008587 //
8588 // The overall sort order order is:
8589 // 1) All object reference fields, sorted alphabetically.
8590 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8591 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8592 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8593 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8594 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8595 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8596 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8597 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8598 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008599 // (References are first to increase the chance of reference visiting
8600 // being able to take a fast path using a bitmap of references at the
8601 // start of the object, see `Class::reference_instance_offsets_`.)
8602 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008603 // Once the fields are sorted in this order we will attempt to fill any gaps
8604 // that might be present in the memory layout of the structure.
8605 // Note that we shall not fill gaps between the superclass fields.
8606
8607 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008608 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008609 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008610 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8611 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8612 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8613 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008614 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008615 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008616 } else {
8617 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008618 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008619 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008620 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008621 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008622 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008623 for (size_t i = 0; i != num_fields; ++i) {
8624 ArtField* field = &fields->At(i);
8625 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008626 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8627 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008628 // Insert references to the start, other fields to the end.
8629 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008630 if (field_type_order == FieldTypeOrder::kReference) {
8631 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008632 ++num_reference_fields;
8633 } else {
8634 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008635 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008636 }
8637 }
8638 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008639
Vladimir Marko42bee502021-01-28 14:58:35 +00008640 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008641 DCHECK(std::is_sorted(
8642 sorted_fields.begin(),
8643 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008644 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8645 ArtField* lhs_field = &fields->At(lhs.field_index);
8646 ArtField* rhs_field = &fields->At(rhs.field_index);
8647 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8648 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8649 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8650 lhs.field_index < rhs.field_index);
8651 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008652 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008653 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008654 DCHECK(std::is_sorted(
8655 sorted_fields.begin() + primitive_fields_start,
8656 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008657 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8658 ArtField* lhs_field = &fields->At(lhs.field_index);
8659 ArtField* rhs_field = &fields->At(rhs.field_index);
8660 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8661 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8662 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8663 lhs.field_index > rhs.field_index);
8664 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008665 }));
8666 // Sort the primitive fields by the field type order, then field index.
8667 std::sort(sorted_fields.begin() + primitive_fields_start,
8668 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008669 [](const auto& lhs, const auto& rhs) {
8670 if (lhs.field_type_order != rhs.field_type_order) {
8671 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008672 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008673 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008674 }
8675 });
8676 // Primitive fields are now sorted by field size (descending), then type, then field index.
8677 DCHECK(std::is_sorted(
8678 sorted_fields.begin() + primitive_fields_start,
8679 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008680 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8681 ArtField* lhs_field = &fields->At(lhs.field_index);
8682 ArtField* rhs_field = &fields->At(rhs.field_index);
8683 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008684 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008685 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008686 CHECK_NE(rhs_type, Primitive::kPrimNot);
8687 if (lhs_type != rhs_type) {
8688 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8689 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8690 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8691 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008692 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008693 }
8694 }));
8695
8696 // Process reference fields.
8697 FieldGaps field_gaps;
8698 size_t index = 0u;
8699 if (num_reference_fields != 0u) {
8700 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8701 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8702 for (; index != num_reference_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008703 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008704 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008705 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008706 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008707 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008708 if (index != num_fields &&
8709 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008710 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008711 while (index != num_fields &&
8712 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8713 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008714 field_offset = AssignFieldOffset<8u>(field, field_offset);
8715 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008716 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008717 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008718 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008719 if (index != num_fields &&
8720 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008721 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8722 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008723 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008724 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8725 ++index;
8726 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8727 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008728 while (index != num_fields &&
8729 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8730 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008731 field_offset = AssignFieldOffset<4u>(field, field_offset);
8732 ++index;
8733 }
8734 }
8735 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008736 if (index != num_fields &&
8737 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008738 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8739 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008740 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008741 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008742 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008743 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8744 ++index;
8745 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008746 while (index != num_fields &&
8747 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8748 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008749 field_offset = AssignFieldOffset<2u>(field, field_offset);
8750 ++index;
8751 }
8752 }
8753 // Process 8-bit fields.
8754 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008755 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008756 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8757 }
8758 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008759 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008760 field_offset = AssignFieldOffset<1u>(field, field_offset);
8761 }
8762
Ian Rogers7b078e82014-09-10 14:44:24 -07008763 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008764
Elliott Hughesadb460d2011-10-05 17:02:34 -07008765 // 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 +00008766 DCHECK(!class_linker->init_done_ || !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
8767 if (!is_static &&
8768 UNLIKELY(!class_linker->init_done_) &&
8769 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008770 // We know there are no non-reference fields in the Reference classes, and we know
8771 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008772 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008773 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008774 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008775 --num_reference_fields;
8776 }
8777
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008778 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008779 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008780 if (is_static) {
8781 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008782 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008783 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008784 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008785 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008786 if (num_reference_fields == 0 || super_class == nullptr) {
8787 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008788 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008789 if (super_class == nullptr ||
8790 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8791 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008792 }
8793 }
8794 if (kIsDebugBuild) {
8795 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8796 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008797 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008798 while (cur_super != nullptr) {
8799 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8800 cur_super = cur_super->GetSuperClass();
8801 }
8802 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008803 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008804 } else {
8805 // Check that there is at least num_reference_fields other than Object.class.
8806 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008807 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008808 }
8809 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008810 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008811 std::string temp;
8812 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8813 size_t previous_size = klass->GetObjectSize();
8814 if (previous_size != 0) {
8815 // Make sure that we didn't originally have an incorrect size.
8816 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008817 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008818 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008819 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008820 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008821
8822 if (kIsDebugBuild) {
8823 // Make sure that the fields array is ordered by name but all reference
8824 // offsets are at the beginning as far as alignment allows.
8825 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00008826 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008827 : klass->GetFirstReferenceInstanceFieldOffset();
8828 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8829 num_reference_fields *
8830 sizeof(mirror::HeapReference<mirror::Object>));
8831 MemberOffset current_ref_offset = start_ref_offset;
8832 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008833 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008834 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008835 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8836 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008837 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008838 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008839 // NOTE: The field names can be the same. This is not possible in the Java language
8840 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008841 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008842 }
8843 Primitive::Type type = field->GetTypeAsPrimitiveType();
8844 bool is_primitive = type != Primitive::kPrimNot;
8845 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8846 strcmp("referent", field->GetName()) == 0) {
8847 is_primitive = true; // We lied above, so we have to expect a lie here.
8848 }
8849 MemberOffset offset = field->GetOffsetDuringLinking();
8850 if (is_primitive) {
8851 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8852 // Shuffled before references.
8853 size_t type_size = Primitive::ComponentSize(type);
8854 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8855 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8856 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8857 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8858 }
8859 } else {
8860 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8861 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8862 sizeof(mirror::HeapReference<mirror::Object>));
8863 }
8864 }
8865 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8866 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008867 return true;
8868}
8869
Vladimir Marko42bee502021-01-28 14:58:35 +00008870bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
8871 CHECK(klass != nullptr);
8872 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
8873}
8874
8875bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
8876 CHECK(klass != nullptr);
8877 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
8878}
8879
Vladimir Marko76649e82014-11-10 18:32:59 +00008880// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008881void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008882 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008883 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008884 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008885 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008886 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008887 // Compute reference offsets unless our superclass overflowed.
8888 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8889 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008890 if (num_reference_fields != 0u) {
8891 // All of the fields that contain object references are guaranteed be grouped in memory
8892 // starting at an appropriately aligned address after super class object data.
8893 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8894 sizeof(mirror::HeapReference<mirror::Object>));
8895 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008896 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008897 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008898 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008899 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008900 reference_offsets |= (0xffffffffu << start_bit) &
8901 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008902 }
8903 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008904 }
8905 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008906 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008907}
8908
Vladimir Marko18090d12018-06-01 16:53:12 +01008909ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8910 ObjPtr<mirror::DexCache> dex_cache) {
8911 StackHandleScope<1> hs(Thread::Current());
8912 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8913 return DoResolveString(string_idx, h_dex_cache);
8914}
8915
8916ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8917 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008918 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008919 uint32_t utf16_length;
8920 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008921 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008922 if (string != nullptr) {
8923 dex_cache->SetResolvedString(string_idx, string);
8924 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008925 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008926}
8927
Vladimir Marko18090d12018-06-01 16:53:12 +01008928ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8929 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008930 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008931 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008932 uint32_t utf16_length;
8933 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008934 ObjPtr<mirror::String> string =
8935 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008936 if (string != nullptr) {
8937 dex_cache->SetResolvedString(string_idx, string);
8938 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008939 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008940}
8941
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008942ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008943 ObjPtr<mirror::Class> referrer) {
8944 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8945}
8946
8947ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008948 ObjPtr<mirror::DexCache> dex_cache,
8949 ObjPtr<mirror::ClassLoader> class_loader) {
8950 const DexFile& dex_file = *dex_cache->GetDexFile();
8951 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Vladimir Markoc63d9672021-03-31 15:50:39 +01008952 ObjPtr<mirror::Class> type = LookupResolvedType(descriptor, class_loader);
8953 if (type != nullptr) {
8954 DCHECK(type->IsResolved());
8955 dex_cache->SetResolvedType(type_idx, type);
8956 }
8957 return type;
8958}
8959
8960ObjPtr<mirror::Class> ClassLinker::LookupResolvedType(const char* descriptor,
8961 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008962 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8963 ObjPtr<mirror::Class> type = nullptr;
8964 if (descriptor[1] == '\0') {
8965 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8966 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008967 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008968 } else {
8969 Thread* const self = Thread::Current();
8970 DCHECK(self != nullptr);
8971 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8972 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008973 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008974 }
Vladimir Markoc63d9672021-03-31 15:50:39 +01008975 return (type != nullptr && type->IsResolved()) ? type : nullptr;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008976}
8977
Andreas Gampeb0625e02019-05-01 12:43:31 -07008978template <typename RefType>
8979ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008980 StackHandleScope<2> hs(Thread::Current());
8981 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8982 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8983 return DoResolveType(type_idx, dex_cache, class_loader);
8984}
8985
Andreas Gampe4835d212018-11-21 14:55:10 -08008986// Instantiate the above.
8987template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8988 ArtField* referrer);
8989template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8990 ArtMethod* referrer);
8991template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8992 ObjPtr<mirror::Class> referrer);
8993
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008994ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008995 Handle<mirror::DexCache> dex_cache,
8996 Handle<mirror::ClassLoader> class_loader) {
8997 Thread* self = Thread::Current();
8998 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8999 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
9000 if (resolved != nullptr) {
9001 // TODO: we used to throw here if resolved's class loader was not the
9002 // boot class loader. This was to permit different classes with the
9003 // same name to be loaded simultaneously by different loaders
9004 dex_cache->SetResolvedType(type_idx, resolved);
9005 } else {
9006 CHECK(self->IsExceptionPending())
9007 << "Expected pending exception for failed resolution of: " << descriptor;
9008 // Convert a ClassNotFoundException to a NoClassDefFoundError.
9009 StackHandleScope<1> hs(self);
9010 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009011 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009012 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
9013 self->ClearException();
9014 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
9015 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009016 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009017 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00009018 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07009019 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00009020 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009021}
9022
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009023ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
9024 ObjPtr<mirror::DexCache> dex_cache,
9025 ObjPtr<mirror::ClassLoader> class_loader,
9026 uint32_t method_idx) {
9027 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
9028 // functions can optimize the search if the dex_cache is the same as the DexCache
9029 // of the class, with fall-back to name and signature search otherwise.
9030 ArtMethod* resolved = nullptr;
9031 if (klass->IsInterface()) {
9032 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9033 } else {
9034 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9035 }
9036 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009037 if (resolved != nullptr &&
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009038 // We pass AccessMethod::kNone instead of kLinking to not warn yet on the
9039 // access, as we'll be looking if the method can be accessed through an
9040 // interface.
David Brazdilf50ac102018-10-17 18:00:06 +01009041 hiddenapi::ShouldDenyAccessToMember(resolved,
9042 hiddenapi::AccessContext(class_loader, dex_cache),
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009043 hiddenapi::AccessMethod::kNone)) {
9044 // The resolved method that we have found cannot be accessed due to
9045 // hiddenapi (typically it is declared up the hierarchy and is not an SDK
9046 // method). Try to find an interface method from the implemented interfaces which is
Nicolas Geoffrayaf61f502021-03-31 16:03:50 +00009047 // part of the SDK.
9048 ArtMethod* itf_method = klass->FindAccessibleInterfaceMethod(resolved, image_pointer_size_);
Nicolas Geoffrayfedff512021-02-07 21:36:33 +00009049 if (itf_method == nullptr) {
9050 // No interface method. Call ShouldDenyAccessToMember again but this time
9051 // with AccessMethod::kLinking to ensure that an appropriate warning is
9052 // logged.
9053 hiddenapi::ShouldDenyAccessToMember(resolved,
9054 hiddenapi::AccessContext(class_loader, dex_cache),
9055 hiddenapi::AccessMethod::kLinking);
9056 resolved = nullptr;
9057 } else {
9058 // We found an interface method that is accessible, continue with the resolved method.
9059 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009060 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009061 if (resolved != nullptr) {
9062 // In case of jmvti, the dex file gets verified before being registered, so first
9063 // check if it's registered before checking class tables.
9064 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009065 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
9066 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009067 << "DexFile referrer: " << dex_file.GetLocation()
9068 << " ClassLoader: " << DescribeLoaders(class_loader, "");
9069 // Be a good citizen and update the dex cache to speed subsequent calls.
David Srbecky5de5efe2021-02-15 21:23:00 +00009070 dex_cache->SetResolvedMethod(method_idx, resolved);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009071 // Disable the following invariant check as the verifier breaks it. b/73760543
9072 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
9073 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
9074 // << "Method: " << resolved->PrettyMethod() << ", "
9075 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
9076 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009077 }
9078 return resolved;
9079}
9080
David Brazdil4525e0b2018-04-05 16:57:32 +01009081// Returns true if `method` is either null or hidden.
9082// Does not print any warnings if it is hidden.
9083static bool CheckNoSuchMethod(ArtMethod* method,
9084 ObjPtr<mirror::DexCache> dex_cache,
9085 ObjPtr<mirror::ClassLoader> class_loader)
9086 REQUIRES_SHARED(Locks::mutator_lock_) {
9087 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01009088 hiddenapi::ShouldDenyAccessToMember(method,
9089 hiddenapi::AccessContext(class_loader, dex_cache),
9090 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01009091}
9092
9093ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
9094 ObjPtr<mirror::DexCache> dex_cache,
9095 ObjPtr<mirror::ClassLoader> class_loader,
9096 uint32_t method_idx) {
9097 if (klass->IsInterface()) {
9098 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9099 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
9100 } else {
9101 // If there was an interface method with the same signature, we would have
9102 // found it in the "copied" methods. Only DCHECK that the interface method
9103 // really does not exist.
9104 if (kIsDebugBuild) {
9105 ArtMethod* method =
9106 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9107 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
9108 }
9109 return nullptr;
9110 }
9111}
9112
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009113template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00009114ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07009115 Handle<mirror::DexCache> dex_cache,
9116 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009117 ArtMethod* referrer,
9118 InvokeType type) {
Nicolas Geoffray605c5912020-04-08 15:12:39 +01009119 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Andreas Gampefa4333d2017-02-14 11:10:34 -08009120 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01009121 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07009122 // Check for hit in the dex cache.
David Srbecky5de5efe2021-02-15 21:23:00 +00009123 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009124 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009125 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
9126 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01009127 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
9128 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07009129 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009130 return resolved;
9131 }
Vladimir Marko89011192017-12-11 13:45:05 +00009132 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009133 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009134 ObjPtr<mirror::Class> klass = nullptr;
9135 if (valid_dex_cache_method) {
9136 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
9137 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009138 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009139 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009140 // We normaly should not end up here. However the verifier currently doesn't guarantee
9141 // the invariant of having the klass in the class table. b/73760543
9142 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Nicolas Geoffray07614192020-04-28 17:31:31 +01009143 if (klass == nullptr) {
9144 // This can only happen if the current thread is not allowed to load
9145 // classes.
9146 DCHECK(!Thread::Current()->CanLoadClasses());
9147 DCHECK(Thread::Current()->IsExceptionPending());
9148 return nullptr;
9149 }
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009150 }
Vladimir Markoba118822017-06-12 15:41:56 +01009151 } else {
9152 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009153 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01009154 if (klass == nullptr) {
9155 DCHECK(Thread::Current()->IsExceptionPending());
9156 return nullptr;
9157 }
9158 }
9159
9160 // Check if the invoke type matches the class type.
9161 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009162 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01009163 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07009164 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009165 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009166 }
Vladimir Markoba118822017-06-12 15:41:56 +01009167
9168 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009169 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009170 }
Vladimir Markoba118822017-06-12 15:41:56 +01009171
9172 // Note: We can check for IllegalAccessError only if we have a referrer.
9173 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
9174 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
9175 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9176 if (!referring_class->CheckResolvedMethodAccess(methods_class,
9177 resolved,
9178 dex_cache.Get(),
9179 method_idx,
9180 type)) {
9181 DCHECK(Thread::Current()->IsExceptionPending());
9182 return nullptr;
9183 }
9184 }
9185
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009186 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01009187 if (LIKELY(resolved != nullptr) &&
9188 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
9189 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07009190 return resolved;
9191 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009192 // If we had a method, or if we can find one with another lookup type,
9193 // it's an incompatible-class-change error.
9194 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01009195 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009196 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009197 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07009198 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009199 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009200 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009201 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
9202 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01009203 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07009204 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08009205 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009206 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07009207 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009208}
9209
Vladimir Marko89011192017-12-11 13:45:05 +00009210ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009211 Handle<mirror::DexCache> dex_cache,
9212 Handle<mirror::ClassLoader> class_loader) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009213 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009214 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009215 if (resolved != nullptr) {
9216 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009217 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9218 return resolved;
9219 }
9220 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009221 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009222 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009223 if (klass == nullptr) {
9224 Thread::Current()->AssertPendingException();
9225 return nullptr;
9226 }
9227 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009228 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9229 } else {
9230 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009231 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009232 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009233 hiddenapi::ShouldDenyAccessToMember(
9234 resolved,
9235 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9236 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009237 resolved = nullptr;
9238 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009239 return resolved;
9240}
9241
Vladimir Markof44d36c2017-03-14 14:18:46 +00009242ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9243 ObjPtr<mirror::DexCache> dex_cache,
9244 ObjPtr<mirror::ClassLoader> class_loader,
9245 bool is_static) {
9246 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009247 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009248 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9249 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009250 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009251 }
9252 if (klass == nullptr) {
9253 // The class has not been resolved yet, so the field is also unresolved.
9254 return nullptr;
9255 }
9256 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009257
David Brazdil1ab0fa82018-05-04 11:28:03 +01009258 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009259}
9260
Vladimir Markoe11dd502017-12-08 14:09:45 +00009261ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009262 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009263 Handle<mirror::ClassLoader> class_loader,
9264 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009265 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayf3688822020-03-25 15:04:03 +00009266 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
David Srbecky5de5efe2021-02-15 21:23:00 +00009267 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009268 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009269 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009270 return resolved;
9271 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009272 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009273 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009274 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009275 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08009276 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07009277 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009278 }
9279
David Brazdil1ab0fa82018-05-04 11:28:03 +01009280 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07009281 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08009282 const char* name = dex_file.GetFieldName(field_id);
9283 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009284 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009285 }
Ian Rogersb067ac22011-12-13 18:05:09 -08009286 return resolved;
9287}
9288
Vladimir Markoe11dd502017-12-08 14:09:45 +00009289ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009290 Handle<mirror::DexCache> dex_cache,
9291 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009292 DCHECK(dex_cache != nullptr);
David Srbecky5de5efe2021-02-15 21:23:00 +00009293 ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009294 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009295 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009296 return resolved;
9297 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009298 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009299 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009300 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009301 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009302 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009303 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009304 }
9305
David Brazdil1ab0fa82018-05-04 11:28:03 +01009306 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9307 if (resolved == nullptr) {
9308 const char* name = dex_file.GetFieldName(field_id);
9309 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009310 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009311 }
9312 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009313}
9314
David Brazdil1ab0fa82018-05-04 11:28:03 +01009315ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9316 ObjPtr<mirror::DexCache> dex_cache,
9317 ObjPtr<mirror::ClassLoader> class_loader,
9318 uint32_t field_idx,
9319 bool is_static) {
Vladimir Markob10668c2021-06-10 09:52:53 +01009320 ArtField* resolved = is_static ? klass->FindStaticField(dex_cache, field_idx)
9321 : klass->FindInstanceField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009322 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009323 hiddenapi::ShouldDenyAccessToMember(resolved,
9324 hiddenapi::AccessContext(class_loader, dex_cache),
9325 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009326 resolved = nullptr;
9327 }
9328
9329 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009330 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009331 }
9332
9333 return resolved;
9334}
9335
9336ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9337 ObjPtr<mirror::DexCache> dex_cache,
9338 ObjPtr<mirror::ClassLoader> class_loader,
9339 uint32_t field_idx) {
Vladimir Markob10668c2021-06-10 09:52:53 +01009340 ArtField* resolved = klass->FindField(dex_cache, field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009341
9342 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009343 hiddenapi::ShouldDenyAccessToMember(resolved,
9344 hiddenapi::AccessContext(class_loader, dex_cache),
9345 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009346 resolved = nullptr;
9347 }
9348
9349 if (resolved != nullptr) {
David Srbecky5de5efe2021-02-15 21:23:00 +00009350 dex_cache->SetResolvedField(field_idx, resolved);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009351 }
9352
9353 return resolved;
9354}
9355
Vladimir Markoaf940202017-12-08 15:01:18 +00009356ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9357 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009358 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009359 Handle<mirror::DexCache> dex_cache,
9360 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009361 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009362 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009363
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009364 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009365 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009366 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009367 }
9368
Narayan Kamath25352fc2016-08-03 12:46:58 +01009369 StackHandleScope<4> hs(self);
9370
9371 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009372 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009373 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009374 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009375 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009376 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009377 DCHECK(self->IsExceptionPending());
9378 return nullptr;
9379 }
9380
9381 // Then resolve the argument types.
9382 //
9383 // TODO: Is there a better way to figure out the number of method arguments
9384 // other than by looking at the shorty ?
9385 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9386
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009387 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009388 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9389 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009390 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009391 DCHECK(self->IsExceptionPending());
9392 return nullptr;
9393 }
9394
9395 DexFileParameterIterator it(dex_file, proto_id);
9396 int32_t i = 0;
9397 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9398 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009399 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009400 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009401 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009402 DCHECK(self->IsExceptionPending());
9403 return nullptr;
9404 }
9405
9406 method_params->Set(i++, param_class.Get());
9407 }
9408
9409 DCHECK(!it.HasNext());
9410
9411 Handle<mirror::MethodType> type = hs.NewHandle(
9412 mirror::MethodType::Create(self, return_type, method_params));
9413 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9414
9415 return type.Get();
9416}
9417
Vladimir Markoaf940202017-12-08 15:01:18 +00009418ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009419 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009420 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009421 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009422 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9423 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009424 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009425}
9426
Vladimir Marko5aead702019-03-27 11:00:36 +00009427ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009428 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009429 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009430 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009431 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009432 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9433 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009434 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009435 bool is_static;
9436 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009437 switch (handle_type) {
9438 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009439 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009440 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009441 is_static = true;
9442 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009443 break;
9444 }
9445 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009446 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009447 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009448 is_static = true;
9449 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009450 break;
9451 }
9452 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009453 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009454 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009455 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009456 num_params = 2;
9457 break;
9458 }
9459 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009460 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009461 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009462 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009463 num_params = 1;
9464 break;
9465 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009466 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009467 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009468 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009469 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009470 case DexFile::MethodHandleType::kInvokeInterface:
9471 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009472 }
9473
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009474 ArtField* target_field =
9475 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9476 if (LIKELY(target_field != nullptr)) {
9477 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9478 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9479 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9480 ThrowIllegalAccessErrorField(referring_class, target_field);
9481 return nullptr;
9482 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009483 if (UNLIKELY(is_put && target_field->IsFinal())) {
9484 ThrowIllegalAccessErrorField(referring_class, target_field);
9485 return nullptr;
9486 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009487 } else {
9488 DCHECK(Thread::Current()->IsExceptionPending());
9489 return nullptr;
9490 }
9491
9492 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009493 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009494 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9495 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009496 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009497 DCHECK(self->IsExceptionPending());
9498 return nullptr;
9499 }
9500
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009501 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009502 Handle<mirror::Class> return_type;
9503 switch (handle_type) {
9504 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009505 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009506 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009507 break;
9508 }
9509 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009510 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009511 break;
9512 }
9513 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009514 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009515 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009516 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009517 break;
9518 }
9519 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009520 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009521 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009522 break;
9523 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009524 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009525 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009526 case DexFile::MethodHandleType::kInvokeConstructor:
9527 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009528 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009529 UNREACHABLE();
9530 }
9531
9532 for (int32_t i = 0; i < num_params; ++i) {
9533 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9534 DCHECK(self->IsExceptionPending());
9535 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009536 }
9537 }
9538
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009539 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009540 DCHECK(self->IsExceptionPending());
9541 return nullptr;
9542 }
9543
9544 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009545 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9546 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009547 DCHECK(self->IsExceptionPending());
9548 return nullptr;
9549 }
Orion Hodson631827d2017-04-10 14:53:47 +01009550
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009551 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9552 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9553}
9554
Vladimir Marko5aead702019-03-27 11:00:36 +00009555ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009556 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009557 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009558 ArtMethod* referrer) {
9559 DexFile::MethodHandleType handle_type =
9560 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9561 mirror::MethodHandle::Kind kind;
9562 uint32_t receiver_count = 0;
9563 ArtMethod* target_method = nullptr;
9564 switch (handle_type) {
9565 case DexFile::MethodHandleType::kStaticPut:
9566 case DexFile::MethodHandleType::kStaticGet:
9567 case DexFile::MethodHandleType::kInstancePut:
9568 case DexFile::MethodHandleType::kInstanceGet:
9569 UNREACHABLE();
9570 case DexFile::MethodHandleType::kInvokeStatic: {
9571 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9572 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009573 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9574 method_handle.field_or_method_idx_,
9575 referrer,
9576 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009577 break;
9578 }
9579 case DexFile::MethodHandleType::kInvokeInstance: {
9580 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9581 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009582 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9583 method_handle.field_or_method_idx_,
9584 referrer,
9585 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009586 break;
9587 }
9588 case DexFile::MethodHandleType::kInvokeConstructor: {
9589 // Constructors are currently implemented as a transform. They
9590 // are special cased later in this method.
9591 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9592 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009593 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9594 method_handle.field_or_method_idx_,
9595 referrer,
9596 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009597 break;
9598 }
9599 case DexFile::MethodHandleType::kInvokeDirect: {
9600 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9601 receiver_count = 1;
9602 StackHandleScope<2> hs(self);
9603 // A constant method handle with type kInvokeDirect can refer to
9604 // a method that is private or to a method in a super class. To
9605 // disambiguate the two options, we resolve the method ignoring
9606 // the invocation type to determine if the method is private. We
9607 // then resolve again specifying the intended invocation type to
9608 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009609 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009610 hs.NewHandle(referrer->GetDexCache()),
9611 hs.NewHandle(referrer->GetClassLoader()));
9612 if (UNLIKELY(target_method == nullptr)) {
9613 break;
9614 }
9615
9616 if (target_method->IsPrivate()) {
9617 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009618 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9619 method_handle.field_or_method_idx_,
9620 referrer,
9621 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009622 } else {
9623 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009624 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9625 method_handle.field_or_method_idx_,
9626 referrer,
9627 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009628 if (UNLIKELY(target_method == nullptr)) {
9629 break;
9630 }
9631 // Find the method specified in the parent in referring class
9632 // so invoke-super invokes the method in the parent of the
9633 // referrer.
9634 target_method =
9635 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9636 kRuntimePointerSize);
9637 }
9638 break;
9639 }
9640 case DexFile::MethodHandleType::kInvokeInterface: {
9641 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9642 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009643 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9644 method_handle.field_or_method_idx_,
9645 referrer,
9646 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009647 break;
9648 }
Orion Hodson631827d2017-04-10 14:53:47 +01009649 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009650
9651 if (UNLIKELY(target_method == nullptr)) {
9652 DCHECK(Thread::Current()->IsExceptionPending());
9653 return nullptr;
9654 }
9655
9656 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9657 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9658 uint32_t access_flags = target_method->GetAccessFlags();
9659 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9660 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9661 return nullptr;
9662 }
9663
9664 // Calculate the number of parameters from the method shorty. We add the
9665 // receiver count (0 or 1) and deduct one for the return value.
9666 uint32_t shorty_length;
9667 target_method->GetShorty(&shorty_length);
9668 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9669
Orion Hodsonecd58562018-09-24 11:27:33 +01009670 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009671 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009672 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9673 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9674 if (method_params.Get() == nullptr) {
9675 DCHECK(self->IsExceptionPending());
9676 return nullptr;
9677 }
9678
Orion Hodsonecd58562018-09-24 11:27:33 +01009679 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009680 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009681 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009682 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009683 // Insert receiver. Use the class identified in the method handle rather than the declaring
9684 // class of the resolved method which may be super class or default interface method
9685 // (b/115964401).
9686 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9687 // receiver_class should have been resolved when resolving the target method.
9688 DCHECK(receiver_class != nullptr);
9689 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009690 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009691
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009692 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009693 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009694 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009695 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009696 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009697 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009698 if (nullptr == klass) {
9699 DCHECK(self->IsExceptionPending());
9700 return nullptr;
9701 }
9702 method_params->Set(index++, klass);
9703 it.Next();
9704 }
9705
Orion Hodsonecd58562018-09-24 11:27:33 +01009706 Handle<mirror::Class> return_type =
9707 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009708 if (UNLIKELY(return_type.IsNull())) {
9709 DCHECK(self->IsExceptionPending());
9710 return nullptr;
9711 }
9712
9713 Handle<mirror::MethodType>
9714 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9715 if (UNLIKELY(method_type.IsNull())) {
9716 DCHECK(self->IsExceptionPending());
9717 return nullptr;
9718 }
9719
9720 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9721 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9722 Handle<mirror::MethodHandlesLookup> lookup =
9723 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9724 return lookup->FindConstructor(self, constructor_class, method_type);
9725 }
9726
9727 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9728 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9729}
9730
Vladimir Markoaf940202017-12-08 15:01:18 +00009731ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9732 uint32_t method_handle_idx,
9733 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009734 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009735 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009736 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009737 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9738 case DexFile::MethodHandleType::kStaticPut:
9739 case DexFile::MethodHandleType::kStaticGet:
9740 case DexFile::MethodHandleType::kInstancePut:
9741 case DexFile::MethodHandleType::kInstanceGet:
9742 return ResolveMethodHandleForField(self, method_handle, referrer);
9743 case DexFile::MethodHandleType::kInvokeStatic:
9744 case DexFile::MethodHandleType::kInvokeInstance:
9745 case DexFile::MethodHandleType::kInvokeConstructor:
9746 case DexFile::MethodHandleType::kInvokeDirect:
9747 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009748 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009749 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009750}
9751
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009752bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9753 return (entry_point == GetQuickResolutionStub()) ||
9754 (quick_resolution_trampoline_ == entry_point);
9755}
9756
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009757bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9758 return (entry_point == GetQuickToInterpreterBridge()) ||
9759 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9760}
9761
9762bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9763 return (entry_point == GetQuickGenericJniStub()) ||
9764 (quick_generic_jni_trampoline_ == entry_point);
9765}
9766
David Sehra49e0532017-08-25 08:05:29 -07009767bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009768 return entry_point == GetJniDlsymLookupStub() ||
9769 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009770}
9771
Vladimir Markofa458ac2020-02-12 14:08:07 +00009772bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9773 return entry_point == GetJniDlsymLookupCriticalStub() ||
9774 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9775}
9776
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009777const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9778 return GetQuickGenericJniStub();
9779}
9780
Mathieu Chartiere401d142015-04-22 13:56:20 -07009781void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009782 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009783 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9784 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009785 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009786 }
9787}
9788
Alex Lightdb01a092017-04-03 15:39:55 -07009789void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9790 DCHECK(method->IsObsolete());
9791 // We cannot mess with the entrypoints of native methods because they are used to determine how
9792 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9793 if (!method->IsNative()) {
9794 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9795 }
9796}
9797
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009798void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009799 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009800 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009801 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9802 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009803 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9804 os << "Dumping registered class loaders\n";
9805 size_t class_loader_index = 0;
9806 for (const ClassLoaderData& class_loader : class_loaders_) {
9807 ObjPtr<mirror::ClassLoader> loader =
9808 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9809 if (loader != nullptr) {
9810 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9811 bool saw_one_dex_file = false;
9812 for (const DexCacheData& dex_cache : dex_caches_) {
9813 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9814 if (saw_one_dex_file) {
9815 os << ":";
9816 }
9817 saw_one_dex_file = true;
9818 os << dex_cache.dex_file->GetLocation();
9819 }
9820 }
9821 os << "]";
9822 bool found_parent = false;
9823 if (loader->GetParent() != nullptr) {
9824 size_t parent_index = 0;
9825 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9826 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9827 soa.Self()->DecodeJObject(class_loader2.weak_root));
9828 if (loader2 == loader->GetParent()) {
9829 os << ", parent #" << parent_index;
9830 found_parent = true;
9831 break;
9832 }
9833 parent_index++;
9834 }
9835 if (!found_parent) {
9836 os << ", unregistered parent of type "
9837 << loader->GetParent()->GetClass()->PrettyDescriptor();
9838 }
9839 } else {
9840 os << ", no parent";
9841 }
9842 os << "\n";
9843 }
9844 }
9845 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009846 Runtime* runtime = Runtime::Current();
9847 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9848 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009849}
9850
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009851class CountClassesVisitor : public ClassLoaderVisitor {
9852 public:
9853 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9854
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009855 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009856 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009857 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009858 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009859 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9860 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009861 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009862 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009863
9864 size_t num_zygote_classes;
9865 size_t num_non_zygote_classes;
9866};
9867
9868size_t ClassLinker::NumZygoteClasses() const {
9869 CountClassesVisitor visitor;
9870 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009871 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009872}
9873
9874size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009875 CountClassesVisitor visitor;
9876 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009877 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009878}
9879
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009880size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009881 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009882 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009883 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009884}
9885
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009886pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009887 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009888}
9889
9890pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009891 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009892}
9893
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009894void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009895 DCHECK(!init_done_);
9896
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009897 DCHECK(klass != nullptr);
9898 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009899
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009900 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009901 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009902 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9903 int32_t index = static_cast<int32_t>(class_root);
9904 DCHECK(class_roots->Get(index) == nullptr);
9905 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009906}
9907
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009908ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9909 Thread* self,
9910 const std::vector<const DexFile*>& dex_files,
9911 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009912 Handle<mirror::ClassLoader> parent_loader,
9913 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009914
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009915 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009916
Mathieu Chartierc7853442015-03-27 14:35:38 -07009917 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009918 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009919
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009920 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009921 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009922 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009923 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009924 mirror::ObjectArray<mirror::Object>::Alloc(self,
9925 dex_elements_class.Get(),
9926 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009927 Handle<mirror::Class> h_dex_element_class =
9928 hs.NewHandle(dex_elements_class->GetComponentType());
9929
Mathieu Chartierc7853442015-03-27 14:35:38 -07009930 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009931 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009932 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009933
Andreas Gampe08883de2016-11-08 13:20:52 -08009934 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009935 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009936
Andreas Gampe08883de2016-11-08 13:20:52 -08009937 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009938 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009939
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009940 // Fill the elements array.
9941 int32_t index = 0;
9942 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009943 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009944
Calin Juravle7865ac72017-06-28 11:03:12 -07009945 // CreateWellKnownClassLoader is only used by gtests and compiler.
9946 // 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 -07009947 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9948 self,
9949 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009950 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009951 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009952
Mathieu Chartier3738e982017-05-12 16:07:28 -07009953 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9954 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009955 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009956 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009957 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009958 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009959
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009960 Handle<mirror::String> h_file_name = hs2.NewHandle(
9961 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009962 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009963 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9964
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009965 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009966 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009967 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009968
9969 h_dex_elements->Set(index, h_element.Get());
9970 index++;
9971 }
9972 DCHECK_EQ(index, h_dex_elements->GetLength());
9973
9974 // Create DexPathList.
9975 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009976 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009977 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009978 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009979 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009980 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9981 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9982 // elements.
9983 {
9984 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9985 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9986 DCHECK(native_lib_dirs != nullptr);
9987 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9988 DCHECK(list_class != nullptr);
9989 {
9990 StackHandleScope<1> h_list_scope(self);
9991 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9992 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9993 DCHECK(list_init);
9994 list_class = h_list_class.Get();
9995 }
9996 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9997 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9998 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9999 // normally never null), as long as one does not try to add elements, this will still
10000 // work.
10001 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
10002 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010003
Calin Juravle7865ac72017-06-28 11:03:12 -070010004 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010005 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
10006 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -070010007 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010008 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -070010009 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -080010010 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -070010011 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -070010012 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010013
10014 // Make a pretend boot-classpath.
10015 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -070010016 ArtField* const parent_field =
Vladimir Markoe300c4e2021-06-08 16:00:05 +010010017 jni::DecodeArtField(WellKnownClasses::java_lang_ClassLoader_parent);
Roland Levillainf39c9eb2015-05-26 15:02:07 +010010018 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010019 if (parent_loader.Get() == nullptr) {
10020 ScopedObjectAccessUnchecked soa(self);
10021 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
10022 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
10023 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
10024 } else {
10025 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
10026 }
Calin Juravle7865ac72017-06-28 11:03:12 -070010027
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010028 ArtField* shared_libraries_field =
10029 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
10030 DCHECK(shared_libraries_field != nullptr);
10031 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
10032
10033 return h_class_loader.Get();
10034}
10035
10036jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
10037 const std::vector<const DexFile*>& dex_files,
10038 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010039 jobject parent_loader,
10040 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010041 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
10042 WellKnownClasses::dalvik_system_PathClassLoader) ||
10043 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +000010044 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
10045 self->GetJniEnv()->IsSameObject(loader_class,
10046 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010047
10048 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
10049 // We could move the jobject to the callers, but all call-sites do this...
10050 ScopedObjectAccessUnchecked soa(self);
10051
10052 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010053 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010054
10055 Handle<mirror::Class> h_loader_class =
10056 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010057 Handle<mirror::ClassLoader> h_parent =
10058 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
10059 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
10060 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010061
10062 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
10063 self,
10064 dex_files,
10065 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010066 h_parent,
10067 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010068
10069 // Make it a global ref and return.
10070 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010071 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010072 return soa.Env()->NewGlobalRef(local_ref.get());
10073}
10074
Calin Juravle7865ac72017-06-28 11:03:12 -070010075jobject ClassLinker::CreatePathClassLoader(Thread* self,
10076 const std::vector<const DexFile*>& dex_files) {
10077 return CreateWellKnownClassLoader(self,
10078 dex_files,
10079 WellKnownClasses::dalvik_system_PathClassLoader,
10080 nullptr);
10081}
10082
Andreas Gampe8ac75952015-06-02 21:01:45 -070010083void ClassLinker::DropFindArrayClassCache() {
10084 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
10085 find_array_class_cache_next_victim_ = 0;
10086}
10087
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010088void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010089 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010090 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -070010091 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010092 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
10093 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010094 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +010010095 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010096 }
10097 }
10098}
10099
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010100void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10101 for (const ClassLoaderData& data : class_loaders_) {
10102 LinearAlloc* alloc = data.allocator;
10103 if (alloc != nullptr && !visitor->Visit(alloc)) {
10104 break;
10105 }
10106 }
10107}
10108
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010109void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10110 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010111 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010112 Thread* const self = Thread::Current();
10113 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010114 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010115 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010116 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010117 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10118 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010119 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010120 }
10121}
10122
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010123void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010124 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010125 std::vector<ClassLoaderData> to_delete;
10126 // Do the delete outside the lock to avoid lock violation in jit code cache.
10127 {
10128 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10129 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10130 const ClassLoaderData& data = *it;
10131 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010132 ObjPtr<mirror::ClassLoader> class_loader =
10133 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010134 if (class_loader != nullptr) {
10135 ++it;
10136 } else {
10137 VLOG(class_linker) << "Freeing class loader";
10138 to_delete.push_back(data);
10139 it = class_loaders_.erase(it);
10140 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010141 }
10142 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010143 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010144 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010145 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010146 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010147}
10148
Mathieu Chartier65975772016-08-05 10:46:36 -070010149class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10150 public:
10151 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10152 : method_(method),
10153 pointer_size_(pointer_size) {}
10154
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010155 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010156 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10157 holder_ = klass;
10158 }
10159 // Return false to stop searching if holder_ is not null.
10160 return holder_ == nullptr;
10161 }
10162
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010163 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010164 const ArtMethod* const method_;
10165 const PointerSize pointer_size_;
10166};
10167
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010168ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010169 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10170 CHECK(method->IsCopied());
10171 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10172 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010173 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010174}
10175
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010176ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
10177 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010178 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +010010179 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010180 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010181}
10182
Vladimir Markod1f73512020-04-02 10:50:35 +010010183bool ClassLinker::IsUpdatableBootClassPathDescriptor(const char* descriptor ATTRIBUTE_UNUSED) {
10184 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10185 LOG(FATAL) << "UNREACHABLE";
10186 UNREACHABLE();
10187}
10188
Calin Juravle33787682019-07-26 14:27:18 -070010189bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10190 REQUIRES_SHARED(Locks::mutator_lock_) {
10191 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10192 LOG(FATAL) << "UNREACHABLE";
10193 UNREACHABLE();
10194}
10195
10196bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10197 REQUIRES_SHARED(Locks::mutator_lock_) {
10198 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10199 LOG(FATAL) << "UNREACHABLE";
10200 UNREACHABLE();
10201}
10202
10203bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10204 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10205 LOG(FATAL) << "UNREACHABLE";
10206 UNREACHABLE();
10207}
10208
Calin Juravle2c2724c2021-01-14 19:54:23 -080010209void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10210 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10211 LOG(FATAL) << "UNREACHABLE";
10212 UNREACHABLE();
10213}
10214
Roland Levillain0e840272018-08-23 19:55:30 +010010215// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +010010216template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010217 uint32_t method_idx,
10218 Handle<mirror::DexCache> dex_cache,
10219 Handle<mirror::ClassLoader> class_loader,
10220 ArtMethod* referrer,
10221 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +010010222template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010223 uint32_t method_idx,
10224 Handle<mirror::DexCache> dex_cache,
10225 Handle<mirror::ClassLoader> class_loader,
10226 ArtMethod* referrer,
10227 InvokeType type);
10228
Roland Levillain0e840272018-08-23 19:55:30 +010010229// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010230template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010231 Thread* self,
10232 ObjPtr<mirror::Class> java_lang_Class,
10233 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010234template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010235 Thread* self,
10236 ObjPtr<mirror::Class> java_lang_Class,
10237 uint32_t class_size);
10238
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010239} // namespace art