blob: f7fe27dc126eaa66aa028873ca4d40783333bd14 [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>
Alex Lighteb7c1442015-08-31 13:17:42 -070031#include <unordered_map>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070032#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070033#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070034
Andreas Gampe46ee31b2016-12-14 10:11:49 -080035#include "android-base/stringprintf.h"
36
Mathieu Chartierc7853442015-03-27 14:35:38 -070037#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070038#include "art_method-inl.h"
Vladimir Markobf121912019-06-04 13:49:05 +010039#include "barrier.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070040#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080041#include "base/casts.h"
Andreas Gampe19f54162019-05-14 16:16:28 -070042#include "base/file_utils.h"
David Sehr67bf42e2018-02-26 16:43:04 -080043#include "base/leb128.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080044#include "base/logging.h"
Vladimir Markobf121912019-06-04 13:49:05 +010045#include "base/mutex-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080046#include "base/os.h"
47#include "base/quasi_atomic.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070048#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010049#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080050#include "base/stl_util.h"
Vladimir Markob9c29f62019-03-20 14:22:51 +000051#include "base/string_view_cpp20.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080052#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010053#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080054#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080055#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070056#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070057#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070059#include "class_loader_utils.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010060#include "class_root-inl.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070061#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000062#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010063#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080064#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070065#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080066#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080067#include "dex/dex_file-inl.h"
68#include "dex/dex_file_exception_helpers.h"
69#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080070#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000071#include "dex/utf.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010072#include "entrypoints/entrypoint_utils-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070073#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070074#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070075#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080076#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000077#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070078#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070079#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070080#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070081#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000082#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070083#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070084#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070085#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080086#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070087#include "imt_conflict_table.h"
88#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070089#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070090#include "interpreter/interpreter.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000091#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080092#include "jit/jit.h"
93#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010094#include "jni/java_vm_ext.h"
95#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070096#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070097#include "mirror/array-alloc-inl.h"
98#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000099#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -0700100#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800101#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700102#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -0700103#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800104#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -0700105#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700106#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100107#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700108#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800109#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700110#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100111#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000112#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700113#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800114#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000115#include "mirror/object-refvisitor-inl.h"
Alex Lighta9bbc082019-11-14 14:51:41 -0800116#include "mirror/object.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700117#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700118#include "mirror/object_array-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000119#include "mirror/object_array.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700120#include "mirror/object_reference.h"
121#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800122#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700123#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800124#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700125#include "mirror/string-inl.h"
Andreas Gampe501c3b02019-04-17 21:54:27 +0000126#include "mirror/throwable.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100127#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700128#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700129#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700130#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700131#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700132#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700133#include "oat_file_assistant.h"
134#include "oat_file_manager.h"
135#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700136#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700137#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800138#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700139#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700140#include "thread-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000141#include "thread.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700142#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700143#include "trace.h"
Vladimir Markob68bb7a2020-03-17 10:55:25 +0000144#include "transaction.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100145#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700146#include "verifier/class_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700147#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700148
Nicolas Geoffray00391822019-12-10 10:17:23 +0000149#include "interpreter/interpreter_mterp_impl.h"
150
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700151namespace art {
152
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800153using android::base::StringPrintf;
154
Mathieu Chartierc7853442015-03-27 14:35:38 -0700155static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700156static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700157
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700158static void ThrowNoClassDefFoundError(const char* fmt, ...)
159 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700160 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700161static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700162 va_list args;
163 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800164 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000165 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800166 va_end(args);
167}
168
Andreas Gampe99babb62015-11-02 16:20:00 -0800169static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700170 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700171 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700172 StackHandleScope<1> hs(self);
173 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700174 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700175 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700176
177 if (exception_class == nullptr) {
178 // No exc class ~ no <init>-with-string.
179 CHECK(self->IsExceptionPending());
180 self->ClearException();
181 return false;
182 }
183
Vladimir Markoba118822017-06-12 15:41:56 +0100184 ArtMethod* exception_init_method = exception_class->FindConstructor(
185 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700186 return exception_init_method != nullptr;
187}
188
Vladimir Markobb206de2019-03-28 10:30:32 +0000189static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700190 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700191 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
192 if (ext == nullptr) {
193 return nullptr;
194 } else {
195 return ext->GetVerifyError();
196 }
197}
198
199// Helper for ThrowEarlierClassFailure. Throws the stored error.
200static void HandleEarlierVerifyError(Thread* self,
201 ClassLinker* class_linker,
202 ObjPtr<mirror::Class> c)
203 REQUIRES_SHARED(Locks::mutator_lock_) {
204 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800205 DCHECK(obj != nullptr);
206 self->AssertNoPendingException();
207 if (obj->IsClass()) {
208 // Previous error has been stored as class. Create a new exception of that type.
209
210 // It's possible the exception doesn't have a <init>(String).
211 std::string temp;
212 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
213
214 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700215 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800216 } else {
217 self->ThrowNewException(descriptor, nullptr);
218 }
219 } else {
220 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100221 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700222 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800223 CHECK(throwable_class->IsAssignableFrom(error_class));
224 self->SetException(obj->AsThrowable());
225 }
226 self->AssertPendingException();
227}
228
Andreas Gampe5b20b352018-10-11 19:03:20 -0700229// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
230// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
231// before.
Andreas Gampe5b20b352018-10-11 19:03:20 -0700232static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
233 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000234 Runtime* runtime = Runtime::Current();
235 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampe5b20b352018-10-11 19:03:20 -0700236 if (!klass->WasVerificationAttempted()) {
237 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
238 klass->SetVerificationAttempted();
Nicolas Geoffray00391822019-12-10 10:17:23 +0000239 // Now that the class has passed verification, try to set nterp entrypoints
240 // to methods that currently use the switch interpreter.
241 if (interpreter::CanRuntimeUseNterp()) {
242 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
243 if (class_linker->IsQuickToInterpreterBridge(m.GetEntryPointFromQuickCompiledCode()) &&
244 interpreter::CanMethodUseNterp(&m)) {
245 if (klass->IsVisiblyInitialized() || !NeedsClinitCheckBeforeCall(&m)) {
246 runtime->GetInstrumentation()->UpdateMethodsCode(&m, interpreter::GetNterpEntryPoint());
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +0000247 } else {
248 // Put the resolution stub, which will initialize the class and then
249 // call the method with nterp.
250 runtime->GetInstrumentation()->UpdateMethodsCode(&m, GetQuickResolutionStub());
Nicolas Geoffray00391822019-12-10 10:17:23 +0000251 }
252 }
253 }
254 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700255 }
256}
257
Vladimir Markobf121912019-06-04 13:49:05 +0100258// Callback responsible for making a batch of classes visibly initialized
259// after all threads have called it from a checkpoint, ensuring visibility.
260class ClassLinker::VisiblyInitializedCallback final
261 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
262 public:
263 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
264 : class_linker_(class_linker),
265 num_classes_(0u),
266 thread_visibility_counter_(0),
267 barriers_() {
268 std::fill_n(classes_, kMaxClasses, nullptr);
269 }
270
271 bool IsEmpty() const {
272 DCHECK_LE(num_classes_, kMaxClasses);
273 return num_classes_ == 0u;
274 }
275
276 bool IsFull() const {
277 DCHECK_LE(num_classes_, kMaxClasses);
278 return num_classes_ == kMaxClasses;
279 }
280
281 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
282 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
283 DCHECK(!IsFull());
284 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
285 ++num_classes_;
286 }
287
288 void AddBarrier(Barrier* barrier) {
289 barriers_.push_front(barrier);
290 }
291
292 std::forward_list<Barrier*> GetAndClearBarriers() {
293 std::forward_list<Barrier*> result;
294 result.swap(barriers_);
295 result.reverse(); // Return barriers in insertion order.
296 return result;
297 }
298
299 void MakeVisible(Thread* self) {
300 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
301 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
302 AdjustThreadVisibilityCounter(self, count);
303 }
304
305 void Run(Thread* self) override {
306 self->ClearMakeVisiblyInitializedCounter();
307 AdjustThreadVisibilityCounter(self, -1);
308 }
309
310 private:
311 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
312 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
313 if (old + adjustment == 0) {
314 // All threads passed the checkpoint. Mark classes as visibly initialized.
315 {
316 ScopedObjectAccess soa(self);
317 StackHandleScope<1u> hs(self);
318 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
319 JavaVMExt* vm = self->GetJniEnv()->GetVm();
320 for (size_t i = 0, num = num_classes_; i != num; ++i) {
321 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
322 vm->DeleteWeakGlobalRef(self, classes_[i]);
323 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100324 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100325 class_linker_->FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100326 }
327 }
328 num_classes_ = 0u;
329 }
330 class_linker_->VisiblyInitializedCallbackDone(self, this);
331 }
332 }
333
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100334 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100335
336 ClassLinker* const class_linker_;
337 size_t num_classes_;
338 jweak classes_[kMaxClasses];
339
340 // The thread visibility counter starts at 0 and it is incremented by the number of
341 // threads that need to run this callback (by the thread that request the callback
342 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
343 // whether after the increment or after a decrement, we know that `Run()` was executed
344 // for all threads and therefore we can mark the classes as visibly initialized.
345 std::atomic<ssize_t> thread_visibility_counter_;
346
347 // List of barries to `Pass()` for threads that wait for the callback to complete.
348 std::forward_list<Barrier*> barriers_;
349};
350
351void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
352 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
353 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
354 }
355 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
356 if (wait) {
357 maybe_barrier.emplace(0);
358 }
359 int wait_count = 0;
360 VisiblyInitializedCallback* callback = nullptr;
361 {
362 MutexLock lock(self, visibly_initialized_callback_lock_);
363 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
364 callback = visibly_initialized_callback_.release();
365 running_visibly_initialized_callbacks_.push_front(*callback);
366 }
367 if (wait) {
368 DCHECK(maybe_barrier.has_value());
369 Barrier* barrier = std::addressof(*maybe_barrier);
370 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
371 cb.AddBarrier(barrier);
372 ++wait_count;
373 }
374 }
375 }
376 if (callback != nullptr) {
377 callback->MakeVisible(self);
378 }
379 if (wait_count != 0) {
380 DCHECK(maybe_barrier.has_value());
381 maybe_barrier->Increment(self, wait_count);
382 }
383}
384
385void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
386 VisiblyInitializedCallback* callback) {
387 MutexLock lock(self, visibly_initialized_callback_lock_);
388 // Pass the barriers if requested.
389 for (Barrier* barrier : callback->GetAndClearBarriers()) {
390 barrier->Pass(self);
391 }
392 // Remove the callback from the list of running callbacks.
393 auto before = running_visibly_initialized_callbacks_.before_begin();
394 auto it = running_visibly_initialized_callbacks_.begin();
395 DCHECK(it != running_visibly_initialized_callbacks_.end());
396 while (std::addressof(*it) != callback) {
397 before = it;
398 ++it;
399 DCHECK(it != running_visibly_initialized_callbacks_.end());
400 }
401 running_visibly_initialized_callbacks_.erase_after(before);
402 // Reuse or destroy the callback object.
403 if (visibly_initialized_callback_ == nullptr) {
404 visibly_initialized_callback_.reset(callback);
405 } else {
406 delete callback;
407 }
408}
409
Alex Lightfb119572019-09-18 15:04:53 -0700410void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
411 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
412 if (cb != nullptr) {
413 cb->MakeVisible(self);
414 }
415 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
416 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
417}
418
Vladimir Markobf121912019-06-04 13:49:05 +0100419ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
420 Thread* self, Handle<mirror::Class> klass) {
421 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
422 // Thanks to the x86 memory model, we do not need any memory fences and
423 // we can immediately mark the class as visibly initialized.
424 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100425 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100426 return nullptr;
427 }
428 if (Runtime::Current()->IsActiveTransaction()) {
429 // Transactions are single-threaded, so we can mark the class as visibly intialized.
430 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
431 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100432 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100433 return nullptr;
434 }
435 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
436 MutexLock lock(self, visibly_initialized_callback_lock_);
437 if (visibly_initialized_callback_ == nullptr) {
438 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
439 }
440 DCHECK(!visibly_initialized_callback_->IsFull());
441 visibly_initialized_callback_->AddClass(self, klass.Get());
442
443 if (visibly_initialized_callback_->IsFull()) {
444 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
445 running_visibly_initialized_callbacks_.push_front(*callback);
446 return callback;
447 } else {
448 return nullptr;
449 }
450}
451
Vladimir Marko86c87522020-05-11 16:55:55 +0100452const void* ClassLinker::RegisterNative(
453 Thread* self, ArtMethod* method, const void* native_method) {
454 CHECK(method->IsNative()) << method->PrettyMethod();
455 CHECK(native_method != nullptr) << method->PrettyMethod();
456 void* new_native_method = nullptr;
457 Runtime* runtime = Runtime::Current();
458 runtime->GetRuntimeCallbacks()->RegisterNativeMethod(method,
459 native_method,
460 /*out*/&new_native_method);
461 if (method->IsCriticalNative()) {
462 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
463 // Remove old registered method if any.
464 auto it = critical_native_code_with_clinit_check_.find(method);
465 if (it != critical_native_code_with_clinit_check_.end()) {
466 critical_native_code_with_clinit_check_.erase(it);
467 }
468 // To ensure correct memory visibility, we need the class to be visibly
469 // initialized before we can set the JNI entrypoint.
470 if (method->GetDeclaringClass()->IsVisiblyInitialized()) {
471 method->SetEntryPointFromJni(new_native_method);
472 } else {
473 critical_native_code_with_clinit_check_.emplace(method, new_native_method);
474 }
475 } else {
476 method->SetEntryPointFromJni(new_native_method);
477 }
478 return new_native_method;
479}
480
481void ClassLinker::UnregisterNative(Thread* self, ArtMethod* method) {
482 CHECK(method->IsNative()) << method->PrettyMethod();
483 // Restore stub to lookup native pointer via dlsym.
484 if (method->IsCriticalNative()) {
485 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
486 auto it = critical_native_code_with_clinit_check_.find(method);
487 if (it != critical_native_code_with_clinit_check_.end()) {
488 critical_native_code_with_clinit_check_.erase(it);
489 }
490 method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
491 } else {
492 method->SetEntryPointFromJni(GetJniDlsymLookupStub());
493 }
494}
495
496const void* ClassLinker::GetRegisteredNative(Thread* self, ArtMethod* method) {
497 if (method->IsCriticalNative()) {
498 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
499 auto it = critical_native_code_with_clinit_check_.find(method);
500 if (it != critical_native_code_with_clinit_check_.end()) {
501 return it->second;
502 }
503 const void* native_code = method->GetEntryPointFromJni();
504 return IsJniDlsymLookupCriticalStub(native_code) ? nullptr : native_code;
505 } else {
506 const void* native_code = method->GetEntryPointFromJni();
507 return IsJniDlsymLookupStub(native_code) ? nullptr : native_code;
508 }
509}
510
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800511void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
512 bool wrap_in_no_class_def,
513 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700514 // The class failed to initialize on a previous attempt, so we want to throw
515 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
516 // failed in verification, in which case v2 5.4.1 says we need to re-throw
517 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800518 Runtime* const runtime = Runtime::Current();
519 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700520 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000521 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
522 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800523 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700524 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800525 } else {
526 extra = verify_error->AsThrowable()->Dump();
527 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700528 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800529 if (log) {
530 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
531 << ": " << extra;
532 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700533 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700534
David Sehr709b0702016-10-13 09:12:37 -0700535 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800536 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800537 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700538 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700539 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000540 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700541 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000542 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
543 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800544 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800545 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800546 }
Alex Lightd6251582016-10-31 11:12:30 -0700547 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
548 // might have meant to go down the earlier if statement with the original error but it got
549 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000550 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800551 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
552 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
553 // exception will be a cause.
554 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700555 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700556 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700557 }
558}
559
Brian Carlstromb23eab12014-10-08 17:55:21 -0700560static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700561 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700562 if (VLOG_IS_ON(class_linker)) {
563 std::string temp;
564 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000565 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700566 }
567}
568
569static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700570 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700571 Thread* self = Thread::Current();
572 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700573
574 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700575 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700576
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800577 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
578 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
579 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800580 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800581 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
582 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
583 // could have caused the error.
584 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
585 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
586 << " failed initialization: "
587 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800588 }
589
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700590 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700591 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
592 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700593
Elliott Hughesa4f94742012-05-29 16:28:38 -0700594 // We only wrap non-Error exceptions; an Error can just be used as-is.
595 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000596 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700597 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700598 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700599}
600
Fred Shih381e4ca2014-08-25 17:24:27 -0700601// Gap between two fields in object layout.
602struct FieldGap {
603 uint32_t start_offset; // The offset from the start of the object.
604 uint32_t size; // The gap size of 1, 2, or 4 bytes.
605};
606struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800607 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700608 }
609 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
610 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800611 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700612 // Note that the priority queue returns the largest element, so operator()
613 // should return true if lhs is less than rhs.
614 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700615 }
616};
Andreas Gampec55bb392018-09-21 00:02:02 +0000617using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700618
619// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800620static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700621 DCHECK(gaps != nullptr);
622
623 uint32_t current_offset = gap_start;
624 while (current_offset != gap_end) {
625 size_t remaining = gap_end - current_offset;
626 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
627 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
628 current_offset += sizeof(uint32_t);
629 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
630 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
631 current_offset += sizeof(uint16_t);
632 } else {
633 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
634 current_offset += sizeof(uint8_t);
635 }
636 DCHECK_LE(current_offset, gap_end) << "Overran gap";
637 }
638}
639// Shuffle fields forward, making use of gaps whenever possible.
640template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000641static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700642 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700643 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700644 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700645 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700646 DCHECK(current_field_idx != nullptr);
647 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700648 DCHECK(gaps != nullptr);
649 DCHECK(field_offset != nullptr);
650
651 DCHECK(IsPowerOfTwo(n));
652 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700653 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700654 Primitive::Type type = field->GetTypeAsPrimitiveType();
655 if (Primitive::ComponentSize(type) < n) {
656 break;
657 }
658 if (!IsAligned<n>(field_offset->Uint32Value())) {
659 MemberOffset old_offset = *field_offset;
660 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
661 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
662 }
David Sehr709b0702016-10-13 09:12:37 -0700663 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700664 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700665 if (!gaps->empty() && gaps->top().size >= n) {
666 FieldGap gap = gaps->top();
667 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100668 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700669 field->SetOffset(MemberOffset(gap.start_offset));
670 if (gap.size > n) {
671 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
672 }
673 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100674 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700675 field->SetOffset(*field_offset);
676 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
677 }
678 ++(*current_field_idx);
679 }
680}
681
Andreas Gampe87658f32019-04-18 18:39:02 +0000682ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700683 : boot_class_table_(new ClassTable()),
684 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800685 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800686 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700687 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000688 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700689 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000690 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000691 jni_dlsym_lookup_trampoline_(nullptr),
Vladimir Markofa458ac2020-02-12 14:08:07 +0000692 jni_dlsym_lookup_critical_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800693 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800694 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100695 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800696 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700697 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100698 visibly_initialized_callback_lock_("visibly initialized callback lock"),
699 visibly_initialized_callback_(nullptr),
Vladimir Marko86c87522020-05-11 16:55:55 +0100700 critical_native_code_with_clinit_check_lock_("critical native code with clinit check lock"),
701 critical_native_code_with_clinit_check_(),
Andreas Gampe7dface32017-07-25 21:32:59 -0700702 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
703 // For CHA disabled during Aot, see b/34193647.
704
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700705 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700706 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
707 "Array cache size wrong.");
708 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700709}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700710
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800711void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700712 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800713 if (c2 == nullptr) {
714 LOG(FATAL) << "Could not find class " << descriptor;
715 UNREACHABLE();
716 }
717 if (c1.Get() != c2) {
718 std::ostringstream os1, os2;
719 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
720 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
721 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
722 << ". This is most likely the result of a broken build. Make sure that "
723 << "libcore and art projects match.\n\n"
724 << os1.str() << "\n\n" << os2.str();
725 UNREACHABLE();
726 }
727}
728
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800729bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
730 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800731 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700732
Mathieu Chartiere401d142015-04-22 13:56:20 -0700733 Thread* const self = Thread::Current();
734 Runtime* const runtime = Runtime::Current();
735 gc::Heap* const heap = runtime->GetHeap();
736
Jeff Haodcdc85b2015-12-04 14:06:18 -0800737 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700738 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700739
Mathieu Chartiere401d142015-04-22 13:56:20 -0700740 // Use the pointer size from the runtime since we are probably creating the image.
741 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
742
Elliott Hughes30646832011-10-13 16:59:46 -0700743 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700744 // 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 -0800745 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700746 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700747 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700748 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
749 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000750 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100751 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800752 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100753 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700754 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700755 if (kUseBakerReadBarrier) {
756 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800757 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700758 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700759 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800760 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700761 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700762
Elliott Hughes418d20f2011-09-22 14:00:39 -0700763 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700764 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700765 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700766 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700767 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700768
Ian Rogers23435d02012-09-24 11:23:12 -0700769 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700770 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700771 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800772 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700773 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700774 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000775 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700776
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700777 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800778 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
779 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100780 runtime->SetSentinel(heap->AllocNonMovableObject(self,
781 java_lang_Object.Get(),
782 java_lang_Object->GetObjectSize(),
783 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700784
Igor Murashkin86083f72017-10-27 10:59:04 -0700785 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000786 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700787 // It might seem the lock here is unnecessary, however all the SubtypeCheck
788 // functions are annotated to require locks all the way down.
789 //
790 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
791 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000792 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
793 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700794 }
795
Ian Rogers23435d02012-09-24 11:23:12 -0700796 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700797 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700798 AllocClass(self, java_lang_Class.Get(),
799 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700800 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700801
Roland Levillain0e840272018-08-23 19:55:30 +0100802 // Setup java.lang.String.
803 //
804 // We make this class non-movable for the unlikely case where it were to be
805 // moved by a sticky-bit (minor) collection when using the Generational
806 // Concurrent Copying (CC) collector, potentially creating a stale reference
807 // in the `klass_` field of one of its instances allocated in the Large-Object
808 // Space (LOS) -- see the comment about the dirty card scanning logic in
809 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700810 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700811 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100812 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700813 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000814 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400815
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700816 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700817 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700818 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700819 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000820 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700821
Ian Rogers23435d02012-09-24 11:23:12 -0700822 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700823 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100824 mirror::ObjectArray<mirror::Class>::Alloc(self,
825 object_array_class.Get(),
826 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700827 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100828 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
829 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
830 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
831 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100832 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
833 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700834
Mathieu Chartier6beced42016-11-15 15:51:31 -0800835 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
836 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
837
Vladimir Marko02610552018-06-04 14:38:00 +0100838 // Create array interface entries to populate once we can load system classes.
839 object_array_class->SetIfTable(AllocIfTable(self, 2));
840 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
841
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700842 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100843 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
844 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
845 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
846 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
847 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
848 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
849 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
850 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
851 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700852
Vladimir Marko70e2a762019-07-12 16:49:00 +0100853 // Allocate the primitive array classes. We need only the native pointer
854 // array at this point (int[] or long[], depending on architecture) but
855 // we shall perform the same setup steps for all primitive array classes.
856 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
857 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
858 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
859 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
860 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
861 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
862 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
863 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700864
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700865 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700866
Ian Rogers52813c92012-10-11 11:50:38 -0700867 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700868 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700869 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100870 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100871 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700872 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000873 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700874
Alex Lightd6251582016-10-31 11:12:30 -0700875
876 // Setup dalvik.system.ClassExt
877 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
878 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100879 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000880 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700881
Mathieu Chartier66f19252012-09-18 08:57:04 -0700882 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700883 Handle<mirror::Class> object_array_string(hs.NewHandle(
884 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700885 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700886 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100887 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700888
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000889 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700890 // Create runtime resolution and imt conflict methods.
891 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000892 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
893 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700894
Ian Rogers23435d02012-09-24 11:23:12 -0700895 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
896 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
897 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800898 if (boot_class_path.empty()) {
899 *error_msg = "Boot classpath is empty.";
900 return false;
901 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800902 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800903 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800904 *error_msg = "Null dex file.";
905 return false;
906 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800907 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800908 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700909 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700910
911 // now we can use FindSystemClass
912
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700913 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
914 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700915 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800916 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700917 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000918 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Vladimir Markofa458ac2020-02-12 14:08:07 +0000919 jni_dlsym_lookup_critical_trampoline_ = GetJniDlsymLookupCriticalStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700920 quick_resolution_trampoline_ = GetQuickResolutionStub();
921 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000922 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700923 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700924 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700925
Alex Lightd6251582016-10-31 11:12:30 -0700926 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000927 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800928 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700929 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000930 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800931 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000932 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800933 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700934 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000935 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700936 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
937 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700938
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800939 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
940 // in class_table_.
941 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700942
Vladimir Marko70e2a762019-07-12 16:49:00 +0100943 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
944 // arrays - can't be done until Object has a vtable and component classes are loaded.
945 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
946 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
947 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
948 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
949 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
950 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
951 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
952 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
953 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
954 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
955 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700956
Ian Rogers23435d02012-09-24 11:23:12 -0700957 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700958 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800959 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700960 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800961 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700962 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
963 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100964 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
965 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700966
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700967 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
968 // suspension.
969 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000970 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700971 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000972 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700973 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000974 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700975 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000976 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700977
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700978 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100979 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700980
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800981 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700982
Ian Rogers23435d02012-09-24 11:23:12 -0700983 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100984 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
985 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700986
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700987 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100988 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700989 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100990 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700991
992 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700993 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
994 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100995 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700996
997 // Create java.lang.reflect.Constructor.class root and array root.
998 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
999 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001000 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001001 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
1002 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001003 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001004
1005 // Create java.lang.reflect.Method.class root and array root.
1006 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
1007 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001008 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001009 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
1010 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001011 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001012
Orion Hodson005ac512017-10-24 15:43:43 +01001013 // Create java.lang.invoke.CallSite.class root
1014 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
1015 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001016 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001017
Narayan Kamathafa48272016-08-03 12:46:58 +01001018 // Create java.lang.invoke.MethodType.class root
1019 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
1020 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001021 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +01001022
1023 // Create java.lang.invoke.MethodHandleImpl.class root
1024 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
1025 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001026 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01001027 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +01001028
Orion Hodsonc069a302017-01-18 09:23:12 +00001029 // Create java.lang.invoke.MethodHandles.Lookup.class root
1030 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
1031 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001032 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +00001033
Orion Hodson005ac512017-10-24 15:43:43 +01001034 // Create java.lang.invoke.VarHandle.class root
1035 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +00001036 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001037 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001038
1039 // Create java.lang.invoke.FieldVarHandle.class root
1040 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
1041 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001042 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001043
1044 // Create java.lang.invoke.ArrayElementVarHandle.class root
1045 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
1046 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001047 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001048
1049 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
1050 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
1051 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001052 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001053
1054 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
1055 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
1056 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001057 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +00001058
Narayan Kamath000e1882016-10-24 17:14:25 +01001059 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
1060 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001061 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +01001062
Brian Carlstrom1f870082011-08-23 16:02:11 -07001063 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -07001064 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +00001065 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -08001066 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -07001067 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001068 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
1069 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001070 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001071 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001072 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001073 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001074 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001075 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001076 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001077 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001078 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001079 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001080 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001081 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001082
Ian Rogers23435d02012-09-24 11:23:12 -07001083 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001084 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001085 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001086 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001087 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001088
jeffhao8cd6dda2012-02-22 10:15:34 -08001089 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -07001090 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001091 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001092 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -07001093 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001094 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
1095 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
1096 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001097 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001098 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1099 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001100
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001101 // Create conflict tables that depend on the class linker.
1102 runtime->FixupConflictTables();
1103
Ian Rogers98379392014-02-24 16:53:16 -08001104 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001105
Brian Carlstroma004aa92012-02-08 18:05:09 -08001106 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001107
1108 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001109}
1110
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001111static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1112 REQUIRES_SHARED(Locks::mutator_lock_) {
1113 // Find String.<init> -> StringFactory bindings.
1114 ObjPtr<mirror::Class> string_factory_class =
1115 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1116 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001117 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001118 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1119 // Update the primordial thread.
1120 self->InitStringEntryPoints();
1121}
1122
Ian Rogers98379392014-02-24 16:53:16 -08001123void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001124 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001125
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001126 CreateStringInitBindings(self, this);
1127
Brian Carlstrom16192862011-09-12 17:50:06 -07001128 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001129 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001130 // as the types of the field can't be resolved prior to the runtime being
1131 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001132 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001133 Handle<mirror::Class> java_lang_ref_Reference =
1134 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001135 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1136 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001137
Mathieu Chartierc7853442015-03-27 14:35:38 -07001138 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001139 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1140 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001141
Mathieu Chartierc7853442015-03-27 14:35:38 -07001142 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001143 CHECK_STREQ(queue->GetName(), "queue");
1144 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001145
Mathieu Chartierc7853442015-03-27 14:35:38 -07001146 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001147 CHECK_STREQ(queueNext->GetName(), "queueNext");
1148 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001149
Mathieu Chartierc7853442015-03-27 14:35:38 -07001150 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001151 CHECK_STREQ(referent->GetName(), "referent");
1152 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001153
Mathieu Chartierc7853442015-03-27 14:35:38 -07001154 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001155 CHECK_STREQ(zombie->GetName(), "zombie");
1156 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001157
Brian Carlstroma663ea52011-08-19 23:33:41 -07001158 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001159 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001160 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001161 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001162 CHECK(klass != nullptr);
1163 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001164 // note SetClassRoot does additional validation.
1165 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001166 }
1167
Vladimir Marko02610552018-06-04 14:38:00 +01001168 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001169
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001170 // disable the slow paths in FindClass and CreatePrimitiveClass now
1171 // that Object, Class, and Object[] are setup
1172 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001173
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001174 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1175 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1176 // ensure that the class will be initialized.
1177 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001178 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001179
1180 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1181 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1182 // Strange, but don't crash.
1183 LOG(WARNING) << "Could not prepare StackOverflowError.";
1184 self->ClearException();
1185 }
1186 }
1187
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001188 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001189}
1190
Vladimir Markodcfcce42018-06-27 10:00:28 +00001191void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001192 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1193 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001194 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001195 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001196 Handle<mirror::Class> h_class(hs.NewHandle(c));
David Srbecky08110ef2020-05-20 19:33:43 +01001197 if (!EnsureInitialized(self, h_class, true, true)) {
1198 LOG(FATAL) << "Exception when initializing " << h_class->PrettyClass()
1199 << ": " << self->GetException()->Dump();
1200 }
Vladimir Markodcfcce42018-06-27 10:00:28 +00001201 } else {
1202 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001203 }
1204 }
1205}
1206
Jeff Haodcdc85b2015-12-04 14:06:18 -08001207struct TrampolineCheckData {
1208 const void* quick_resolution_trampoline;
1209 const void* quick_imt_conflict_trampoline;
1210 const void* quick_generic_jni_trampoline;
1211 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001212 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001213 ArtMethod* m;
1214 bool error;
1215};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001216
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001217bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1218 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001219 CHECK(!init_done_);
1220
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001221 Runtime* const runtime = Runtime::Current();
1222 Thread* const self = Thread::Current();
1223 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001224 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1225 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001226 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1227 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001228 if (!ValidPointerSize(pointer_size_unchecked)) {
1229 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001230 return false;
1231 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001232 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001233 if (!runtime->IsAotCompiler()) {
1234 // Only the Aot compiler supports having an image with a different pointer size than the
1235 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1236 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001237 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001238 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001239 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001240 sizeof(void*));
1241 return false;
1242 }
1243 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001244 DCHECK(!runtime->HasResolutionMethod());
1245 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1246 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1247 runtime->SetImtUnimplementedMethod(
1248 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1249 runtime->SetCalleeSaveMethod(
1250 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1251 CalleeSaveType::kSaveAllCalleeSaves);
1252 runtime->SetCalleeSaveMethod(
1253 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1254 CalleeSaveType::kSaveRefsOnly);
1255 runtime->SetCalleeSaveMethod(
1256 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1257 CalleeSaveType::kSaveRefsAndArgs);
1258 runtime->SetCalleeSaveMethod(
1259 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1260 CalleeSaveType::kSaveEverything);
1261 runtime->SetCalleeSaveMethod(
1262 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1263 CalleeSaveType::kSaveEverythingForClinit);
1264 runtime->SetCalleeSaveMethod(
1265 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1266 CalleeSaveType::kSaveEverythingForSuspendCheck);
1267
Jeff Haodcdc85b2015-12-04 14:06:18 -08001268 std::vector<const OatFile*> oat_files =
1269 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1270 DCHECK(!oat_files.empty());
1271 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001272 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001273 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001274 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1275 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1276 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1277 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1278 if (kIsDebugBuild) {
1279 // Check that the other images use the same trampoline.
1280 for (size_t i = 1; i < oat_files.size(); ++i) {
1281 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001282 const void* ith_jni_dlsym_lookup_trampoline_ =
1283 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001284 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1285 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001286 const void* ith_quick_resolution_trampoline =
1287 ith_oat_header.GetQuickResolutionTrampoline();
1288 const void* ith_quick_imt_conflict_trampoline =
1289 ith_oat_header.GetQuickImtConflictTrampoline();
1290 const void* ith_quick_generic_jni_trampoline =
1291 ith_oat_header.GetQuickGenericJniTrampoline();
1292 const void* ith_quick_to_interpreter_bridge_trampoline =
1293 ith_oat_header.GetQuickToInterpreterBridge();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001294 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001295 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001296 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001297 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1298 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1299 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1300 // Make sure that all methods in this image do not contain those trampolines as
1301 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1302 TrampolineCheckData data;
1303 data.error = false;
1304 data.pointer_size = GetImagePointerSize();
1305 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1306 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1307 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1308 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1309 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001310 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1311 if (obj->IsClass()) {
1312 ObjPtr<mirror::Class> klass = obj->AsClass();
1313 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1314 const void* entrypoint =
1315 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1316 if (entrypoint == data.quick_resolution_trampoline ||
1317 entrypoint == data.quick_imt_conflict_trampoline ||
1318 entrypoint == data.quick_generic_jni_trampoline ||
1319 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1320 data.m = &m;
1321 data.error = true;
1322 return;
1323 }
1324 }
1325 }
1326 };
1327 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001328 if (data.error) {
1329 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001330 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001331 *error_msg = "Found an ArtMethod with a bad entrypoint";
1332 return false;
1333 }
1334 }
1335 }
1336 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001337
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001338 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001339 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001340 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001341 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001342
Vladimir Marko024d69f2019-06-13 10:52:32 +01001343 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1344 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1345 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1346 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1347 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1348 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001349
Vladimir Markod1908512018-11-22 14:57:28 +00001350 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001351 // Boot class loader, use a null handle.
1352 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001353 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001354 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001355 /*out*/&dex_files,
1356 error_msg)) {
1357 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001358 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001359 // Append opened dex files at the end.
1360 boot_dex_files_.insert(boot_dex_files_.end(),
1361 std::make_move_iterator(dex_files.begin()),
1362 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001363 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001364 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1365 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1366 }
Ian Rogers98379392014-02-24 16:53:16 -08001367 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001368
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001369 VLOG(startup) << __FUNCTION__ << " exiting";
1370 return true;
1371}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001372
Vladimir Marko4433c432018-12-04 14:57:47 +00001373void ClassLinker::AddExtraBootDexFiles(
1374 Thread* self,
1375 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1376 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001377 AppendToBootClassPath(self, dex_file.get());
Vladimir Marko4433c432018-12-04 14:57:47 +00001378 boot_dex_files_.push_back(std::move(dex_file));
1379 }
1380}
1381
Jeff Hao5872d7c2016-04-27 11:07:41 -07001382bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001383 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001384 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001385 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1386 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001387}
1388
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001389class CHAOnDeleteUpdateClassVisitor {
1390 public:
1391 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1392 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1393 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1394 self_(Thread::Current()) {}
1395
1396 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1397 // This class is going to be unloaded. Tell CHA about it.
1398 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1399 return true;
1400 }
1401 private:
1402 const LinearAlloc* allocator_;
1403 const ClassHierarchyAnalysis* cha_;
1404 const PointerSize pointer_size_;
1405 const Thread* self_;
1406};
1407
Chris Wailes0c61be42018-09-26 17:27:34 -07001408/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001409 * A class used to ensure that all references to strings interned in an AppImage have been
1410 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001411 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001412class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001413 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001414 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1415 const InternTable::UnorderedSet& image_interns)
1416 : space_(space),
1417 image_interns_(image_interns),
1418 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001419
Chris Wailes0c61be42018-09-26 17:27:34 -07001420 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001421 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001422 if (referred_obj != nullptr &&
1423 space_.HasAddress(referred_obj.Ptr()) &&
1424 referred_obj->IsString()) {
1425 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001426 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1427 if (it != image_interns_.end() && it->Read() == referred_str) {
1428 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001429 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001430 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001431 }
1432
Chris Wailes0c61be42018-09-26 17:27:34 -07001433 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001434 mirror::CompressedReference<mirror::Object>* root) const
1435 REQUIRES_SHARED(Locks::mutator_lock_) {
1436 if (!root->IsNull()) {
1437 VisitRoot(root);
1438 }
1439 }
1440
Chris Wailes0c61be42018-09-26 17:27:34 -07001441 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001442 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001443 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001444 }
1445
1446 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001447 void operator()(ObjPtr<mirror::Object> obj,
1448 MemberOffset offset,
1449 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001450 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001451 // References within image or across images don't need a read barrier.
1452 ObjPtr<mirror::Object> referred_obj =
1453 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1454 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001455 }
1456
1457 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1458 ObjPtr<mirror::Reference> ref) const
1459 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001460 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001461 }
1462
Vladimir Marko8e05f092019-06-10 11:10:38 +01001463 size_t GetCount() const {
1464 return count_;
1465 }
1466
1467 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001468 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001469 const InternTable::UnorderedSet& image_interns_;
1470 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001471};
1472
Chris Wailes0c61be42018-09-26 17:27:34 -07001473/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001474 * This function counts references to strings interned in the AppImage.
1475 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001476 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001477size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1478 const InternTable::UnorderedSet& image_interns)
1479 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001480 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1481 const ImageHeader& image_header = space.GetImageHeader();
1482 const uint8_t* target_base = space.GetMemMap()->Begin();
1483 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001484
1485 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1486 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001487
Vladimir Marko8e05f092019-06-10 11:10:38 +01001488 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001489 bitmap->VisitMarkedRange(objects_begin,
1490 objects_end,
1491 [&space, &visitor](mirror::Object* obj)
1492 REQUIRES_SHARED(Locks::mutator_lock_) {
1493 if (space.HasAddress(obj)) {
1494 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001495 obj->VisitReferences</* kVisitNativeRoots= */ true,
1496 kVerifyNone,
1497 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001498 } else {
1499 // Don't visit native roots for non-dex-cache as they can't contain
1500 // native references to strings. This is verified during compilation
1501 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001502 obj->VisitReferences</* kVisitNativeRoots= */ false,
1503 kVerifyNone,
1504 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001505 }
1506 }
1507 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001508 return visitor.GetCount();
1509}
1510
1511template <typename Visitor>
1512static void VisitInternedStringReferences(
1513 gc::space::ImageSpace* space,
1514 bool use_preresolved_strings,
1515 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1516 const uint8_t* target_base = space->Begin();
1517 const ImageSection& sro_section =
1518 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1519 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1520
1521 VLOG(image)
1522 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1523 << num_string_offsets;
1524
1525 const auto* sro_base =
1526 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1527
1528 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1529 uint32_t base_offset = sro_base[offset_index].first;
1530
1531 if (HasDexCacheStringNativeRefTag(base_offset)) {
1532 base_offset = ClearDexCacheNativeRefTags(base_offset);
1533 DCHECK_ALIGNED(base_offset, 2);
1534
1535 ObjPtr<mirror::DexCache> dex_cache =
1536 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1537 uint32_t string_slot_index = sro_base[offset_index].second;
1538
1539 mirror::StringDexCachePair source =
1540 dex_cache->GetStrings()[string_slot_index].load(std::memory_order_relaxed);
1541 ObjPtr<mirror::String> referred_string = source.object.Read();
1542 DCHECK(referred_string != nullptr);
1543
1544 ObjPtr<mirror::String> visited = visitor(referred_string);
1545 if (visited != referred_string) {
1546 // Because we are not using a helper function we need to mark the GC card manually.
1547 WriteBarrier::ForEveryFieldWrite(dex_cache);
1548 dex_cache->GetStrings()[string_slot_index].store(
1549 mirror::StringDexCachePair(visited, source.index), std::memory_order_relaxed);
1550 }
1551 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1552 if (use_preresolved_strings) {
1553 base_offset = ClearDexCacheNativeRefTags(base_offset);
1554 DCHECK_ALIGNED(base_offset, 2);
1555
1556 ObjPtr<mirror::DexCache> dex_cache =
1557 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1558 uint32_t string_index = sro_base[offset_index].second;
1559
Mathieu Chartier77f84fc2019-06-14 12:49:54 -07001560 GcRoot<mirror::String>* preresolved_strings =
1561 dex_cache->GetPreResolvedStrings();
1562 // Handle calls to ClearPreResolvedStrings that might occur concurrently by the profile
1563 // saver that runs shortly after startup. In case the strings are cleared, there is nothing
1564 // to fix up.
1565 if (preresolved_strings != nullptr) {
1566 ObjPtr<mirror::String> referred_string =
1567 preresolved_strings[string_index].Read();
1568 if (referred_string != nullptr) {
1569 ObjPtr<mirror::String> visited = visitor(referred_string);
1570 if (visited != referred_string) {
1571 // Because we are not using a helper function we need to mark the GC card manually.
1572 WriteBarrier::ForEveryFieldWrite(dex_cache);
1573 preresolved_strings[string_index] = GcRoot<mirror::String>(visited);
1574 }
1575 }
Vladimir Marko8e05f092019-06-10 11:10:38 +01001576 }
1577 }
1578 } else {
1579 uint32_t raw_member_offset = sro_base[offset_index].second;
1580 DCHECK_ALIGNED(base_offset, 2);
1581 DCHECK_ALIGNED(raw_member_offset, 2);
1582
1583 ObjPtr<mirror::Object> obj_ptr =
1584 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1585 MemberOffset member_offset(raw_member_offset);
1586 ObjPtr<mirror::String> referred_string =
1587 obj_ptr->GetFieldObject<mirror::String,
1588 kVerifyNone,
1589 kWithoutReadBarrier,
1590 /* kIsVolatile= */ false>(member_offset);
1591 DCHECK(referred_string != nullptr);
1592
1593 ObjPtr<mirror::String> visited = visitor(referred_string);
1594 if (visited != referred_string) {
1595 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1596 /* kCheckTransaction= */ false,
1597 kVerifyNone,
1598 /* kIsVolatile= */ false>(member_offset, visited);
1599 }
1600 }
1601 }
1602}
1603
1604static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1605 REQUIRES_SHARED(Locks::mutator_lock_) {
1606 InternTable::UnorderedSet image_interns;
1607 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1608 if (section.Size() > 0) {
1609 size_t read_count;
1610 const uint8_t* data = space->Begin() + section.Offset();
1611 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1612 image_set.swap(image_interns);
1613 }
1614 size_t num_recorded_refs = 0u;
1615 VisitInternedStringReferences(
1616 space,
1617 /*use_preresolved_strings=*/ true,
1618 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1619 REQUIRES_SHARED(Locks::mutator_lock_) {
1620 auto it = image_interns.find(GcRoot<mirror::String>(str));
1621 CHECK(it != image_interns.end());
1622 CHECK(it->Read() == str);
1623 ++num_recorded_refs;
1624 return str;
1625 });
1626 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1627 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001628}
1629
Andreas Gampe2af99022017-04-25 08:32:59 -07001630// new_class_set is the set of classes that were read from the class table section in the image.
1631// If there was no class table section, it is null.
1632// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001633class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001634 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001635 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001636 ClassLinker* class_linker,
1637 gc::space::ImageSpace* space,
1638 Handle<mirror::ClassLoader> class_loader,
1639 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001640 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001641 REQUIRES(!Locks::dex_lock_)
1642 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001643
Chris Wailesfbeef462018-10-19 14:16:35 -07001644 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001645 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001646};
1647
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001648void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001649 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001650 gc::space::ImageSpace* space,
1651 Handle<mirror::ClassLoader> class_loader,
1652 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001653 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001654 REQUIRES(!Locks::dex_lock_)
1655 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001656 ScopedTrace app_image_timing("AppImage:Updating");
1657
Vladimir Marko8e05f092019-06-10 11:10:38 +01001658 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1659 // In debug build, verify the string references before applying
1660 // the Runtime::LoadAppImageStartupCache() option.
1661 VerifyInternedStringReferences(space);
1662 }
1663
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001664 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001665 Runtime* const runtime = Runtime::Current();
1666 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001667 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001668 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001669 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001670 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001671 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001672 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001673 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001674 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001675 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001676 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001677 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001678 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001679
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001680 if (!load_app_image_startup_cache) {
1681 dex_cache->ClearPreResolvedStrings();
1682 }
1683
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001684 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001685 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001686 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001687 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001688 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001689 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001690 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001691
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001692 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001693 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001694 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001695 DCHECK(it != new_class_set->end());
1696 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001697 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001698
Vladimir Marko1a1de672016-10-13 12:53:15 +01001699 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001700 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001701 DCHECK(it2 != new_class_set->end());
1702 DCHECK_EQ(it2->Read(), super_class);
1703 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001704
Vladimir Marko1a1de672016-10-13 12:53:15 +01001705 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1706 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001707 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1708 if (!class_linker->IsQuickResolutionStub(code) &&
1709 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001710 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001711 !m.IsNative()) {
1712 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001713 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001714 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001715
Vladimir Marko1a1de672016-10-13 12:53:15 +01001716 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1717 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001718 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1719 if (!class_linker->IsQuickResolutionStub(code) &&
1720 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001721 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001722 !m.IsNative()) {
1723 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001724 }
1725 }
1726 }
1727 }
1728 }
1729 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001730 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001731
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001732 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001733 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001734 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001735
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001736 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001737 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001738 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001739 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1740 header.VisitPackedArtMethods([&](ArtMethod& method)
1741 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1742 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1743 if (klass != nullptr) {
1744 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1745 }
1746 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001747 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001748}
1749
Chris Wailesfbeef462018-10-19 14:16:35 -07001750void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001751 // Iterate over the string reference offsets stored in the image and intern
1752 // the strings they point to.
1753 ScopedTrace timing("AppImage:InternString");
1754
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001755 Runtime* const runtime = Runtime::Current();
1756 InternTable* const intern_table = runtime->GetInternTable();
1757
1758 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001759
1760 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1761 // for faster lookup.
1762 // TODO: Optimize with a bitmap or bloom filter
1763 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001764 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001765 REQUIRES_SHARED(Locks::mutator_lock_)
1766 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001767 const size_t non_boot_image_strings = intern_table->CountInterns(
1768 /*visit_boot_images=*/false,
1769 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001770 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001771 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1772 // Visit the smaller of the two sets to compute the intersection.
1773 if (interns.size() < non_boot_image_strings) {
1774 for (auto it = interns.begin(); it != interns.end(); ) {
1775 ObjPtr<mirror::String> string = it->Read();
1776 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1777 if (existing == nullptr) {
1778 existing = intern_table->LookupStrongLocked(string);
1779 }
1780 if (existing != nullptr) {
1781 intern_remap.Put(string.Ptr(), existing.Ptr());
1782 it = interns.erase(it);
1783 } else {
1784 ++it;
1785 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001786 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001787 } else {
1788 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1789 REQUIRES_SHARED(Locks::mutator_lock_)
1790 REQUIRES(Locks::intern_table_lock_) {
1791 auto it = interns.find(root);
1792 if (it != interns.end()) {
1793 ObjPtr<mirror::String> existing = root.Read();
1794 intern_remap.Put(it->Read(), existing.Ptr());
1795 it = interns.erase(it);
1796 }
1797 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1798 }
1799 // Sanity check to ensure correctness.
1800 if (kIsDebugBuild) {
1801 for (GcRoot<mirror::String>& root : interns) {
1802 ObjPtr<mirror::String> string = root.Read();
1803 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1804 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001805 }
1806 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001807 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001808 intern_table->AddImageStringsToTable(space, func);
1809 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001810 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001811 VisitInternedStringReferences(
1812 space,
1813 load_startup_cache,
1814 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1815 auto it = intern_remap.find(str.Ptr());
1816 if (it != intern_remap.end()) {
1817 return ObjPtr<mirror::String>(it->second);
1818 }
1819 return str;
1820 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001821 }
1822}
1823
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001824static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1825 const char* location,
1826 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001827 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001828 DCHECK(error_msg != nullptr);
1829 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001830 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001831 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001832 return std::unique_ptr<const DexFile>();
1833 }
1834 std::string inner_error_msg;
1835 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1836 if (dex_file == nullptr) {
1837 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1838 location,
1839 oat_file->GetLocation().c_str(),
1840 inner_error_msg.c_str());
1841 return std::unique_ptr<const DexFile>();
1842 }
1843
1844 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1845 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1846 location,
1847 dex_file->GetLocationChecksum(),
1848 oat_dex_file->GetDexFileLocationChecksum());
1849 return std::unique_ptr<const DexFile>();
1850 }
1851 return dex_file;
1852}
1853
1854bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1855 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1856 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001857 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001858 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001859 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001860 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001861 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001862 dex_caches_object->AsObjectArray<mirror::DexCache>();
1863 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001864 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001865 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1866 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1867 dex_file_location.c_str(),
1868 error_msg);
1869 if (dex_file == nullptr) {
1870 return false;
1871 }
1872 dex_cache->SetDexFile(dex_file.get());
1873 out_dex_files->push_back(std::move(dex_file));
1874 }
1875 return true;
1876}
1877
Andreas Gampe0793bec2016-12-01 11:37:33 -08001878// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1879// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001880class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001881 public:
1882 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1883 REQUIRES_SHARED(Locks::mutator_lock_) {
1884 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001885 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1886 DCHECK(obj != nullptr);
1887 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1888 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1889 if (obj->IsClass()) {
1890 auto klass = obj->AsClass();
1891 for (ArtField& field : klass->GetIFields()) {
1892 CHECK_EQ(field.GetDeclaringClass(), klass);
1893 }
1894 for (ArtField& field : klass->GetSFields()) {
1895 CHECK_EQ(field.GetDeclaringClass(), klass);
1896 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001897 const PointerSize pointer_size = isc.pointer_size_;
1898 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001899 isc.SanityCheckArtMethod(&m, klass);
1900 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001901 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001902 if (vtable != nullptr) {
1903 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1904 }
1905 if (klass->ShouldHaveImt()) {
1906 ImTable* imt = klass->GetImt(pointer_size);
1907 for (size_t i = 0; i < ImTable::kSize; ++i) {
1908 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1909 }
1910 }
1911 if (klass->ShouldHaveEmbeddedVTable()) {
1912 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1913 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1914 }
1915 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001916 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001917 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1918 if (iftable->GetMethodArrayCount(i) > 0) {
1919 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1920 }
1921 }
1922 }
1923 };
1924 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001925 }
1926
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001927 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1928 ClassLinker* class_linker,
1929 mirror::MethodDexCacheType* arr,
1930 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001931 REQUIRES_SHARED(Locks::mutator_lock_) {
1932 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001933 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001934 }
1935
Andreas Gampe0793bec2016-12-01 11:37:33 -08001936 private:
1937 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1938 : spaces_(heap->GetBootImageSpaces()),
1939 pointer_size_(class_linker->GetImagePointerSize()) {
1940 space_begin_.reserve(spaces_.size());
1941 method_sections_.reserve(spaces_.size());
1942 runtime_method_sections_.reserve(spaces_.size());
1943 for (gc::space::ImageSpace* space : spaces_) {
1944 space_begin_.push_back(space->Begin());
1945 auto& header = space->GetImageHeader();
1946 method_sections_.push_back(&header.GetMethodsSection());
1947 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1948 }
1949 }
1950
1951 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1952 REQUIRES_SHARED(Locks::mutator_lock_) {
1953 if (m->IsRuntimeMethod()) {
1954 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1955 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1956 } else if (m->IsCopied()) {
1957 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1958 } else if (expected_class != nullptr) {
1959 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1960 }
1961 if (!spaces_.empty()) {
1962 bool contains = false;
1963 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1964 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1965 contains = method_sections_[i]->Contains(offset) ||
1966 runtime_method_sections_[i]->Contains(offset);
1967 }
1968 CHECK(contains) << m << " not found";
1969 }
1970 }
1971
1972 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1973 ObjPtr<mirror::Class> expected_class)
1974 REQUIRES_SHARED(Locks::mutator_lock_) {
1975 CHECK(arr != nullptr);
1976 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1977 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1978 // expected_class == null means we are a dex cache.
1979 if (expected_class != nullptr) {
1980 CHECK(method != nullptr);
1981 }
1982 if (method != nullptr) {
1983 SanityCheckArtMethod(method, expected_class);
1984 }
1985 }
1986 }
1987
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001988 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001989 REQUIRES_SHARED(Locks::mutator_lock_) {
1990 CHECK_EQ(arr != nullptr, size != 0u);
1991 if (arr != nullptr) {
1992 bool contains = false;
1993 for (auto space : spaces_) {
1994 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001995 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001996 contains = true;
1997 break;
1998 }
1999 }
2000 CHECK(contains);
2001 }
2002 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002003 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
2004 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08002005 // expected_class == null means we are a dex cache.
2006 if (method != nullptr) {
2007 SanityCheckArtMethod(method, nullptr);
2008 }
2009 }
2010 }
2011
2012 const std::vector<gc::space::ImageSpace*>& spaces_;
2013 const PointerSize pointer_size_;
2014
2015 // Cached sections from the spaces.
2016 std::vector<const uint8_t*> space_begin_;
2017 std::vector<const ImageSection*> method_sections_;
2018 std::vector<const ImageSection*> runtime_method_sections_;
2019};
2020
Andreas Gampebe7af222017-07-25 09:57:28 -07002021static void VerifyAppImage(const ImageHeader& header,
2022 const Handle<mirror::ClassLoader>& class_loader,
2023 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
2024 ClassTable* class_table, gc::space::ImageSpace* space)
2025 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002026 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2027 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
2028 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2029 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
2030 << mirror::Class::PrettyClass(klass);
2031 }
2032 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07002033 {
2034 // Verify that all direct interfaces of classes in the class table are also resolved.
2035 std::vector<ObjPtr<mirror::Class>> classes;
2036 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
2037 REQUIRES_SHARED(Locks::mutator_lock_) {
2038 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
2039 classes.push_back(klass);
2040 }
2041 return true;
2042 };
2043 class_table->Visit(verify_direct_interfaces_in_table);
2044 Thread* self = Thread::Current();
2045 for (ObjPtr<mirror::Class> klass : classes) {
2046 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
2047 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
2048 << klass->PrettyDescriptor() << " iface #" << i;
2049 }
2050 }
2051 }
2052 // Check that all non-primitive classes in dex caches are also in the class table.
Alex Lighta9bbc082019-11-14 14:51:41 -08002053 for (auto dex_cache : dex_caches.ConstIterate<mirror::DexCache>()) {
Andreas Gampebe7af222017-07-25 09:57:28 -07002054 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
2055 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
2056 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
2057 if (klass != nullptr && !klass->IsPrimitive()) {
2058 CHECK(class_table->Contains(klass))
2059 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
2060 }
2061 }
2062 }
2063}
2064
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002065bool ClassLinker::AddImageSpace(
2066 gc::space::ImageSpace* space,
2067 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002068 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
2069 std::string* error_msg) {
2070 DCHECK(out_dex_files != nullptr);
2071 DCHECK(error_msg != nullptr);
2072 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002073 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002074 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002075 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002076 DCHECK(dex_caches_object != nullptr);
2077 Runtime* const runtime = Runtime::Current();
2078 gc::Heap* const heap = runtime->GetHeap();
2079 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002080 // Check that the image is what we are expecting.
2081 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
2082 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
2083 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
2084 image_pointer_size_);
2085 return false;
2086 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002087 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
2088 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
2089 *error_msg = StringPrintf("Expected %zu image roots but got %d",
2090 expected_image_roots,
2091 header.GetImageRoots()->GetLength());
2092 return false;
2093 }
2094 StackHandleScope<3> hs(self);
2095 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
2096 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2097 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2098 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002099 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002100 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2101 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002102 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002103 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002104 *error_msg = StringPrintf("Expected %d class roots but got %d",
2105 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002106 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002107 return false;
2108 }
2109 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002110 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2111 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2112 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002113 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2114 return false;
2115 }
2116 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002117 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002118 if (oat_file->GetOatHeader().GetDexFileCount() !=
2119 static_cast<uint32_t>(dex_caches->GetLength())) {
2120 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2121 "image";
2122 return false;
2123 }
2124
Alex Lighta9bbc082019-11-14 14:51:41 -08002125 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00002126 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002127 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2128 dex_file_location.c_str(),
2129 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002130 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002131 return false;
2132 }
2133
2134 if (app_image) {
2135 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2136 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002137 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002138 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002139 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002140 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002141 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002142 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002143 }
2144 }
2145 } else {
2146 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002147 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2148 this,
2149 dex_cache->GetResolvedMethods(),
2150 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002151 }
2152 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002153 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002154 }
2155 out_dex_files->push_back(std::move(dex_file));
2156 }
2157
2158 if (app_image) {
2159 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002160 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002161 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2162 *error_msg = "Unexpected BootClassLoader in app image";
2163 return false;
2164 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002165 }
2166
2167 if (kSanityCheckObjects) {
Alex Lighta9bbc082019-11-14 14:51:41 -08002168 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002169 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2170 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2171 if (field != nullptr) {
2172 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2173 }
2174 }
2175 }
2176 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002177 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002178 }
2179 }
2180
2181 // Set entry point to interpreter if in InterpretOnly mode.
2182 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002183 // Set image methods' entry point to interpreter.
2184 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2185 if (!method.IsRuntimeMethod()) {
2186 DCHECK(method.GetDeclaringClass() != nullptr);
2187 if (!method.IsNative() && !method.IsResolutionMethod()) {
2188 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2189 image_pointer_size_);
2190 }
2191 }
2192 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002193 }
2194
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002195 if (interpreter::CanRuntimeUseNterp()) {
2196 // Set image methods' entry point that point to the interpreter bridge to the nterp entry point.
2197 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2198 if (IsQuickToInterpreterBridge(method.GetEntryPointFromQuickCompiledCode()) &&
2199 interpreter::CanMethodUseNterp(&method)) {
2200 method.SetEntryPointFromQuickCompiledCodePtrSize(interpreter::GetNterpEntryPoint(),
2201 image_pointer_size_);
2202 }
2203 }, space->Begin(), image_pointer_size_);
2204 }
2205
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00002206 if (runtime->IsVerificationSoftFail()) {
2207 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2208 if (!method.IsNative() && method.IsInvokable()) {
2209 method.ClearSkipAccessChecks();
2210 }
2211 }, space->Begin(), image_pointer_size_);
2212 }
2213
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002214 ClassTable* class_table = nullptr;
2215 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002216 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002217 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002218 }
2219 // If we have a class table section, read it and use it for verification in
2220 // UpdateAppImageClassLoadersAndDexCaches.
2221 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002222 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002223 const bool added_class_table = class_table_section.Size() > 0u;
2224 if (added_class_table) {
2225 const uint64_t start_time2 = NanoTime();
2226 size_t read_count = 0;
2227 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2228 /*make copy*/false,
2229 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002230 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002231 }
2232 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002233 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002234
2235 {
2236 ScopedTrace trace("AppImage:UpdateClassLoaders");
2237 // Update class loader and resolved strings. If added_class_table is false, the resolved
2238 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002239 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002240 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002241 // Note: We probably don't need the read barrier unless we copy the app image objects into
2242 // the region space.
2243 ObjPtr<mirror::Class> klass(root.Read());
2244 // Do not update class loader for boot image classes where the app image
2245 // class loader is only the initiating loader but not the defining loader.
2246 // Avoid read barrier since we are comparing against null.
2247 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002248 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002249 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002250 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002251 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002252
Vladimir Marko305c38b2018-02-14 11:50:07 +00002253 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002254 // Every class in the app image has initially SubtypeCheckInfo in the
2255 // Uninitialized state.
2256 //
2257 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2258 // after class initialization is complete. The app image ClassStatus as-is
2259 // are almost all ClassStatus::Initialized, and being in the
2260 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2261 //
2262 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2263 //
2264 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002265 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002266 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2267 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002268 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002269 }
2270 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002271 }
2272 if (!oat_file->GetBssGcRoots().empty()) {
2273 // Insert oat file to class table for visiting .bss GC roots.
2274 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002275 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002276
Mathieu Chartier69731002016-03-02 16:08:31 -08002277 if (added_class_table) {
2278 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2279 class_table->AddClassSet(std::move(temp_set));
2280 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002281
Mathieu Chartier69731002016-03-02 16:08:31 -08002282 if (kIsDebugBuild && app_image) {
2283 // This verification needs to happen after the classes have been added to the class loader.
2284 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002285 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002286 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002287 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002288
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002289 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002290 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002291}
2292
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002293bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002294 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2295 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002296}
2297
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002298void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002299 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2300 // enabling tracing requires the mutator lock, there are no race conditions here.
2301 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002302 Thread* const self = Thread::Current();
2303 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002304 if (kUseReadBarrier) {
2305 // We do not track new roots for CC.
2306 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2307 kVisitRootFlagClearRootLog |
2308 kVisitRootFlagStartLoggingNewRoots |
2309 kVisitRootFlagStopLoggingNewRoots));
2310 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002311 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002312 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2313 // There is 3 GC cases to handle:
2314 // Non moving concurrent:
2315 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002316 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002317 //
2318 // Moving non-concurrent:
2319 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2320 // To prevent missing roots, this case needs to ensure that there is no
2321 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2322 // class which is in the class table.
2323 //
2324 // Moving concurrent:
2325 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2326 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002327 //
2328 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2329 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2330 // these objects.
2331 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002332 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002333 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002334 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002335 for (const ClassLoaderData& data : class_loaders_) {
2336 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2337 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2338 }
2339 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002340 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002341 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002342 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002343 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002344 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002345 // Concurrent moving GC marked new roots through the to-space invariant.
2346 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002347 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002348 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2349 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2350 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2351 if (old_ref != nullptr) {
2352 DCHECK(old_ref->IsClass());
2353 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2354 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2355 // Concurrent moving GC marked new roots through the to-space invariant.
2356 CHECK_EQ(new_ref, old_ref);
2357 }
2358 }
2359 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002360 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002361 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002362 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002363 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002364 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002365 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002366 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002367 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002368 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002369 }
2370 // We deliberately ignore the class roots in the image since we
2371 // handle image roots by using the MS/CMS rescanning of dirty cards.
2372}
2373
Brian Carlstroma663ea52011-08-19 23:33:41 -07002374// Keep in sync with InitCallback. Anything we visit, we need to
2375// reinit references to when reinitializing a ClassLinker from a
2376// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002377void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002378 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002379 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002380 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2381 // unloading if we are marking roots.
2382 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002383}
2384
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002385class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2386 public:
2387 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2388 : visitor_(visitor),
2389 done_(false) {}
2390
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002391 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002392 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002393 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002394 if (!done_ && class_table != nullptr) {
2395 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2396 if (!class_table->Visit(visitor)) {
2397 // If the visitor ClassTable returns false it means that we don't need to continue.
2398 done_ = true;
2399 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002400 }
2401 }
2402
2403 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002404 // Class visitor that limits the class visits from a ClassTable to the classes with
2405 // the provided defining class loader. This filter is used to avoid multiple visits
2406 // of the same class which can be recorded for multiple initiating class loaders.
2407 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2408 public:
2409 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2410 ClassVisitor* visitor)
2411 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2412
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002413 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002414 if (klass->GetClassLoader() != defining_class_loader_) {
2415 return true;
2416 }
2417 return (*visitor_)(klass);
2418 }
2419
Vladimir Marko0984e482019-03-27 16:41:41 +00002420 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002421 ClassVisitor* const visitor_;
2422 };
2423
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002424 ClassVisitor* const visitor_;
2425 // If done is true then we don't need to do any more visiting.
2426 bool done_;
2427};
2428
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002429void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002430 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002431 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2432 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002433 }
2434}
2435
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002436void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002437 Thread* const self = Thread::Current();
2438 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2439 // Not safe to have thread suspension when we are holding a lock.
2440 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002441 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002442 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002443 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002444 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002445 }
2446}
2447
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002448class GetClassesInToVector : public ClassVisitor {
2449 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002450 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002451 classes_.push_back(klass);
2452 return true;
2453 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002454 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002455};
2456
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002457class GetClassInToObjectArray : public ClassVisitor {
2458 public:
2459 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2460 : arr_(arr), index_(0) {}
2461
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002462 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002463 ++index_;
2464 if (index_ <= arr_->GetLength()) {
2465 arr_->Set(index_ - 1, klass);
2466 return true;
2467 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002468 return false;
2469 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002470
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002471 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002472 return index_ <= arr_->GetLength();
2473 }
2474
2475 private:
2476 mirror::ObjectArray<mirror::Class>* const arr_;
2477 int32_t index_;
2478};
2479
2480void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002481 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2482 // is avoiding duplicates.
2483 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002484 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002485 GetClassesInToVector accumulator;
2486 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002487 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002488 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002489 return;
2490 }
2491 }
2492 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002493 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002494 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002495 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002496 // We size the array assuming classes won't be added to the class table during the visit.
2497 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002498 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002499 size_t class_table_size;
2500 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002501 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002502 // Add 100 in case new classes get loaded when we are filling in the object array.
2503 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002504 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002505 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002506 classes.Assign(
2507 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002508 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002509 GetClassInToObjectArray accumulator(classes.Get());
2510 VisitClasses(&accumulator);
2511 if (accumulator.Succeeded()) {
2512 break;
2513 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002514 }
2515 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2516 // If the class table shrank during creation of the clases array we expect null elements. If
2517 // the class table grew then the loop repeats. If classes are created after the loop has
2518 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002519 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002520 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002521 return;
2522 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002523 }
2524 }
2525}
2526
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002527ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002528 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002529 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002530 // CHA unloading analysis is not needed. No negative consequences are expected because
2531 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002532 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002533 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002534 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002535 while (!running_visibly_initialized_callbacks_.empty()) {
2536 std::unique_ptr<VisiblyInitializedCallback> callback(
2537 std::addressof(running_visibly_initialized_callbacks_.front()));
2538 running_visibly_initialized_callbacks_.pop_front();
2539 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002540}
2541
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002542void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002543 Runtime* const runtime = Runtime::Current();
2544 JavaVMExt* const vm = runtime->GetJavaVM();
2545 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002546 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002547 if (runtime->GetJit() != nullptr) {
2548 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2549 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002550 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002551 code_cache->RemoveMethodsIn(self, *data.allocator);
2552 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002553 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002554 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002555 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002556 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002557 // Cleanup references to single implementation ArtMethods that will be deleted.
2558 if (cleanup_cha) {
2559 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2560 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2561 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002562 {
2563 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2564 auto end = critical_native_code_with_clinit_check_.end();
2565 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2566 if (data.allocator->ContainsUnsafe(it->first)) {
2567 it = critical_native_code_with_clinit_check_.erase(it);
2568 } else {
2569 ++it;
2570 }
2571 }
2572 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002573
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002574 delete data.allocator;
2575 delete data.class_table;
2576}
2577
Vladimir Markobcf17522018-06-01 13:14:32 +01002578ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2579 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002580 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002581 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2582 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002583}
2584
Vladimir Markobcf17522018-06-01 13:14:32 +01002585ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2586 Thread* self,
2587 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002588 StackHandleScope<1> hs(self);
2589 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002590 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002591 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002592 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002593 self->AssertPendingOOMException();
2594 return nullptr;
2595 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002596 // Use InternWeak() so that the location String can be collected when the ClassLoader
2597 // with this DexCache is collected.
2598 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002599 if (location == nullptr) {
2600 self->AssertPendingOOMException();
2601 return nullptr;
2602 }
2603 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002604 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002605}
2606
Vladimir Markobcf17522018-06-01 13:14:32 +01002607ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2608 const DexFile& dex_file,
2609 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002610 ObjPtr<mirror::String> location = nullptr;
2611 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002612 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002613 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002614 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002615 mirror::DexCache::InitializeDexCache(self,
2616 dex_cache,
2617 location,
2618 &dex_file,
2619 linear_alloc,
2620 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002621 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002622 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002623}
2624
Vladimir Marko70e2a762019-07-12 16:49:00 +01002625template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002626ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2627 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002628 uint32_t class_size,
2629 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002630 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002631 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002632 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002633 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2634 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002635 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002636 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002637 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002638 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002639 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002640}
2641
Vladimir Marko70e2a762019-07-12 16:49:00 +01002642template <bool kMovable>
2643ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2644 ObjPtr<mirror::Class> java_lang_Class,
2645 uint32_t class_size) {
2646 mirror::Class::InitializeClassVisitor visitor(class_size);
2647 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2648}
2649
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002650ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002651 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002652}
2653
Vladimir Marko70e2a762019-07-12 16:49:00 +01002654void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2655 ClassRoot primitive_root,
2656 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002657 // We make this class non-movable for the unlikely case where it were to be
2658 // moved by a sticky-bit (minor) collection when using the Generational
2659 // Concurrent Copying (CC) collector, potentially creating a stale reference
2660 // in the `klass_` field of one of its instances allocated in the Large-Object
2661 // Space (LOS) -- see the comment about the dirty card scanning logic in
2662 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002663 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2664 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2665 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2666 DCHECK(component_type->IsPrimitive());
2667 array_class->SetComponentType(component_type);
2668 SetClassRoot(array_root, array_class);
2669}
2670
2671void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2672 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2673 array_class->SetSuperClass(java_lang_Object);
2674 array_class->SetVTable(java_lang_Object->GetVTable());
2675 array_class->SetPrimitiveType(Primitive::kPrimNot);
2676 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2677 array_class->SetClassFlags(component_type->IsPrimitive()
2678 ? mirror::kClassFlagNoReferenceFields
2679 : mirror::kClassFlagObjectArray);
2680 array_class->SetClassLoader(component_type->GetClassLoader());
2681 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2682 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2683 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2684 array_class->SetImt(object_imt, image_pointer_size_);
2685 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2686 // the kAccVerificationAttempted flag is added below, and there are no
2687 // methods that need the kAccSkipAccessChecks flag.
2688 DCHECK_EQ(array_class->NumMethods(), 0u);
2689
2690 // don't need to set new_class->SetObjectSize(..)
2691 // because Object::SizeOf delegates to Array::SizeOf
2692
2693 // All arrays have java/lang/Cloneable and java/io/Serializable as
2694 // interfaces. We need to set that up here, so that stuff like
2695 // "instanceof" works right.
2696
2697 // Use the single, global copies of "interfaces" and "iftable"
2698 // (remember not to free them for arrays).
2699 {
2700 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2701 CHECK(array_iftable != nullptr);
2702 array_class->SetIfTable(array_iftable);
2703 }
2704
2705 // Inherit access flags from the component type.
2706 int access_flags = component_type->GetAccessFlags();
2707 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2708 access_flags &= kAccJavaFlagsMask;
2709 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2710 // and remove "interface".
2711 access_flags |= kAccAbstract | kAccFinal;
2712 access_flags &= ~kAccInterface;
2713 // Arrays are access-checks-clean and preverified.
2714 access_flags |= kAccVerificationAttempted;
2715
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002716 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002717
Vladimir Markobf121912019-06-04 13:49:05 +01002718 // Array classes are fully initialized either during single threaded startup,
2719 // or from a pre-fence visitor, so visibly initialized.
2720 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002721}
2722
2723void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2724 // Do not hold lock on the array class object, the initialization of
2725 // core array classes is done while the process is still single threaded.
2726 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2727 FinishArrayClassSetup(array_class);
2728
2729 std::string temp;
2730 const char* descriptor = array_class->GetDescriptor(&temp);
2731 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2732 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2733 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002734}
2735
Vladimir Markobcf17522018-06-01 13:14:32 +01002736ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002737 Thread* self,
2738 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002739 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002740 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002741}
2742
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002743ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2744 const char* descriptor,
2745 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002746 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002747 if (kIsDebugBuild) {
2748 StackHandleScope<1> hs(self);
2749 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2750 Thread::PoisonObjectPointersIfDebug();
2751 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002752
2753 // For temporary classes we must wait for them to be retired.
2754 if (init_done_ && klass->IsTemp()) {
2755 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002756 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002757 ThrowEarlierClassFailure(klass);
2758 return nullptr;
2759 }
2760 StackHandleScope<1> hs(self);
2761 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2762 ObjectLock<mirror::Class> lock(self, h_class);
2763 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002764 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002765 lock.WaitIgnoringInterrupts();
2766 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002767 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002768 ThrowEarlierClassFailure(h_class.Get());
2769 return nullptr;
2770 }
2771 CHECK(h_class->IsRetired());
2772 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002773 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002774 }
2775
Brian Carlstromaded5f72011-10-07 17:15:04 -07002776 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002777 size_t index = 0;
2778 // Maximum number of yield iterations until we start sleeping.
2779 static const size_t kNumYieldIterations = 1000;
2780 // How long each sleep is in us.
2781 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002782 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002783 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002784 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002785 {
2786 ObjectTryLock<mirror::Class> lock(self, h_class);
2787 // Can not use a monitor wait here since it may block when returning and deadlock if another
2788 // thread has locked klass.
2789 if (lock.Acquired()) {
2790 // Check for circular dependencies between classes, the lock is required for SetStatus.
2791 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2792 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002793 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002794 return nullptr;
2795 }
2796 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002797 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002798 {
2799 // Handle wrapper deals with klass moving.
2800 ScopedThreadSuspension sts(self, kSuspended);
2801 if (index < kNumYieldIterations) {
2802 sched_yield();
2803 } else {
2804 usleep(kSleepDurationUS);
2805 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002806 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002807 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002808 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002809
Vladimir Marko72ab6842017-01-20 19:32:50 +00002810 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002811 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002812 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002813 }
2814 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002815 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002816 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002817 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002818}
2819
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002820using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002821
2822// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002823ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002824 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002825 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002826 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002827 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002828 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002829 return ClassPathEntry(dex_file, dex_class_def);
2830 }
2831 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002832 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002833}
2834
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002835bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2836 Thread* self,
2837 const char* descriptor,
2838 size_t hash,
2839 Handle<mirror::ClassLoader> class_loader,
2840 /*out*/ ObjPtr<mirror::Class>* result) {
2841 ArtField* field =
2842 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2843 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2844 if (raw_shared_libraries == nullptr) {
2845 return true;
2846 }
2847
2848 StackHandleScope<2> hs(self);
2849 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2850 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2851 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002852 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2853 temp_loader.Assign(loader);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002854 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2855 return false; // One of the shared libraries is not supported.
2856 }
2857 if (*result != nullptr) {
2858 return true; // Found the class up the chain.
2859 }
2860 }
2861 return true;
2862}
2863
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002864bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2865 Thread* self,
2866 const char* descriptor,
2867 size_t hash,
2868 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002869 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002870 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002871 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002872 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002873 return true;
2874 }
2875
David Brazdil05909d82018-12-06 16:25:16 +00002876 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002877 // For regular path or dex class loader the search order is:
2878 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002879 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002880 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002881
Calin Juravlecdd49122017-07-05 20:09:53 -07002882 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2883 StackHandleScope<1> hs(self);
2884 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2885 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2886 return false; // One of the parents is not supported.
2887 }
2888 if (*result != nullptr) {
2889 return true; // Found the class up the chain.
2890 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002891
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002892 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2893 return false; // One of the shared library loader is not supported.
2894 }
2895 if (*result != nullptr) {
2896 return true; // Found the class in a shared library.
2897 }
2898
Calin Juravlecdd49122017-07-05 20:09:53 -07002899 // Search the current class loader classpath.
2900 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002901 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002902 }
2903
Calin Juravlecdd49122017-07-05 20:09:53 -07002904 if (IsDelegateLastClassLoader(soa, class_loader)) {
2905 // For delegate last, the search order is:
2906 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002907 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002908 // - class loader dex files
2909 // - parent
2910 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2911 if (*result != nullptr) {
2912 return true; // The class is part of the boot class path.
2913 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002914 if (self->IsExceptionPending()) {
2915 // Pending exception means there was an error other than ClassNotFound that must be returned
2916 // to the caller.
2917 return false;
2918 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002919
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002920 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2921 return false; // One of the shared library loader is not supported.
2922 }
2923 if (*result != nullptr) {
2924 return true; // Found the class in a shared library.
2925 }
2926
Calin Juravlecdd49122017-07-05 20:09:53 -07002927 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2928 if (*result != nullptr) {
2929 return true; // Found the class in the current class loader
2930 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002931 if (self->IsExceptionPending()) {
2932 // Pending exception means there was an error other than ClassNotFound that must be returned
2933 // to the caller.
2934 return false;
2935 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002936
2937 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2938 StackHandleScope<1> hs(self);
2939 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2940 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2941 }
2942
2943 // Unsupported class loader.
2944 *result = nullptr;
2945 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002946}
2947
Andreas Gampe501c3b02019-04-17 21:54:27 +00002948namespace {
2949
2950// Matches exceptions caught in DexFile.defineClass.
2951ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2952 ClassLinker* class_linker)
2953 REQUIRES_SHARED(Locks::mutator_lock_) {
2954 return
2955 // ClassNotFoundException.
2956 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2957 class_linker))
2958 ||
2959 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2960 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2961}
2962
2963// Clear exceptions caught in DexFile.defineClass.
2964ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2965 REQUIRES_SHARED(Locks::mutator_lock_) {
2966 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2967 self->ClearException();
2968 }
2969}
2970
2971} // namespace
2972
Calin Juravle415dc3d2017-06-28 11:03:12 -07002973// Finds the class in the boot class loader.
2974// If the class is found the method returns the resolved class. Otherwise it returns null.
2975ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2976 const char* descriptor,
2977 size_t hash) {
2978 ObjPtr<mirror::Class> result = nullptr;
2979 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2980 if (pair.second != nullptr) {
2981 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2982 if (klass != nullptr) {
2983 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002984 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002985 result = DefineClass(self,
2986 descriptor,
2987 hash,
2988 ScopedNullHandle<mirror::ClassLoader>(),
2989 *pair.first,
2990 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002991 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002992 if (result == nullptr) {
2993 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002994 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002995 }
2996 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002997 return result;
2998}
Andreas Gampef865ea92015-04-13 22:14:19 -07002999
Calin Juravle415dc3d2017-06-28 11:03:12 -07003000ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
3001 ScopedObjectAccessAlreadyRunnable& soa,
3002 const char* descriptor,
3003 size_t hash,
3004 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00003005 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
3006 IsInMemoryDexClassLoader(soa, class_loader) ||
3007 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07003008 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07003009
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003010 ObjPtr<mirror::Class> ret;
3011 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003012 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003013 if (dex_class_def != nullptr) {
3014 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
3015 descriptor,
3016 hash,
3017 class_loader,
3018 *cp_dex_file,
3019 *dex_class_def);
3020 if (klass == nullptr) {
3021 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003022 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003023 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00003024 } else {
3025 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003026 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003027 ret = klass;
3028 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003029 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003030 return true; // Continue with the next DexFile.
3031 };
3032
3033 VisitClassLoaderDexFiles(soa, class_loader, define_class);
3034 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003035}
3036
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003037ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
3038 const char* descriptor,
3039 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08003040 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08003041 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003042 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07003043 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003044 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003045 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
3046 // for primitive classes that aren't backed by dex files.
3047 return FindPrimitiveClass(descriptor[0]);
3048 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003049 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003050 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003051 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07003052 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003053 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003054 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003055 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003056 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003057 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003058 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07003059 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003060 return DefineClass(self,
3061 descriptor,
3062 hash,
3063 ScopedNullHandle<mirror::ClassLoader>(),
3064 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07003065 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07003066 } else {
3067 // The boot class loader is searched ahead of the application class loader, failures are
3068 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
3069 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003070 ObjPtr<mirror::Throwable> pre_allocated =
3071 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003072 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07003073 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05003074 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003075 }
3076 ObjPtr<mirror::Class> result_ptr;
3077 bool descriptor_equals;
3078 if (descriptor[0] == '[') {
3079 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
3080 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
3081 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
3082 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05003083 } else {
Ian Rogers98379392014-02-24 16:53:16 -08003084 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003085 bool known_hierarchy =
3086 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
3087 if (result_ptr != nullptr) {
3088 // The chain was understood and we found the class. We still need to add the class to
3089 // the class table to protect from racy programs that can try and redefine the path list
3090 // which would change the Class<?> returned for subsequent evaluation of const-class.
3091 DCHECK(known_hierarchy);
3092 DCHECK(result_ptr->DescriptorEquals(descriptor));
3093 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003094 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003095 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00003096 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
3097 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003098 //
3099 // If the chain was understood but we did not find the class, let the Java-side
3100 // rediscover all this and throw the exception with the right stack trace. Note that
3101 // the Java-side could still succeed for racy programs if another thread is actively
3102 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07003103
Alex Light185a4612018-10-04 15:54:25 -07003104 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07003105 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00003106 // Oops, we can't call into java so we can't run actual class-loader code.
3107 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003108 ObjPtr<mirror::Throwable> pre_allocated =
3109 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3110 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003111 return nullptr;
3112 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003113
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003114 // Inlined DescriptorToDot(descriptor) with extra validation.
3115 //
3116 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
3117 // the DescriptorEquals() check below and give a confusing error message. For example,
3118 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
3119 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
3120 // "class loader [...] returned class java.lang.String instead of java.lang.String".
3121 size_t descriptor_length = strlen(descriptor);
3122 if (UNLIKELY(descriptor[0] != 'L') ||
3123 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
3124 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
3125 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
3126 return nullptr;
3127 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003128
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003129 std::string class_name_string(descriptor + 1, descriptor_length - 2);
3130 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00003131 if (known_hierarchy &&
3132 fast_class_not_found_exceptions_ &&
3133 !Runtime::Current()->IsJavaDebuggable()) {
3134 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
3135 // debuggable, optimize this path by throwing directly here without going back to Java
3136 // language. This reduces how many ClassNotFoundExceptions happen.
3137 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
3138 "%s",
3139 class_name_string.c_str());
3140 } else {
3141 ScopedLocalRef<jobject> class_loader_object(
3142 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
3143 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
3144 {
3145 ScopedThreadStateChange tsc(self, kNative);
3146 ScopedLocalRef<jobject> class_name_object(
3147 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
3148 if (class_name_object.get() == nullptr) {
3149 DCHECK(self->IsExceptionPending()); // OOME.
3150 return nullptr;
3151 }
3152 CHECK(class_loader_object.get() != nullptr);
3153 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
3154 WellKnownClasses::java_lang_ClassLoader_loadClass,
3155 class_name_object.get()));
3156 }
3157 if (result.get() == nullptr && !self->IsExceptionPending()) {
3158 // broken loader - throw NPE to be compatible with Dalvik
3159 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
3160 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003161 return nullptr;
3162 }
Andreas Gampe87658f32019-04-18 18:39:02 +00003163 result_ptr = soa.Decode<mirror::Class>(result.get());
3164 // Check the name of the returned class.
3165 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003166 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003167 } else {
3168 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003169 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003170 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003171
3172 if (self->IsExceptionPending()) {
3173 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3174 // However, to comply with the RI behavior, first check if another thread succeeded.
3175 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3176 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3177 self->ClearException();
3178 return EnsureResolved(self, descriptor, result_ptr);
3179 }
3180 return nullptr;
3181 }
3182
3183 // Try to insert the class to the class table, checking for mismatch.
3184 ObjPtr<mirror::Class> old;
3185 {
3186 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3187 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3188 old = class_table->Lookup(descriptor, hash);
3189 if (old == nullptr) {
3190 old = result_ptr; // For the comparison below, after releasing the lock.
3191 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003192 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003193 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003194 } // else throw below, after releasing the lock.
3195 }
3196 }
3197 if (UNLIKELY(old != result_ptr)) {
3198 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3199 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003200 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003201 const char* loader_class_name =
3202 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3203 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3204 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3205 << DescriptorToDot(descriptor) << "\").";
3206 return EnsureResolved(self, descriptor, old);
3207 }
3208 if (UNLIKELY(!descriptor_equals)) {
3209 std::string result_storage;
3210 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3211 std::string loader_storage;
3212 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3213 ThrowNoClassDefFoundError(
3214 "Initiating class loader of type %s returned class %s instead of %s.",
3215 DescriptorToDot(loader_class_name).c_str(),
3216 DescriptorToDot(result_name).c_str(),
3217 DescriptorToDot(descriptor).c_str());
3218 return nullptr;
3219 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003220 // Success.
3221 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003222}
3223
Alex Light270db1c2019-12-03 12:20:01 +00003224// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3225// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3226// like pausing class definition.
3227struct ScopedDefiningClass {
3228 public:
3229 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3230 : self_(self), returned_(false) {
3231 Locks::mutator_lock_->AssertSharedHeld(self_);
3232 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3233 self_->IncrDefineClassCount();
3234 }
3235 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3236 Locks::mutator_lock_->AssertSharedHeld(self_);
3237 CHECK(returned_);
3238 }
3239
3240 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3241 REQUIRES_SHARED(Locks::mutator_lock_) {
3242 CHECK(!returned_);
3243 self_->DecrDefineClassCount();
3244 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3245 Thread::PoisonObjectPointersIfDebug();
3246 returned_ = true;
3247 return h_klass.Get();
3248 }
3249
3250 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3251 REQUIRES_SHARED(Locks::mutator_lock_) {
3252 StackHandleScope<1> hs(self_);
3253 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3254 return Finish(h_klass);
3255 }
3256
3257 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3258 REQUIRES_SHARED(Locks::mutator_lock_) {
3259 ScopedNullHandle<mirror::Class> snh;
3260 return Finish(snh);
3261 }
3262
3263 private:
3264 Thread* self_;
3265 bool returned_;
3266};
3267
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003268ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3269 const char* descriptor,
3270 size_t hash,
3271 Handle<mirror::ClassLoader> class_loader,
3272 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003273 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003274 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003275 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003276 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003277
Brian Carlstromaded5f72011-10-07 17:15:04 -07003278 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003279 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003280 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003281 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003282 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003283 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003284 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003285 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003286 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003287 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003288 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003289 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003290 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003291 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003292 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003293 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003294 }
3295
Vladimir Markob9c29f62019-03-20 14:22:51 +00003296 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3297 // some runtime modules. Prevent definition of classes in app class loader that could clash
3298 // with these modules as these classes could be resolved differently during execution.
3299 if (class_loader != nullptr &&
3300 Runtime::Current()->IsAotCompiler() &&
Vladimir Markod1f73512020-04-02 10:50:35 +01003301 IsUpdatableBootClassPathDescriptor(descriptor)) {
Vladimir Markob9c29f62019-03-20 14:22:51 +00003302 ObjPtr<mirror::Throwable> pre_allocated =
3303 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3304 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003305 return sdc.Finish(nullptr);
Vladimir Markob9c29f62019-03-20 14:22:51 +00003306 }
3307
Alex Lighte9f61032018-09-24 16:04:51 -07003308 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3309 // code to be executed. We put it up here so we can avoid all the allocations associated with
3310 // creating the class. This can happen with (eg) jit threads.
3311 if (!self->CanLoadClasses()) {
3312 // Make sure we don't try to load anything, potentially causing an infinite loop.
3313 ObjPtr<mirror::Throwable> pre_allocated =
3314 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3315 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003316 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003317 }
3318
Andreas Gampefa4333d2017-02-14 11:10:34 -08003319 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003320 // Allocate a class with the status of not ready.
3321 // Interface object should get the right size here. Regular class will
3322 // figure out the right size later and be replaced with one of the right
3323 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003324 if (CanAllocClass()) {
3325 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3326 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003327 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003328 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003329 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003330 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003331 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003332 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003333 }
Alex Lightb0f11922017-01-23 14:25:17 -08003334 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3335 // nothing.
3336 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003337 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003338 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3339 // will only be called once.
3340 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3341 klass,
3342 class_loader,
3343 dex_file,
3344 dex_class_def,
3345 &new_dex_file,
3346 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003347 // Check to see if an exception happened during runtime callbacks. Return if so.
3348 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003349 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003350 }
Alex Lightb0f11922017-01-23 14:25:17 -08003351 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003352 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003353 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003354 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003355 }
3356 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003357 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003358
Jeff Hao848f70a2014-01-15 13:49:50 -08003359 // Mark the string class by setting its access flag.
3360 if (UNLIKELY(!init_done_)) {
3361 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3362 klass->SetStringClass();
3363 }
3364 }
3365
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003366 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003367 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003368 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003369 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003370
Mathieu Chartier590fee92013-09-13 13:46:47 -07003371 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003372 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003373 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003374 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3375 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003376 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003377 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003378
Mathieu Chartierc7853442015-03-27 14:35:38 -07003379 // Load the fields and other things after we are inserted in the table. This is so that we don't
3380 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3381 // other reason is that the field roots are only visited from the class table. So we need to be
3382 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003383 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003384 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003385 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003386 // An exception occured during load, set status to erroneous while holding klass' lock in case
3387 // notification is necessary.
3388 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003389 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003390 }
Alex Light270db1c2019-12-03 12:20:01 +00003391 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003392 }
3393
Brian Carlstromaded5f72011-10-07 17:15:04 -07003394 // Finish loading (if necessary) by finding parents
3395 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003396 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003397 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003398 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003399 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003400 }
Alex Light270db1c2019-12-03 12:20:01 +00003401 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003402 }
3403 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003404
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003405 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003406 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003407 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003408
Brian Carlstromaded5f72011-10-07 17:15:04 -07003409 // Link the class (if necessary)
3410 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003411 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003412 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003413
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003414 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003415 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003416 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003417 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003418 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003419 }
Alex Light270db1c2019-12-03 12:20:01 +00003420 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003421 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003422 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003423 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003424 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003425
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003426 // Instrumentation may have updated entrypoints for all methods of all
3427 // classes. However it could not update methods of this class while we
3428 // were loading it. Now the class is resolved, we can update entrypoints
3429 // as required by instrumentation.
3430 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3431 // We must be in the kRunnable state to prevent instrumentation from
3432 // suspending all threads to update entrypoints while we are doing it
3433 // for this class.
3434 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003435 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003436 }
3437
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003438 /*
3439 * We send CLASS_PREPARE events to the debugger from here. The
3440 * definition of "preparation" is creating the static fields for a
3441 * class and initializing them to the standard default values, but not
3442 * executing any code (that comes later, during "initialization").
3443 *
3444 * We did the static preparation in LinkClass.
3445 *
3446 * The class has been prepared and resolved but possibly not yet verified
3447 * at this point.
3448 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003449 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003450
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003451 // Notify native debugger of the new class and its layout.
3452 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3453
Alex Light270db1c2019-12-03 12:20:01 +00003454 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003455}
3456
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003457uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003458 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003459 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003460 size_t num_8 = 0;
3461 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003462 size_t num_32 = 0;
3463 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003464 ClassAccessor accessor(dex_file, dex_class_def);
3465 // We allow duplicate definitions of the same field in a class_data_item
3466 // but ignore the repeated indexes here, b/21868015.
3467 uint32_t last_field_idx = dex::kDexNoIndex;
3468 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3469 uint32_t field_idx = field.GetIndex();
3470 // Ordering enforced by DexFileVerifier.
3471 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3472 if (UNLIKELY(field_idx == last_field_idx)) {
3473 continue;
3474 }
3475 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003476 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003477 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3478 char c = descriptor[0];
3479 switch (c) {
3480 case 'L':
3481 case '[':
3482 num_ref++;
3483 break;
3484 case 'J':
3485 case 'D':
3486 num_64++;
3487 break;
3488 case 'I':
3489 case 'F':
3490 num_32++;
3491 break;
3492 case 'S':
3493 case 'C':
3494 num_16++;
3495 break;
3496 case 'B':
3497 case 'Z':
3498 num_8++;
3499 break;
3500 default:
3501 LOG(FATAL) << "Unknown descriptor: " << c;
3502 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003503 }
3504 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003505 return mirror::Class::ComputeClassSize(false,
3506 0,
3507 num_8,
3508 num_16,
3509 num_32,
3510 num_64,
3511 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003512 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003513}
3514
Alex Lightfc49fec2018-01-16 22:28:36 +00003515// Special case to get oat code without overwriting a trampoline.
3516const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003517 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003518 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003519 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003520 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003521 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003522 if (code != nullptr) {
3523 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003524 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003525
3526 jit::Jit* jit = Runtime::Current()->GetJit();
3527 if (jit != nullptr) {
3528 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3529 if (code != nullptr) {
3530 return code;
3531 }
3532 }
3533
Alex Lightfc49fec2018-01-16 22:28:36 +00003534 if (method->IsNative()) {
3535 // No code and native? Use generic trampoline.
3536 return GetQuickGenericJniStub();
3537 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003538
3539 if (interpreter::CanRuntimeUseNterp() && interpreter::CanMethodUseNterp(method)) {
3540 return interpreter::GetNterpEntryPoint();
3541 }
3542
Alex Lightfc49fec2018-01-16 22:28:36 +00003543 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003544}
3545
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003546bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003547 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003548 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3549 return false;
3550 }
3551
Elliott Hughes956af0f2014-12-11 14:34:28 -08003552 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003553 return true;
3554 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003555
3556 Runtime* runtime = Runtime::Current();
3557 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3558 if (instr->InterpretOnly()) {
3559 return true;
3560 }
3561
3562 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3563 // Doing this check avoids doing compiled/interpreter transitions.
3564 return true;
3565 }
3566
Alex Lightfc588092020-01-23 15:39:08 -08003567 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003568 // Force the use of interpreter when it is required by the debugger.
3569 return true;
3570 }
3571
Alex Light8f34aba2017-10-09 13:46:32 -07003572 if (Thread::Current()->IsAsyncExceptionPending()) {
3573 // Force use of interpreter to handle async-exceptions
3574 return true;
3575 }
3576
Alex Light2d441b12018-06-08 15:33:21 -07003577 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3578 const void* instr_target = instr->GetCodeForInvoke(method);
3579 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3580 return ShouldUseInterpreterEntrypoint(method, instr_target);
3581 }
3582
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003583 if (runtime->IsJavaDebuggable()) {
3584 // For simplicity, we ignore precompiled code and go to the interpreter
3585 // assuming we don't already have jitted code.
3586 // We could look at the oat file where `quick_code` is being defined,
3587 // and check whether it's been compiled debuggable, but we decided to
3588 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003589 jit::Jit* jit = Runtime::Current()->GetJit();
3590 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3591 }
3592
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003593 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003594 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003595 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003596 // since we want to JIT it (at first use) with extra stackmaps for native
3597 // debugging. We keep however all AOT code from the boot image,
3598 // since the JIT-at-first-use is blocking and would result in non-negligible
3599 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003600 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003601 }
3602
3603 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003604}
3605
Vladimir Marko86c87522020-05-11 16:55:55 +01003606void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003607 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003608 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003609 size_t num_direct_methods = klass->NumDirectMethods();
3610 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003611 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003612 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003613 if (UNLIKELY(klass->IsProxyClass())) {
3614 return;
3615 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003616 PointerSize pointer_size = image_pointer_size_;
3617 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3618 klass->GetDirectMethods(pointer_size).end(),
3619 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3620 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3621 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3622 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3623 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3624 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3625 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3626 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3627 lb->first->SetEntryPointFromJni(lb->second);
3628 lb = critical_native_code_with_clinit_check_.erase(lb);
3629 }
3630 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003631 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003632 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003633 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003634 return; // OAT file unavailable.
3635 }
Ian Rogers19846512012-02-24 11:42:47 -08003636 }
Alex Light64ad14d2014-08-19 14:23:13 -07003637
Mathieu Chartierf8322842014-05-16 10:59:25 -07003638 const DexFile& dex_file = klass->GetDexFile();
Ian Rogers97b52f82014-08-14 11:34:07 -07003639 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003640 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3641 klass->GetDexClassDefIndex(),
3642 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003643 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003644 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3645 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003646 if (!method->IsStatic()) {
3647 // Only update static methods.
3648 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003649 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003650 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003651
3652 // In order:
3653 // 1) Check if we have AOT Code.
3654 // 2) Check if we have JIT Code.
3655 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003656 if (has_oat_class) {
3657 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003658 quick_code = oat_method.GetQuickCode();
3659 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003660
Vladimir Markocce414f2019-10-07 08:51:33 +01003661 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003662 if (quick_code == nullptr && jit != nullptr) {
3663 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003664 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003665
3666 if (quick_code == nullptr &&
3667 interpreter::CanRuntimeUseNterp() &&
3668 interpreter::CanMethodUseNterp(method)) {
3669 quick_code = interpreter::GetNterpEntryPoint();
3670 }
3671
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003672 // Check whether the method is native, in which case it's generic JNI.
3673 if (quick_code == nullptr && method->IsNative()) {
3674 quick_code = GetQuickGenericJniStub();
3675 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003676 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003677 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3678 // If we have the trampoline or the bridge already, no need to update.
3679 // This saves in not dirtying boot image memory.
3680 continue;
3681 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003682 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003683 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003684 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003685 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003686 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003687 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003688}
3689
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003690// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3691// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003692inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3693 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003694 DCHECK(method != nullptr);
3695 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003696 method->SetEntryPointFromQuickCompiledCodePtrSize(
3697 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3698 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003699}
3700
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003701static void LinkCode(ClassLinker* class_linker,
3702 ArtMethod* method,
3703 const OatFile::OatClass* oat_class,
3704 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003705 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003706 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003707 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003708 // The following code only applies to a non-compiler runtime.
3709 return;
3710 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003711
Ian Rogers62d6c772013-02-27 08:32:07 -08003712 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003713 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003714
Alex Light9139e002015-10-09 15:59:48 -07003715 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003716 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003717 return;
3718 }
Ian Rogers19846512012-02-24 11:42:47 -08003719
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003720 const void* quick_code = nullptr;
3721 if (oat_class != nullptr) {
3722 // Every kind of method should at least get an invoke stub from the oat_method.
3723 // non-abstract methods also get their code pointers.
3724 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3725 quick_code = oat_method.GetQuickCode();
3726 }
3727
3728 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3729
3730 // Note: this mimics the logic in image_writer.cc that installs the resolution
3731 // stub only if we have compiled code and the method needs a class initialization
3732 // check.
3733 if (quick_code == nullptr) {
3734 method->SetEntryPointFromQuickCompiledCode(
3735 method->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge());
3736 } else if (enter_interpreter) {
3737 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003738 } else if (NeedsClinitCheckBeforeCall(method)) {
3739 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3740 // If we do have code but the method needs a class initialization check before calling
3741 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003742 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3743 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003744 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003745 } else {
3746 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003747 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003748
Ian Rogers62d6c772013-02-27 08:32:07 -08003749 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003750 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3751 // as the extra processing for @CriticalNative is not needed yet.
3752 method->SetEntryPointFromJni(
3753 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Andreas Gampe90546832014-03-12 18:07:19 -07003754
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003755 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003756 // We have a native method here without code. Then it should have the generic JNI
3757 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003758 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003759 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003760 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003761 }
3762}
3763
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003764void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003765 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003766 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003767 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003768 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003769 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003770 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003771 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003772 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003773
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003774 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003775 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003776 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003777 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003778 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003779 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003780 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003781
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003782 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003783 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003784}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003785
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003786LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3787 LinearAlloc* allocator,
3788 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003789 if (length == 0) {
3790 return nullptr;
3791 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003792 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3793 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3794 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003795 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003796 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003797 CHECK(ret != nullptr);
3798 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3799 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003800}
3801
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003802LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3803 LinearAlloc* allocator,
3804 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003805 if (length == 0) {
3806 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003807 }
Vladimir Marko14632852015-08-17 12:07:23 +01003808 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3809 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003810 const size_t storage_size =
3811 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003812 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003813 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003814 CHECK(ret != nullptr);
3815 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003816 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003817 }
3818 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003819}
3820
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003821LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003822 if (class_loader == nullptr) {
3823 return Runtime::Current()->GetLinearAlloc();
3824 }
3825 LinearAlloc* allocator = class_loader->GetAllocator();
3826 DCHECK(allocator != nullptr);
3827 return allocator;
3828}
3829
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003830LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003831 if (class_loader == nullptr) {
3832 return Runtime::Current()->GetLinearAlloc();
3833 }
3834 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3835 LinearAlloc* allocator = class_loader->GetAllocator();
3836 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003837 RegisterClassLoader(class_loader);
3838 allocator = class_loader->GetAllocator();
3839 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003840 }
3841 return allocator;
3842}
3843
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003844void ClassLinker::LoadClass(Thread* self,
3845 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003846 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003847 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003848 ClassAccessor accessor(dex_file,
3849 dex_class_def,
3850 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003851 if (!accessor.HasClassData()) {
3852 return;
3853 }
3854 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003855 {
3856 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3857 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003858 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003859 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003860 // We allow duplicate definitions of the same field in a class_data_item
3861 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003862 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003863 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3864 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003865 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003866 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3867 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003868 accessor.NumInstanceFields());
3869 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003870 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003871 uint32_t last_static_field_idx = 0u;
3872 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003873
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003874 // Methods
3875 bool has_oat_class = false;
3876 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3877 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3878 : OatFile::OatClass::Invalid();
3879 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3880 klass->SetMethodsPtr(
3881 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3882 accessor.NumDirectMethods(),
3883 accessor.NumVirtualMethods());
3884 size_t class_def_method_index = 0;
3885 uint32_t last_dex_method_index = dex::kDexNoIndex;
3886 size_t last_class_def_method_index = 0;
3887
3888 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3889 // methods needs to decode all of the fields.
3890 accessor.VisitFieldsAndMethods([&](
3891 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3892 uint32_t field_idx = field.GetIndex();
3893 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3894 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3895 LoadField(field, klass, &sfields->At(num_sfields));
3896 ++num_sfields;
3897 last_static_field_idx = field_idx;
3898 }
3899 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3900 uint32_t field_idx = field.GetIndex();
3901 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3902 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3903 LoadField(field, klass, &ifields->At(num_ifields));
3904 ++num_ifields;
3905 last_instance_field_idx = field_idx;
3906 }
3907 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3908 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3909 image_pointer_size_);
3910 LoadMethod(dex_file, method, klass, art_method);
3911 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3912 uint32_t it_method_index = method.GetIndex();
3913 if (last_dex_method_index == it_method_index) {
3914 // duplicate case
3915 art_method->SetMethodIndex(last_class_def_method_index);
3916 } else {
3917 art_method->SetMethodIndex(class_def_method_index);
3918 last_dex_method_index = it_method_index;
3919 last_class_def_method_index = class_def_method_index;
3920 }
3921 ++class_def_method_index;
3922 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3923 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3924 class_def_method_index - accessor.NumDirectMethods(),
3925 image_pointer_size_);
3926 LoadMethod(dex_file, method, klass, art_method);
3927 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3928 ++class_def_method_index;
3929 });
3930
3931 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003932 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003933 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3934 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3935 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003936 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3937 if (sfields != nullptr) {
3938 sfields->SetSize(num_sfields);
3939 }
3940 if (ifields != nullptr) {
3941 ifields->SetSize(num_ifields);
3942 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003943 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003944 // Set the field arrays.
3945 klass->SetSFieldsPtr(sfields);
3946 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003947 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003948 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003949 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003950 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003951 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003952 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003953}
3954
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003955void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003956 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003957 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003958 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003959 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003960 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003961
David Brazdil85865692018-10-30 17:26:20 +00003962 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3963 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003964}
3965
Mathieu Chartier268764d2016-09-13 12:09:38 -07003966void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003967 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003968 Handle<mirror::Class> klass,
3969 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003970 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003971 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003972 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003973
Mathieu Chartier268764d2016-09-13 12:09:38 -07003974 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003975 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003976 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003977 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003978
David Brazdil85865692018-10-30 17:26:20 +00003979 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3980 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003981
Ian Rogersdfb325e2013-10-30 01:00:44 -07003982 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003983 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003984 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3985 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003986 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003987 klass->SetFinalizable();
3988 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003989 std::string temp;
3990 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003991 // The Enum class declares a "final" finalize() method to prevent subclasses from
3992 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3993 // subclasses, so we exclude it here.
3994 // We also want to avoid setting the flag on Object, where we know that finalize() is
3995 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003996 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3997 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003998 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003999 }
4000 }
4001 }
4002 } else if (method_name[0] == '<') {
4003 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004004 bool is_init = (strcmp("<init>", method_name) == 0);
4005 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07004006 if (UNLIKELY(!is_init && !is_clinit)) {
4007 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
4008 } else {
4009 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
4010 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07004011 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07004012 access_flags |= kAccConstructor;
4013 }
4014 }
4015 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01004016 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
4017 // Check if the native method is annotated with @FastNative or @CriticalNative.
4018 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
4019 dex_file, dst->GetClassDef(), dex_method_idx);
4020 }
Ian Rogers241b5de2013-10-09 17:58:57 -07004021 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00004022 // Must be done after SetAccessFlags since IsAbstract depends on it.
4023 if (klass->IsInterface() && dst->IsAbstract()) {
4024 dst->CalculateAndSetImtIndex();
4025 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07004026}
4027
Mathieu Chartier0a19e212019-11-27 14:35:24 -08004028void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004029 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004030 self,
Mathieu Chartier0a19e212019-11-27 14:35:24 -08004031 *dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004032 Runtime::Current()->GetLinearAlloc());
Mathieu Chartier0a19e212019-11-27 14:35:24 -08004033 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07004034 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07004035}
4036
Mathieu Chartier0a19e212019-11-27 14:35:24 -08004037void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004038 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08004039 CHECK(dex_file != nullptr);
4040 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
4041 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07004042 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08004043 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004044}
4045
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004046void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004047 ObjPtr<mirror::DexCache> dex_cache,
4048 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004049 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08004050 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00004051 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004052 // For app images, the dex cache location may be a suffix of the dex file location since the
4053 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08004054 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
4055 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004056 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
4057 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00004058 // The following paths checks don't work on preopt when using boot dex files, where the dex
4059 // cache location is the one on device, and the dex_file's location is the one on host.
4060 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
4061 CHECK_GE(dex_file_location.length(), dex_cache_length)
4062 << dex_cache_location << " " << dex_file.GetLocation();
4063 const std::string dex_file_suffix = dex_file_location.substr(
4064 dex_file_location.length() - dex_cache_length,
4065 dex_cache_length);
4066 // Example dex_cache location is SettingsProvider.apk and
4067 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
4068 CHECK_EQ(dex_cache_location, dex_file_suffix);
4069 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004070 const OatFile* oat_file =
4071 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00004072 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
4073 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
4074 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
4075 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08004076 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004077 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
4078 DexCacheData data = *it;
4079 if (self->IsJWeakCleared(data.weak_root)) {
4080 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004081 it = dex_caches_.erase(it);
4082 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00004083 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004084 it->dex_file->GetOatDexFile() != nullptr &&
4085 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00004086 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004087 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004088 ++it;
4089 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004090 }
Vladimir Markob066d432018-01-03 13:14:37 +00004091 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00004092 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004093 }
David Brazdila5c3a802019-03-08 14:59:41 +00004094 // Let hiddenapi assign a domain to the newly registered dex file.
4095 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
4096
Vladimir Markocd556b02017-02-03 11:47:34 +00004097 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004098 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004099 DexCacheData data;
4100 data.weak_root = dex_cache_jweak;
4101 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00004102 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00004103 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00004104 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004105 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
4106 // path dex caches without an image.
4107 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08004108 // Make sure that the dex cache holds the classloader live.
4109 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004110 if (class_loader != nullptr) {
4111 // Since we added a strong root to the class table, do the write barrier as required for
4112 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004113 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004114 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004115 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004116}
4117
Alex Light725da8f2020-02-19 14:46:33 -08004118ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
4119 return data != nullptr
4120 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00004121 : nullptr;
4122}
4123
Alex Light725da8f2020-02-19 14:46:33 -08004124bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00004125 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08004126 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00004127 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08004128 CHECK(data != nullptr);
4129 DCHECK_EQ(dex_cache->GetDexFile(), data->dex_file);
4130 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00004131}
4132
Alex Light07f06212017-06-01 14:01:43 -07004133void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
4134 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004135 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07004136 Thread* self = Thread::Current();
4137 StackHandleScope<2> hs(self);
4138 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
4139 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
4140 const DexFile* dex_file = dex_cache->GetDexFile();
4141 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
4142 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08004143 ReaderMutexLock mu(self, *Locks::dex_lock_);
4144 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
4145 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07004146 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
4147 << "been registered on dex file " << dex_file->GetLocation();
4148 }
4149 ClassTable* table;
4150 {
4151 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4152 table = InsertClassTableForClassLoader(h_class_loader.Get());
4153 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004154 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4155 // a thread holding the dex lock and blocking on a condition variable regarding
4156 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004157 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07004158 WriterMutexLock mu(self, *Locks::dex_lock_);
4159 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
4160 table->InsertStrongRoot(h_dex_cache.Get());
4161 if (h_class_loader.Get() != nullptr) {
4162 // Since we added a strong root to the class table, do the write barrier as required for
4163 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004164 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004165 }
4166}
4167
Alex Lightde7f8782020-02-24 10:14:22 -08004168static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
4169 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08004170 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08004171 "Attempt to register dex file %s with multiple class loaders",
4172 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08004173}
4174
Vladimir Markocd556b02017-02-03 11:47:34 +00004175ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4176 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004177 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08004178 ObjPtr<mirror::DexCache> old_dex_cache;
4179 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004180 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004181 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004182 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4183 old_dex_cache = DecodeDexCacheLocked(self, old_data);
4184 if (old_dex_cache != nullptr) {
4185 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
4186 return old_dex_cache;
4187 } else {
4188 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
4189 // be thrown when it's safe to do so to simplify this.
4190 registered_with_another_class_loader = true;
4191 }
4192 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004193 }
Alex Light725da8f2020-02-19 14:46:33 -08004194 // We need to have released the dex_lock_ to allocate safely.
4195 if (registered_with_another_class_loader) {
4196 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4197 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07004198 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004199 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004200 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4201 DCHECK(linear_alloc != nullptr);
4202 ClassTable* table;
4203 {
4204 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4205 table = InsertClassTableForClassLoader(class_loader);
4206 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004207 // Don't alloc while holding the lock, since allocation may need to
4208 // suspend all threads and another thread may need the dex_lock_ to
4209 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004210 StackHandleScope<3> hs(self);
4211 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004212 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07004213 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
4214 self,
4215 dex_file)));
4216 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004217 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004218 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4219 // a thread holding the dex lock and blocking on a condition variable regarding
4220 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004221 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004222 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004223 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4224 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004225 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004226 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
4227 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
4228 // that the arrays are null.
4229 mirror::DexCache::InitializeDexCache(self,
4230 h_dex_cache.Get(),
4231 h_location.Get(),
4232 &dex_file,
4233 linear_alloc,
4234 image_pointer_size_);
4235 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004236 }
Alex Light725da8f2020-02-19 14:46:33 -08004237 if (old_dex_cache != nullptr) {
4238 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4239 // If this thread encountered OOME, ignore it.
4240 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
4241 self->ClearException();
4242 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
4243 // dex_lock_.
4244 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
4245 return old_dex_cache;
4246 } else {
4247 registered_with_another_class_loader = true;
4248 }
4249 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004250 }
Alex Light725da8f2020-02-19 14:46:33 -08004251 if (registered_with_another_class_loader) {
4252 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4253 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004254 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004255 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004256 self->AssertPendingOOMException();
4257 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004258 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004259 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004260 if (h_class_loader.Get() != nullptr) {
4261 // Since we added a strong root to the class table, do the write barrier as required for
4262 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004263 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004264 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004265 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004266}
4267
Vladimir Markocd556b02017-02-03 11:47:34 +00004268bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004269 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004270 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004271}
4272
Vladimir Markocd556b02017-02-03 11:47:34 +00004273ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4274 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004275 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4276 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004277 if (dex_cache != nullptr) {
4278 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004279 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004280 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004281 for (const DexCacheData& data : dex_caches_) {
Alex Light725da8f2020-02-19 14:46:33 -08004282 if (DecodeDexCacheLocked(self, &data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004283 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004284 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004285 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004286 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
Alex Light725da8f2020-02-19 14:46:33 -08004287 << " " << &dex_file << " " << dex_cache_data->dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004288 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004289}
4290
Vladimir Markocd556b02017-02-03 11:47:34 +00004291ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4292 const DexFile* dex_file = dex_cache->GetDexFile();
4293 DCHECK(dex_file != nullptr);
4294 ReaderMutexLock mu(self, *Locks::dex_lock_);
4295 // Search assuming unique-ness of dex file.
4296 for (const DexCacheData& data : dex_caches_) {
4297 // Avoid decoding (and read barriers) other unrelated dex caches.
4298 if (data.dex_file == dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004299 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004300 if (registered_dex_cache != nullptr) {
4301 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4302 return data.class_table;
4303 }
4304 }
4305 }
4306 return nullptr;
4307}
4308
Alex Light725da8f2020-02-19 14:46:33 -08004309const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004310 // Search assuming unique-ness of dex file.
4311 for (const DexCacheData& data : dex_caches_) {
4312 // Avoid decoding (and read barriers) other unrelated dex caches.
4313 if (data.dex_file == &dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004314 return &data;
Vladimir Markocd556b02017-02-03 11:47:34 +00004315 }
4316 }
Alex Light725da8f2020-02-19 14:46:33 -08004317 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004318}
4319
Vladimir Marko70e2a762019-07-12 16:49:00 +01004320void ClassLinker::CreatePrimitiveClass(Thread* self,
4321 Primitive::Type type,
4322 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004323 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004324 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004325 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4326 // Do not hold lock on the primitive class object, the initialization of
4327 // primitive classes is done while the process is still single threaded.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004328 primitive_class->SetAccessFlagsDuringLinking(
Vladimir Marko70e2a762019-07-12 16:49:00 +01004329 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4330 primitive_class->SetPrimitiveType(type);
4331 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4332 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4333 // the kAccVerificationAttempted flag was added above, and there are no
4334 // methods that need the kAccSkipAccessChecks flag.
4335 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004336 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4337 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004338 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004339 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004340 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004341 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004342 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004343 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004344}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004345
Vladimir Marko02610552018-06-04 14:38:00 +01004346inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4347 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4348}
4349
Brian Carlstrombe977852011-07-19 14:54:54 -07004350// Create an array class (i.e. the class object for the array, not the
4351// array itself). "descriptor" looks like "[C" or "[[[[B" or
4352// "[Ljava/lang/String;".
4353//
4354// If "descriptor" refers to an array of primitives, look up the
4355// primitive type's internally-generated class object.
4356//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004357// "class_loader" is the class loader of the class that's referring to
4358// us. It's used to ensure that we're looking for the element type in
4359// the right context. It does NOT become the class loader for the
4360// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004361//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004362// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004363ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4364 const char* descriptor,
4365 size_t hash,
4366 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004367 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004368 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004369 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004370
4371 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4372 // code to be executed. We put it up here so we can avoid all the allocations associated with
4373 // creating the class. This can happen with (eg) jit threads.
4374 if (!self->CanLoadClasses()) {
4375 // Make sure we don't try to load anything, potentially causing an infinite loop.
4376 ObjPtr<mirror::Throwable> pre_allocated =
4377 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4378 self->SetException(pre_allocated);
4379 return nullptr;
4380 }
4381
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004382 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4383 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004384 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004385 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004386 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004387 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4388 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004389 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004390 DCHECK(self->IsExceptionPending());
4391 return nullptr;
4392 } else {
4393 self->ClearException();
4394 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004395 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004396 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4397 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4398 return nullptr;
4399 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004400 // See if the component type is already loaded. Array classes are
4401 // always associated with the class loader of their underlying
4402 // element type -- an array of Strings goes with the loader for
4403 // java/lang/String -- so we need to look for it there. (The
4404 // caller should have checked for the existence of the class
4405 // before calling here, but they did so with *their* class loader,
4406 // not the component type's loader.)
4407 //
4408 // If we find it, the caller adds "loader" to the class' initiating
4409 // loader list, which should prevent us from going through this again.
4410 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004411 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004412 // are the same, because our caller (FindClass) just did the
4413 // lookup. (Even if we get this wrong we still have correct behavior,
4414 // because we effectively do this lookup again when we add the new
4415 // class to the hash table --- necessary because of possible races with
4416 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004417 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004418 ObjPtr<mirror::Class> new_class =
4419 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004420 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004421 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004422 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004423 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004424 // Core array classes, i.e. Object[], Class[], String[] and primitive
4425 // arrays, have special initialization and they should be found above.
4426 DCHECK(!component_type->IsObjectClass() ||
4427 // Guard from false positives for errors before setting superclass.
4428 component_type->IsErroneousUnresolved());
4429 DCHECK(!component_type->IsStringClass());
4430 DCHECK(!component_type->IsClassClass());
4431 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004432
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004433 // Fill out the fields in the Class.
4434 //
4435 // It is possible to execute some methods against arrays, because
4436 // all arrays are subclasses of java_lang_Object_, so we need to set
4437 // up a vtable. We can just point at the one in java_lang_Object_.
4438 //
4439 // Array classes are simple enough that we don't need to do a full
4440 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004441 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4442 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4443 size_t usable_size)
4444 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004445 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004446 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4447 init_class(obj, usable_size);
4448 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4449 klass->SetComponentType(component_type.Get());
4450 // Do not hold lock for initialization, the fence issued after the visitor
4451 // returns ensures memory visibility together with the implicit consume
4452 // semantics (for all supported architectures) for any thread that loads
4453 // the array class reference from any memory locations afterwards.
4454 FinishArrayClassSetup(klass);
4455 };
4456 auto new_class = hs.NewHandle<mirror::Class>(
4457 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004458 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004459 self->AssertPendingOOMException();
4460 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004461 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004462
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004463 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004464 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004465 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4466 // duplicate events in case of races. Array classes don't really follow dedicated
4467 // load and prepare, anyways.
4468 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4469 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4470
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004471 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004472 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004473 }
4474 // Another thread must have loaded the class after we
4475 // started but before we finished. Abandon what we've
4476 // done.
4477 //
4478 // (Yes, this happens.)
4479
Vladimir Markobcf17522018-06-01 13:14:32 +01004480 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004481}
4482
Vladimir Marko9186b182018-11-06 14:55:54 +00004483ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4484 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004485 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004486 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4487 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4488 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4489 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4490 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4491 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4492 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4493 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4494 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004495 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004496 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004497 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004498 return GetClassRoot(class_root, this);
4499}
4500
4501ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4502 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4503 if (UNLIKELY(result == nullptr)) {
4504 std::string printable_type(PrintableChar(type));
4505 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4506 }
4507 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004508}
4509
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004510ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4511 ObjPtr<mirror::Class> klass,
4512 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004513 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004514 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004515 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004516 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004517 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004518 source += " from ";
4519 source += dex_cache->GetLocation()->ToModifiedUtf8();
4520 }
4521 LOG(INFO) << "Loaded class " << descriptor << source;
4522 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004523 {
4524 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004525 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004526 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004527 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004528 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004529 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004530 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004531 VerifyObject(klass);
4532 class_table->InsertWithHash(klass, hash);
4533 if (class_loader != nullptr) {
4534 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004535 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004536 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004537 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004538 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004539 }
4540 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004541 if (kIsDebugBuild) {
4542 // Test that copied methods correctly can find their holder.
4543 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4544 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4545 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004546 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004547 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004548}
4549
Vladimir Marko1998cd02017-01-13 13:02:58 +00004550void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004551 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4552 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4553 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4554 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004555 }
4556}
4557
Alex Lighte64300b2015-12-15 15:02:47 -08004558// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004559void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004560 LengthPrefixedArray<ArtMethod>* new_methods) {
4561 klass->SetMethodsPtrUnchecked(new_methods,
4562 klass->NumDirectMethods(),
4563 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004564 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004565 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004566}
4567
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004568ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4569 const char* descriptor,
4570 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004571 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4572}
4573
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004574ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4575 const char* descriptor,
4576 size_t hash,
4577 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004578 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4579 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4580 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004581 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004582 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004583 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004584 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004585 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004586 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004587}
4588
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004589class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4590 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004591 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004592
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004593 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004594 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004595 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004596 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004597 if (class_table != nullptr) {
4598 class_table->FreezeSnapshot();
4599 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004600 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004601};
4602
4603void ClassLinker::MoveClassTableToPreZygote() {
4604 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004605 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004606 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004607 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004608}
4609
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004610// Look up classes by hash and descriptor and put all matching ones in the result array.
4611class LookupClassesVisitor : public ClassLoaderVisitor {
4612 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004613 LookupClassesVisitor(const char* descriptor,
4614 size_t hash,
4615 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004616 : descriptor_(descriptor),
4617 hash_(hash),
4618 result_(result) {}
4619
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004620 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004621 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004622 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004623 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004624 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4625 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004626 result_->push_back(klass);
4627 }
4628 }
4629
4630 private:
4631 const char* const descriptor_;
4632 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004633 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004634};
4635
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004636void ClassLinker::LookupClasses(const char* descriptor,
4637 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004638 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004639 Thread* const self = Thread::Current();
4640 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004641 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004642 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004643 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004644 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004645 result.push_back(klass);
4646 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004647 LookupClassesVisitor visitor(descriptor, hash, &result);
4648 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004649}
4650
Alex Lightf1f10492015-10-07 16:08:36 -07004651bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4652 Handle<mirror::Class> klass,
4653 Handle<mirror::Class> supertype) {
4654 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004655 DCHECK(klass != nullptr);
4656 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004657
Alex Lightf1f10492015-10-07 16:08:36 -07004658 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4659 VerifyClass(self, supertype);
4660 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004661
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004662 if (supertype->IsVerified()
4663 || supertype->ShouldVerifyAtRuntime()
4664 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004665 // The supertype is either verified, or we soft failed at AOT time.
4666 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004667 return true;
4668 }
4669 // If we got this far then we have a hard failure.
4670 std::string error_msg =
4671 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004672 klass->PrettyDescriptor().c_str(),
4673 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004674 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004675 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004676 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004677 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004678 // Set during VerifyClass call (if at all).
4679 self->ClearException();
4680 }
4681 // Change into a verify error.
4682 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004683 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004684 self->GetException()->SetCause(cause.Get());
4685 }
4686 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4687 if (Runtime::Current()->IsAotCompiler()) {
4688 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4689 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004690 // Need to grab the lock to change status.
4691 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004692 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004693 return false;
4694}
4695
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004696verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004697 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004698 {
4699 // TODO: assert that the monitor on the Class is held
4700 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004701
Andreas Gampe884f3b82016-03-30 19:52:58 -07004702 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004703 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004704 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004705 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004706 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4707 // case we may see the same status again. b/62912904. This is why the check is
4708 // greater or equal.
4709 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004710 << "Class '" << klass->PrettyClass()
4711 << "' performed an illegal verification state transition from " << old_status
4712 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004713 old_status = klass->GetStatus();
4714 }
jeffhao98eacac2011-09-14 16:11:53 -07004715
Andreas Gampe884f3b82016-03-30 19:52:58 -07004716 // The class might already be erroneous, for example at compile time if we attempted to verify
4717 // this class as a parent to another.
4718 if (klass->IsErroneous()) {
4719 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004720 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004721 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004722
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004723 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004724 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004725 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004726 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004727 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004728
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004729 if (klass->IsVerifiedNeedsAccessChecks()) {
4730 if (!Runtime::Current()->IsAotCompiler()) {
4731 // Mark the class as having a verification attempt to avoid re-running
4732 // the verifier and avoid calling EnsureSkipAccessChecksMethods.
4733 klass->SetVerificationAttempted();
4734 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4735 }
4736 return verifier::FailureKind::kAccessChecksFailure;
4737 }
4738
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004739 // For AOT, don't attempt to re-verify if we have already found we should
4740 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004741 if (klass->ShouldVerifyAtRuntime()) {
4742 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004743 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004744 }
jeffhao98eacac2011-09-14 16:11:53 -07004745
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004746 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4747 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004748
4749 // Skip verification if disabled.
4750 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004751 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004752 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004753 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004754 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004755 }
4756
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004757 VLOG(class_linker) << "Beginning verification for class: "
4758 << klass->PrettyDescriptor()
4759 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4760
Ian Rogers9ffb0392012-09-10 11:56:50 -07004761 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004762 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004763 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4764 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004765 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004766 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004767 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004768 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004769
Alex Lightf1f10492015-10-07 16:08:36 -07004770 // Verify all default super-interfaces.
4771 //
4772 // (1) Don't bother if the superclass has already had a soft verification failure.
4773 //
4774 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4775 // recursive initialization by themselves. This is because when an interface is initialized
4776 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4777 // but choose not to for an optimization. If the interfaces is being verified due to a class
4778 // initialization (which would need all the default interfaces to be verified) the class code
4779 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004780 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004781 && !klass->IsInterface()) { // See (2)
4782 int32_t iftable_count = klass->GetIfTableCount();
4783 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4784 // Loop through all interfaces this class has defined. It doesn't matter the order.
4785 for (int32_t i = 0; i < iftable_count; i++) {
4786 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004787 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004788 // We only care if we have default interfaces and can skip if we are already verified...
4789 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4790 continue;
4791 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4792 // We had a hard failure while verifying this interface. Just return immediately.
4793 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004794 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004795 } else if (UNLIKELY(!iface->IsVerified())) {
4796 // We softly failed to verify the iface. Stop checking and clean up.
4797 // Put the iface into the supertype handle so we know what caused us to fail.
4798 supertype.Assign(iface.Get());
4799 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004800 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004801 }
4802 }
4803
Alex Lightf1f10492015-10-07 16:08:36 -07004804 // At this point if verification failed, then supertype is the "first" supertype that failed
4805 // verification (without a specific order). If verification succeeded, then supertype is either
4806 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004807 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004808 supertype.Get() == klass->GetSuperClass() ||
4809 !supertype->IsVerified());
4810
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004811 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004812 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004813 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004814 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004815
4816 VLOG(class_linker) << "Class preverified status for class "
4817 << klass->PrettyDescriptor()
4818 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4819 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004820 << preverified
4821 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004822
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004823 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4824 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004825 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4826 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004827
Ian Rogers62d6c772013-02-27 08:32:07 -08004828 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004829 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004830 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004831 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004832 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004833
4834 // Verification is done, grab the lock again.
4835 ObjectLock<mirror::Class> lock(self, klass);
4836
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004837 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4838 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004839 VLOG(class_linker) << "Soft verification failure in class "
4840 << klass->PrettyDescriptor()
4841 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4842 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004843 }
Ian Rogers1f539342012-10-03 21:09:42 -07004844 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004845 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004846 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004847 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004848 // Even though there were no verifier failures we need to respect whether the super-class and
4849 // super-default-interfaces were verified or requiring runtime reverification.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004850 if (supertype == nullptr
4851 || supertype->IsVerified()
4852 || supertype->IsVerifiedNeedsAccessChecks()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004853 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004854 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004855 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004856 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4857 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004858 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004859 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004860 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004861 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004862 CHECK(verifier_failure == verifier::FailureKind::kSoftFailure ||
4863 verifier_failure == verifier::FailureKind::kAccessChecksFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004864 // Soft failures at compile time should be retried at runtime. Soft
4865 // failures at runtime will be handled by slow paths in the generated
4866 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004867 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004868 if (verifier_failure == verifier::FailureKind::kSoftFailure) {
4869 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4870 } else {
4871 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4872 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004873 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004874 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004875 // As this is a fake verified status, make sure the methods are _not_ marked
4876 // kAccSkipAccessChecks later.
4877 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004878 }
4879 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004880 } else {
David Sehr709b0702016-10-13 09:12:37 -07004881 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004882 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4883 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004884 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004885 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004886 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004887 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004888 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004889 if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks ||
4890 UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
Igor Murashkindf707e42016-02-02 16:56:50 -08004891 // Never skip access checks if the verification soft fail is forced.
4892 // Mark the class as having a verification attempt to avoid re-running the verifier.
4893 klass->SetVerificationAttempted();
4894 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004895 // Class is verified so we don't need to do any access check on its methods.
4896 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
4897 // method.
4898 // Note: we're going here during compilation and at runtime. When we set the
4899 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
4900 // in the image and is set when loading the image.
Andreas Gampecc1b5352016-12-01 16:58:38 -08004901 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004902 }
Andreas Gampe48498592014-09-10 19:48:05 -07004903 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004904 // Done verifying. Notify the compiler about the verification status, in case the class
4905 // was verified implicitly (eg super class of a compiled class).
4906 if (Runtime::Current()->IsAotCompiler()) {
4907 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4908 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4909 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004910 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004911}
4912
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004913verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4914 Handle<mirror::Class> klass,
4915 verifier::HardFailLogMode log_level,
4916 std::string* error_msg) {
4917 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004918 return verifier::ClassVerifier::VerifyClass(self,
4919 klass.Get(),
4920 runtime->GetCompilerCallbacks(),
4921 runtime->IsAotCompiler(),
4922 log_level,
4923 Runtime::Current()->GetTargetSdkVersion(),
4924 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004925}
4926
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004927bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004928 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004929 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004930 // If we're compiling, we can only verify the class using the oat file if
4931 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004932 // the compilation unit (app - dependencies). We will let the compiler callback
4933 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004934 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004935 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004936 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004937 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004938 return false;
4939 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004940 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004941
Andreas Gampeb40d3612018-06-26 15:49:42 -07004942 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004943 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004944 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004945 return false;
4946 }
4947
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004948 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004949 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004950 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004951 return true;
4952 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004953 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4954 // We return that the clas has already been verified, and the caller should
4955 // check the class status to ensure we run with access checks.
4956 return true;
4957 }
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004958 // If we only verified a subset of the classes at compile time, we can end up with classes that
4959 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004960 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004961 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004962 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004963 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4964 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4965 << klass->PrettyClass() << " " << dex_file.GetLocation();
4966
Vladimir Marko72ab6842017-01-20 19:32:50 +00004967 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004968 // Compile time verification failed with a hard error. This is caused by invalid instructions
4969 // in the class. These errors are unrecoverable.
4970 return false;
4971 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004972 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004973 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4974 // not loading the class.
4975 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4976 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004977 return false;
4978 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004979 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004980 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004981 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004982 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004983 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004984}
4985
Alex Light5a559862016-01-29 12:24:48 -08004986void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004987 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004988 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004989 }
4990}
4991
Alex Light5a559862016-01-29 12:24:48 -08004992void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004993 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004994 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004995 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004996 return; // native or abstract method
4997 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004998 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004999 return; // nothing to process
5000 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005001 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005002 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005003 for (uint32_t idx = 0; idx < handlers_size; idx++) {
5004 CatchHandlerIterator iterator(handlers_ptr);
5005 for (; iterator.HasNext(); iterator.Next()) {
5006 // Ensure exception types are resolved so that they don't need resolution to be delivered,
5007 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08005008 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005009 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005010 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005011 DCHECK(Thread::Current()->IsExceptionPending());
5012 Thread::Current()->ClearException();
5013 }
5014 }
5015 }
5016 handlers_ptr = iterator.EndDataPointer();
5017 }
5018}
5019
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01005020ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
5021 jstring name,
5022 jobjectArray interfaces,
5023 jobject loader,
5024 jobjectArray methods,
5025 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005026 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07005027
5028 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
5029 // code to be executed. We put it up here so we can avoid all the allocations associated with
5030 // creating the class. This can happen with (eg) jit-threads.
5031 if (!self->CanLoadClasses()) {
5032 // Make sure we don't try to load anything, potentially causing an infinite loop.
5033 ObjPtr<mirror::Throwable> pre_allocated =
5034 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
5035 self->SetException(pre_allocated);
5036 return nullptr;
5037 }
5038
Alex Light133987d2020-03-26 19:22:12 +00005039 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005040 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005041 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005042 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005043 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005044 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005045 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005046 DCHECK(temp_klass->GetClass() != nullptr);
5047 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08005048 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
5049 // the methods.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00005050 temp_klass->SetAccessFlagsDuringLinking(
5051 kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005052 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
5053 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
5054 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005055 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08005056 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005057 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005058 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00005059 std::string storage;
5060 const char* descriptor = temp_klass->GetDescriptor(&storage);
5061 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005062
Mathieu Chartierd57d4542015-10-14 10:55:30 -07005063 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005064 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07005065
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005066 // Insert the class before loading the fields as the field roots
5067 // (ArtField::declaring_class_) are only visited from the class
5068 // table. There can't be any suspend points between inserting the
5069 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00005070 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005071 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08005072
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005073 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07005074 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07005075 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005076 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005077
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005078 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
5079 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005080 ArtField& interfaces_sfield = sfields->At(0);
5081 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005082 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005083 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005084
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005085 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005086 ArtField& throws_sfield = sfields->At(1);
5087 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005088 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005089 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04005090
Ian Rogers466bb252011-10-14 03:29:56 -07005091 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08005092 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04005093
Alex Light133987d2020-03-26 19:22:12 +00005094 // The array we get passed contains all methods, including private and static
5095 // ones that aren't proxied. We need to filter those out since only interface
5096 // methods (non-private & virtual) are actually proxied.
5097 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
5098 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01005099 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07005100 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00005101 // List of the actual virtual methods this class will have.
5102 std::vector<ArtMethod*> proxied_methods;
5103 std::vector<size_t> proxied_throws_idx;
5104 proxied_methods.reserve(h_methods->GetLength());
5105 proxied_throws_idx.reserve(h_methods->GetLength());
5106 // Filter out to only the non-private virtual methods.
5107 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
5108 ArtMethod* m = mirror->GetArtMethod();
5109 if (!m->IsPrivate() && !m->IsStatic()) {
5110 proxied_methods.push_back(m);
5111 proxied_throws_idx.push_back(idx);
5112 }
5113 }
5114 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07005115 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
5116 // contains an array of all the classes each function is declared to throw.
5117 // This is used to wrap unexpected exceptions in a
5118 // UndeclaredThrowableException exception. This array is in the same order as
5119 // the methods array and like the methods array must be filtered to remove any
5120 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00005121 const bool has_filtered_methods =
5122 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
5123 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
5124 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
5125 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
5126 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
5127 (has_filtered_methods)
5128 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
5129 self, original_proxied_throws->GetClass(), num_virtual_methods)
5130 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07005131 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
5132 self->AssertPendingOOMException();
5133 return nullptr;
5134 }
Alex Light133987d2020-03-26 19:22:12 +00005135 if (has_filtered_methods) {
5136 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
5137 DCHECK_LE(new_idx, orig_idx);
5138 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
5139 }
5140 }
Alex Lighte64300b2015-12-15 15:02:47 -08005141
5142 // Create the methods array.
5143 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
5144 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005145 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
5146 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08005147 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005148 self->AssertPendingOOMException();
5149 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005150 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005151 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005152
5153 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005154 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005155
5156 // Create virtual method using specified prototypes.
5157 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005158 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005159 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005160 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005161 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005162 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5163 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005164 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005165
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005166 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005167 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005168 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005169 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005170 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005171
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005172 // At this point the class is loaded. Publish a ClassLoad event.
5173 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5174 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5175
5176 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005177 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005178 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005179 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005180 // Link the fields and virtual methods, creating vtable and iftables.
5181 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005182 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005183 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005184 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005185 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005186 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005187 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005188 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005189 CHECK(temp_klass->IsRetired());
5190 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005191
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005192 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005193 interfaces_sfield.SetObject<false>(
5194 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005195 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005196 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5197 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005198 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00005199 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005200
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005201 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5202
Vladimir Marko305c38b2018-02-14 11:50:07 +00005203 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5204 // See also ClassLinker::EnsureInitialized().
5205 if (kBitstringSubtypeCheckEnabled) {
5206 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5207 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5208 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5209 }
5210
Vladimir Markobf121912019-06-04 13:49:05 +01005211 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005212 {
5213 // Lock on klass is released. Lock new class object.
5214 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005215 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005216 // Conservatively go through the ClassStatus::kInitialized state.
5217 callback = MarkClassInitialized(self, klass);
5218 }
5219 if (callback != nullptr) {
5220 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005221 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005222
5223 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07005224 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005225 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005226 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5227
Ian Rogersc2b44472011-12-14 21:17:17 -08005228 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005229 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005230 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08005231 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005232
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005233 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005234 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005235 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005236 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005237 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005238
5239 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005240 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005241 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005242
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005243 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005244 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005245 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005246 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005247 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005248 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005249}
5250
Mathieu Chartiere401d142015-04-22 13:56:20 -07005251void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5252 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005253 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5254 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005255
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005256 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5257 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005258 ArtMethod* proxy_constructor =
5259 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005260 DCHECK(proxy_constructor != nullptr)
5261 << "Could not find <init> method in java.lang.reflect.Proxy";
5262
Jeff Haodb8a6642014-08-14 17:18:52 -07005263 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5264 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005265 DCHECK(out != nullptr);
5266 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005267 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005268 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005269 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005270 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5271 kAccPublic |
5272 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005273 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005274
5275 // Set the original constructor method.
5276 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005277}
5278
Mathieu Chartiere401d142015-04-22 13:56:20 -07005279void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005280 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005281 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5282 CHECK_STREQ(np->GetName(), "<init>");
5283 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005284 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005285}
5286
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005287void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005288 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005289 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005290 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005291 DCHECK(out != nullptr);
5292 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005293
Alex Lighte9dd04f2016-03-16 16:09:45 -07005294 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005295 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005296 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5297 // preference to the invocation handler.
5298 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5299 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005300 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5301 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005302 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5303
5304 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5305 // method they copy might (if it's a default method).
5306 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005307
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005308 // Set the original interface method.
5309 out->SetDataPtrSize(prototype, image_pointer_size_);
5310
Ian Rogers466bb252011-10-14 03:29:56 -07005311 // At runtime the method looks like a reference and argument saving method, clone the code
5312 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005313 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005314}
Jesse Wilson95caa792011-10-12 18:14:17 -04005315
Mathieu Chartiere401d142015-04-22 13:56:20 -07005316void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005317 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005318 CHECK(!prototype->IsFinal());
5319 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005320 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005321
5322 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5323 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005324 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005325 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005326}
5327
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005328bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005329 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005330 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005331 return true;
5332 }
5333 if (!can_init_statics) {
5334 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005335 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005336 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005337 return false;
5338 }
5339 // Check if there are encoded static values needing initialization.
5340 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005341 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005342 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005343 if (dex_class_def->static_values_off_ != 0) {
5344 return false;
5345 }
5346 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005347 }
5348 // If we are a class we need to initialize all interfaces with default methods when we are
5349 // initialized. Check all of them.
5350 if (!klass->IsInterface()) {
5351 size_t num_interfaces = klass->GetIfTableCount();
5352 for (size_t i = 0; i < num_interfaces; i++) {
5353 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5354 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5355 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005356 return false;
5357 }
5358 }
5359 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005360 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005361 if (klass->IsInterface() || !klass->HasSuperClass()) {
5362 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005363 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005364 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005365 if (super_class->IsInitialized()) {
5366 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005367 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005368 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005369}
5370
Mathieu Chartier23369542020-03-04 08:24:11 -08005371bool ClassLinker::InitializeClass(Thread* self,
5372 Handle<mirror::Class> klass,
5373 bool can_init_statics,
5374 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005375 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5376
5377 // Are we already initialized and therefore done?
5378 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5379 // an initialized class will never change its state.
5380 if (klass->IsInitialized()) {
5381 return true;
5382 }
5383
5384 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005385 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005386 return false;
5387 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005388
Ian Rogers7b078e82014-09-10 14:44:24 -07005389 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005390 Runtime* const runtime = Runtime::Current();
5391 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005392 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005393 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005394 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005395
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005396 // Re-check under the lock in case another thread initialized ahead of us.
5397 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005398 return true;
5399 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005400
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005401 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005402 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005403 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005404 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005405 return false;
5406 }
5407
Vladimir Marko72ab6842017-01-20 19:32:50 +00005408 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5409 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005410
5411 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005412 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005413 if (!klass->IsVerified()) {
5414 // We failed to verify, expect either the klass to be erroneous or verification failed at
5415 // compile time.
5416 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005417 // The class is erroneous. This may be a verifier error, or another thread attempted
5418 // verification and/or initialization and failed. We can distinguish those cases by
5419 // whether an exception is already pending.
5420 if (self->IsExceptionPending()) {
5421 // Check that it's a VerifyError.
5422 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005423 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005424 } else {
5425 // Check that another thread attempted initialization.
5426 DCHECK_NE(0, klass->GetClinitThreadId());
5427 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5428 // Need to rethrow the previous failure now.
5429 ThrowEarlierClassFailure(klass.Get(), true);
5430 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005431 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005432 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005433 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005434 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005435 self->AssertNoPendingException();
5436 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005437 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005438 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005439 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005440 } else {
5441 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005442 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005443
5444 // A separate thread could have moved us all the way to initialized. A "simple" example
5445 // involves a subclass of the current class being initialized at the same time (which
5446 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005447 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005448 if (klass->IsInitialized()) {
5449 return true;
5450 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005451 }
5452
Vladimir Marko2c64a832018-01-04 11:31:56 +00005453 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005454 // initializing higher up the stack or another thread has beat us
5455 // to initializing and we need to wait. Either way, this
5456 // invocation of InitializeClass will not be responsible for
5457 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005458 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005459 // Could have got an exception during verification.
5460 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005461 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005462 return false;
5463 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005464 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005465 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005466 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005467 return true;
5468 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005469 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005470 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005471 }
5472
Jeff Haoe2e40342017-07-19 10:45:18 -07005473 // Try to get the oat class's status for this class if the oat file is present. The compiler
5474 // tries to validate superclass descriptors, and writes the result into the oat file.
5475 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5476 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5477 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005478 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005479 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5480 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5481 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005482 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005483 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005484 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005485 return false;
5486 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005487 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005488
Vladimir Marko2c64a832018-01-04 11:31:56 +00005489 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005490 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005491
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005492 // From here out other threads may observe that we're initializing and so changes of state
5493 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005494 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005495 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005496
Mathieu Chartier23369542020-03-04 08:24:11 -08005497 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005498 }
5499
Andreas Gampeaf864702019-07-23 14:05:35 -07005500 uint64_t t_sub = 0;
5501
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005502 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005503 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005504 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005505 if (!super_class->IsInitialized()) {
5506 CHECK(!super_class->IsInterface());
5507 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005508 StackHandleScope<1> hs(self);
5509 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005510 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005511 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005512 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005513 if (!super_initialized) {
5514 // The super class was verified ahead of entering initializing, we should only be here if
5515 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005516 // For the case of aot compiler, the super class might also be initializing but we don't
5517 // want to process circular dependencies in pre-compile.
5518 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005519 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005520 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005521 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005522 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005523 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005524 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005525 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005526 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005527 return false;
5528 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005529 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005530 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005531 }
5532
Alex Lighteb7c1442015-08-31 13:17:42 -07005533 if (!klass->IsInterface()) {
5534 // Initialize interfaces with default methods for the JLS.
5535 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005536 // Only setup the (expensive) handle scope if we actually need to.
5537 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005538 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005539 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5540 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005541 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005542 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005543 CHECK(handle_scope_iface->IsInterface());
5544 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5545 // We have already done this for this interface. Skip it.
5546 continue;
5547 }
5548 // We cannot just call initialize class directly because we need to ensure that ALL
5549 // interfaces with default methods are initialized. Non-default interface initialization
5550 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005551 // This is not very precise, misses all walking.
5552 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005553 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5554 handle_scope_iface,
5555 can_init_statics,
5556 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005557 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005558 if (!iface_initialized) {
5559 ObjectLock<mirror::Class> lock(self, klass);
5560 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005561 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005562 return false;
5563 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005564 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005565 }
5566 }
5567 }
5568
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005569 const size_t num_static_fields = klass->NumStaticFields();
5570 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005571 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005572 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005573 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005574 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005575 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005576
5577 // Eagerly fill in static fields so that the we don't have to do as many expensive
5578 // Class::FindStaticField in ResolveField.
5579 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005580 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005581 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005582 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005583 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005584 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005585 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5586 field,
5587 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5588 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005589 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005590 } else {
5591 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005592 }
5593 }
5594
Vladimir Markoe11dd502017-12-08 14:09:45 +00005595 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5596 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005597 this,
5598 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005599 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005600
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005601 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005602 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005603 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005604 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5605 if (!value_it.HasNext()) {
5606 break;
5607 }
5608 ArtField* art_field = ResolveField(field.GetIndex(),
5609 dex_cache,
5610 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005611 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005612 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005613 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005614 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005615 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005616 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005617 if (self->IsExceptionPending()) {
5618 break;
5619 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005620 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005621 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005622 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005623 }
5624 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005625
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005626
Mathieu Chartierda595be2016-08-10 13:57:39 -07005627 if (!self->IsExceptionPending()) {
5628 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5629 if (clinit != nullptr) {
5630 CHECK(can_init_statics);
5631 JValue result;
5632 clinit->Invoke(self, nullptr, 0, &result, "V");
5633 }
5634 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005635 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005636 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005637
Vladimir Markobf121912019-06-04 13:49:05 +01005638 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005639 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005640 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005641 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005642
5643 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005644 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005645 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005646 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005647 } else if (Runtime::Current()->IsTransactionAborted()) {
5648 // The exception thrown when the transaction aborted has been caught and cleared
5649 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005650 VLOG(compiler) << "Return from class initializer of "
5651 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005652 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005653 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005654 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005655 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005656 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005657 if (stats_enabled) {
5658 RuntimeStats* global_stats = runtime->GetStats();
5659 RuntimeStats* thread_stats = self->GetStats();
5660 ++global_stats->class_init_count;
5661 ++thread_stats->class_init_count;
5662 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5663 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5664 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005665 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005666 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005667 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005668 std::string temp;
5669 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005670 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005671 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005672 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005673 }
Vladimir Markobf121912019-06-04 13:49:05 +01005674 if (callback != nullptr) {
5675 callback->MakeVisible(self);
5676 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005677 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005678}
5679
Alex Lighteb7c1442015-08-31 13:17:42 -07005680// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5681// and perform the initialization only on those interfaces that contain default methods.
5682bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5683 Handle<mirror::Class> iface,
5684 bool can_init_statics,
5685 bool can_init_parents) {
5686 CHECK(iface->IsInterface());
5687 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005688 // Only create the (expensive) handle scope if we need it.
5689 if (UNLIKELY(num_direct_ifaces > 0)) {
5690 StackHandleScope<1> hs(self);
5691 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5692 // First we initialize all of iface's super-interfaces recursively.
5693 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005694 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005695 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005696 if (!super_iface->HasBeenRecursivelyInitialized()) {
5697 // Recursive step
5698 handle_super_iface.Assign(super_iface);
5699 if (!InitializeDefaultInterfaceRecursive(self,
5700 handle_super_iface,
5701 can_init_statics,
5702 can_init_parents)) {
5703 return false;
5704 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005705 }
5706 }
5707 }
5708
5709 bool result = true;
5710 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5711 // initialize if we don't have default methods.
5712 if (iface->HasDefaultMethods()) {
5713 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5714 }
5715
5716 // Mark that this interface has undergone recursive default interface initialization so we know we
5717 // can skip it on any later class initializations. We do this even if we are not a default
5718 // interface since we can still avoid the traversal. This is purely a performance optimization.
5719 if (result) {
5720 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005721 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5722 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5723 // initialization is a performance optimization (to avoid another idempotent visit
5724 // for other implementing classes/interfaces), and can be revisited later.
5725 ObjectTryLock<mirror::Class> lock(self, iface);
5726 if (lock.Acquired()) {
5727 iface->SetRecursivelyInitialized();
5728 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005729 }
5730 return result;
5731}
5732
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005733bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5734 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005735 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005736 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005737 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005738 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005739 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005740 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005741
5742 // When we wake up, repeat the test for init-in-progress. If
5743 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005744 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005745 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005746 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005747 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005748 return false;
5749 }
5750 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005751 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005752 continue;
5753 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005754 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005755 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005756 // Compile time initialization failed.
5757 return false;
5758 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005759 if (klass->IsErroneous()) {
5760 // The caller wants an exception, but it was thrown in a
5761 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005762 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005763 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005764 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005765 return false;
5766 }
5767 if (klass->IsInitialized()) {
5768 return true;
5769 }
David Sehr709b0702016-10-13 09:12:37 -07005770 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005771 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005772 }
Ian Rogers07140832014-09-30 15:43:59 -07005773 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005774}
5775
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005776static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5777 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005778 ArtMethod* method,
5779 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005780 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005781 DCHECK(Thread::Current()->IsExceptionPending());
5782 DCHECK(!m->IsProxyMethod());
5783 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005784 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5785 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005786 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005787 std::string return_type = dex_file->PrettyType(return_type_idx);
5788 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005789 ThrowWrappedLinkageError(klass.Get(),
5790 "While checking class %s method %s signature against %s %s: "
5791 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005792 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5793 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005794 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005795 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005796 return_type.c_str(), class_loader.c_str());
5797}
5798
5799static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5800 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005801 ArtMethod* method,
5802 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005803 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005804 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005805 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005806 DCHECK(Thread::Current()->IsExceptionPending());
5807 DCHECK(!m->IsProxyMethod());
5808 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005809 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5810 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005811 ThrowWrappedLinkageError(klass.Get(),
5812 "While checking class %s method %s signature against %s %s: "
5813 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005814 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5815 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005816 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005817 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005818 index, arg_type.c_str(), class_loader.c_str());
5819}
5820
5821static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5822 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005823 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005824 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005825 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005826 ThrowLinkageError(klass.Get(),
5827 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005828 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5829 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005830 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005831 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005832 error_msg.c_str());
5833}
5834
Ian Rogersb5fb2072014-12-02 17:22:02 -08005835static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005836 Handle<mirror::Class> klass,
5837 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005838 ArtMethod* method1,
5839 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005840 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005841 {
5842 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005843 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005844 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005845 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005846 return false;
5847 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005848 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005849 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005850 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005851 return false;
5852 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005853 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005854 ThrowSignatureMismatch(klass, super_klass, method1,
5855 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005856 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005857 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005858 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005859 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005860 return false;
5861 }
5862 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005863 const dex::TypeList* types1 = method1->GetParameterTypeList();
5864 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005865 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005866 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005867 ThrowSignatureMismatch(klass, super_klass, method1,
5868 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005869 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005870 return false;
5871 }
5872 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005873 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005874 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005875 ThrowSignatureMismatch(klass, super_klass, method1,
5876 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005877 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005878 return false;
5879 }
5880 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005881 }
5882 uint32_t num_types = types1->Size();
5883 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005884 ThrowSignatureMismatch(klass, super_klass, method1,
5885 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005886 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005887 return false;
5888 }
5889 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005890 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005891 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005892 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005893 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005894 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005895 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005896 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005897 return false;
5898 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005899 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005900 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005901 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005902 if (UNLIKELY(other_param_type == nullptr)) {
5903 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005904 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005905 return false;
5906 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005907 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005908 ThrowSignatureMismatch(klass, super_klass, method1,
5909 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5910 i,
David Sehr709b0702016-10-13 09:12:37 -07005911 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005912 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005913 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005914 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005915 return false;
5916 }
5917 }
5918 return true;
5919}
5920
5921
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005922bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005923 if (klass->IsInterface()) {
5924 return true;
5925 }
Ian Rogers151f2212014-05-06 11:27:27 -07005926 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005927 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005928 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005929 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005930 if (klass->HasSuperClass() &&
5931 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005932 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005933 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005934 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5935 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5936 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005937 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5938 klass,
5939 super_klass,
5940 m,
5941 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005942 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005943 return false;
5944 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005945 }
5946 }
5947 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005948 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005949 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5950 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5951 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005952 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005953 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5954 j, image_pointer_size_);
5955 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5956 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005957 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5958 klass,
5959 super_klass,
5960 m,
5961 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005962 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005963 return false;
5964 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005965 }
5966 }
5967 }
5968 }
5969 return true;
5970}
5971
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005972bool ClassLinker::EnsureInitialized(Thread* self,
5973 Handle<mirror::Class> c,
5974 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005975 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005976 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005977
Mathieu Chartier524507a2014-08-27 15:28:28 -07005978 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005979 // If we've seen an initialized but not visibly initialized class
5980 // many times, request visible initialization.
5981 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5982 // Thanks to the x86 memory model classes skip the initialized status.
5983 DCHECK(c->IsVisiblyInitialized());
5984 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5985 if (self->IncrementMakeVisiblyInitializedCounter()) {
5986 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5987 }
5988 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005989 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005990 return true;
5991 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005992 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5993 //
5994 // Ensure the bitstring is initialized before any of the class initialization
5995 // logic occurs. Once a class initializer starts running, objects can
5996 // escape into the heap and use the subtype checking code.
5997 //
5998 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5999 // can be used as a source for the IsSubClass check, and that all ancestors
6000 // of the class are Assigned (can be used as a target for IsSubClass check)
6001 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00006002 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07006003 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00006004 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07006005 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
6006 }
Ian Rogers7b078e82014-09-10 14:44:24 -07006007 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07006008 if (!success) {
6009 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07006010 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07006011 }
6012 } else {
6013 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08006014 }
6015 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07006016}
6017
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006018void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
6019 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006020 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006021 for (ArtField& field : new_class->GetIFields()) {
6022 if (field.GetDeclaringClass() == temp_class) {
6023 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006024 }
6025 }
6026
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006027 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006028 for (ArtField& field : new_class->GetSFields()) {
6029 if (field.GetDeclaringClass() == temp_class) {
6030 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006031 }
6032 }
6033
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006034 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006035 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08006036 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006037 if (method.GetDeclaringClass() == temp_class) {
6038 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006039 }
6040 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006041
6042 // Make sure the remembered set and mod-union tables know that we updated some of the native
6043 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006044 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006045}
6046
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006047void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08006048 CHECK(class_loader->GetAllocator() == nullptr);
6049 CHECK(class_loader->GetClassTable() == nullptr);
6050 Thread* const self = Thread::Current();
6051 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08006052 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08006053 // Create and set the class table.
6054 data.class_table = new ClassTable;
6055 class_loader->SetClassTable(data.class_table);
6056 // Create and set the linear allocator.
6057 data.allocator = Runtime::Current()->CreateLinearAlloc();
6058 class_loader->SetAllocator(data.allocator);
6059 // Add to the list so that we know to free the data later.
6060 class_loaders_.push_back(data);
6061}
6062
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006063ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07006064 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07006065 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006066 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07006067 ClassTable* class_table = class_loader->GetClassTable();
6068 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08006069 RegisterClassLoader(class_loader);
6070 class_table = class_loader->GetClassTable();
6071 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07006072 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006073 return class_table;
6074}
6075
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006076ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07006077 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006078}
6079
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006080static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006081 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006082 while (klass->HasSuperClass()) {
6083 klass = klass->GetSuperClass();
6084 if (klass->ShouldHaveImt()) {
6085 return klass->GetImt(pointer_size);
6086 }
6087 }
6088 return nullptr;
6089}
6090
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006091bool ClassLinker::LinkClass(Thread* self,
6092 const char* descriptor,
6093 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006094 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006095 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006096 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006097
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006098 if (!LinkSuperClass(klass)) {
6099 return false;
6100 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006101 ArtMethod* imt_data[ImTable::kSize];
6102 // If there are any new conflicts compared to super class.
6103 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006104 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006105 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006106 return false;
6107 }
Ian Rogers7b078e82014-09-10 14:44:24 -07006108 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006109 return false;
6110 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006111 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006112 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07006113 return false;
6114 }
6115 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00006116 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006117
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006118 ImTable* imt = nullptr;
6119 if (klass->ShouldHaveImt()) {
6120 // If there are any new conflicts compared to the super class we can not make a copy. There
6121 // can be cases where both will have a conflict method at the same slot without having the same
6122 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
6123 // will possibly create a table that is incorrect for either of the classes.
6124 // Same IMT with new_conflict does not happen very often.
6125 if (!new_conflict) {
6126 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
6127 if (super_imt != nullptr) {
6128 bool imt_equals = true;
6129 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
6130 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
6131 }
6132 if (imt_equals) {
6133 imt = super_imt;
6134 }
6135 }
6136 }
6137 if (imt == nullptr) {
6138 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
6139 imt = reinterpret_cast<ImTable*>(
6140 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
6141 if (imt == nullptr) {
6142 return false;
6143 }
6144 imt->Populate(imt_data, image_pointer_size_);
6145 }
6146 }
6147
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006148 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
6149 // We don't need to retire this class as it has no embedded tables or it was created the
6150 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006151 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006152
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006153 if (klass->ShouldHaveEmbeddedVTable()) {
6154 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006155 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006156 if (klass->ShouldHaveImt()) {
6157 klass->SetImt(imt, image_pointer_size_);
6158 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006159
6160 // Update CHA info based on whether we override methods.
6161 // Have to do this before setting the class as resolved which allows
6162 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006163 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006164 cha_->UpdateAfterLoadingOf(klass);
6165 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006166
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006167 // This will notify waiters on klass that saw the not yet resolved
6168 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006169 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006170 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006171 } else {
6172 CHECK(!klass->IsResolved());
6173 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006174 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006175 Handle<mirror::Class> h_new_class =
6176 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006177 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6178 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6179 // may not see any references to the target space and clean the card for a class if another
6180 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006181 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006182 klass->SetSFieldsPtrUnchecked(nullptr);
6183 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006184 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006185 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006186 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006187 return false;
6188 }
6189
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006190 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6191 ObjectLock<mirror::Class> lock(self, h_new_class);
6192 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006193
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006194 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006195 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006196 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006197 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006198 const ObjPtr<mirror::Class> existing =
6199 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006200 if (class_loader != nullptr) {
6201 // We updated the class in the class table, perform the write barrier so that the GC knows
6202 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006203 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006204 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006205 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006206 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006207 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6208 }
6209 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006210
Mingyao Yang063fc772016-08-02 11:02:54 -07006211 // Update CHA info based on whether we override methods.
6212 // Have to do this before setting the class as resolved which allows
6213 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006214 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006215 cha_->UpdateAfterLoadingOf(h_new_class);
6216 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006217
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006218 // This will notify waiters on temp class that saw the not yet resolved class in the
6219 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006220 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006221
Vladimir Marko2c64a832018-01-04 11:31:56 +00006222 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006223 // This will notify waiters on new_class that saw the not yet resolved
6224 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006225 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006226 // Return the new class.
6227 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006228 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006229 return true;
6230}
6231
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006232bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006233 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006234 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006235 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6236 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006237 // Check that a class does not inherit from itself directly.
6238 //
6239 // TODO: This is a cheap check to detect the straightforward case
6240 // of a class extending itself (b/28685551), but we should do a
6241 // proper cycle detection on loaded classes, to detect all cases
6242 // of class circularity errors (b/28830038).
6243 if (super_class_idx == class_def.class_idx_) {
6244 ThrowClassCircularityError(klass.Get(),
6245 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006246 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006247 return false;
6248 }
6249
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006250 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006251 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006252 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006253 return false;
6254 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006255 // Verify
6256 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006257 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006258 super_class->PrettyDescriptor().c_str(),
6259 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006260 return false;
6261 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006262 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006263 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006264 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006265 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006266 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006267 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006268 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006269 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006270 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006271 DCHECK(Thread::Current()->IsExceptionPending());
6272 return false;
6273 }
6274 // Verify
6275 if (!klass->CanAccess(interface)) {
6276 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006277 ThrowIllegalAccessError(klass.Get(),
6278 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006279 interface->PrettyDescriptor().c_str(),
6280 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006281 return false;
6282 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006283 }
6284 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006285 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006286 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006287 return true;
6288}
6289
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006290bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006291 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006292 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006293 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6294 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006295 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006296 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006297 return false;
6298 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006299 return true;
6300 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006301 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006302 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006303 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006304 return false;
6305 }
6306 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006307 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006308 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6309 return false;
6310 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006311 if (super->IsFinal()) {
6312 ThrowVerifyError(klass.Get(),
6313 "Superclass %s of %s is declared final",
6314 super->PrettyDescriptor().c_str(),
6315 klass->PrettyDescriptor().c_str());
6316 return false;
6317 }
6318 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006319 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006320 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006321 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006322 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006323 return false;
6324 }
6325 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006326 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006327 super->PrettyDescriptor().c_str(),
6328 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006329 return false;
6330 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006331
Brian Carlstromf3632832014-05-20 15:36:53 -07006332 // Inherit kAccClassIsFinalizable from the superclass in case this
6333 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006334 if (super->IsFinalizable()) {
6335 klass->SetFinalizable();
6336 }
6337
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006338 // Inherit class loader flag form super class.
6339 if (super->IsClassLoaderClass()) {
6340 klass->SetClassLoaderClass();
6341 }
6342
Elliott Hughes2da50362011-10-10 16:57:08 -07006343 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006344 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006345 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006346 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006347 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006348 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006349 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006350 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006351 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006352 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006353 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006354 return false;
6355 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006356
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006357 if (kIsDebugBuild) {
6358 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006359 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006360 CHECK(super->IsResolved());
6361 super = super->GetSuperClass();
6362 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006363 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006364 return true;
6365}
6366
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006367// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006368bool ClassLinker::LinkMethods(Thread* self,
6369 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006370 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006371 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006372 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006373 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006374 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6375 // need to have default methods be in the virtuals array of each class but we don't set that up
6376 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006377 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006378 // Link virtual methods then interface methods.
6379 // We set up the interface lookup table first because we need it to determine if we need to update
6380 // any vtable entries with new default method implementations.
6381 return SetupInterfaceLookupTable(self, klass, interfaces)
6382 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006383 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006384}
6385
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006386// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6387// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6388// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006389class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006390 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006391 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006392 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006393 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6394 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006395 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006396 }
6397
6398 const char* GetName() {
6399 if (name_ == nullptr) {
6400 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6401 }
6402 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006403 }
6404
Mathieu Chartiere401d142015-04-22 13:56:20 -07006405 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006406 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006407 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006408 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006409 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006410 if (dex_file_ == other_dex_file) {
6411 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6412 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006413 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006414 uint32_t other_name_len;
6415 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6416 &other_name_len);
6417 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6418 return false;
6419 }
6420 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6421 }
6422
6423 private:
6424 // Dex file for the method to compare against.
6425 const DexFile* const dex_file_;
6426 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006427 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006428 // Lazily computed name from the dex file's strings.
6429 const char* name_;
6430 // Lazily computed name length.
6431 uint32_t name_len_;
6432};
6433
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006434class LinkVirtualHashTable {
6435 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006436 LinkVirtualHashTable(Handle<mirror::Class> klass,
6437 size_t hash_size,
6438 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006439 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006440 : klass_(klass),
6441 hash_size_(hash_size),
6442 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006443 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006444 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6445 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006446
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006447 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006448 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6449 virtual_method_index, image_pointer_size_);
6450 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006451 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006452 uint32_t index = hash % hash_size_;
6453 // Linear probe until we have an empty slot.
6454 while (hash_table_[index] != invalid_index_) {
6455 if (++index == hash_size_) {
6456 index = 0;
6457 }
6458 }
6459 hash_table_[index] = virtual_method_index;
6460 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006461
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006462 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006463 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006464 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006465 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006466 size_t index = hash % hash_size_;
6467 while (true) {
6468 const uint32_t value = hash_table_[index];
6469 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6470 // the block and can safely assume not found.
6471 if (value == invalid_index_) {
6472 break;
6473 }
6474 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006475 ArtMethod* virtual_method =
6476 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6477 if (comparator->HasSameNameAndSignature(
6478 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006479 hash_table_[index] = removed_index_;
6480 return value;
6481 }
6482 }
6483 if (++index == hash_size_) {
6484 index = 0;
6485 }
6486 }
6487 return GetNotFoundIndex();
6488 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006489
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006490 static uint32_t GetNotFoundIndex() {
6491 return invalid_index_;
6492 }
6493
6494 private:
6495 static const uint32_t invalid_index_;
6496 static const uint32_t removed_index_;
6497
6498 Handle<mirror::Class> klass_;
6499 const size_t hash_size_;
6500 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006501 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006502};
6503
6504const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6505const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6506
Stephen Hines1ddd9132017-02-08 01:51:18 -08006507bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006508 Thread* self,
6509 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006510 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006511 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006512 if (klass->IsInterface()) {
6513 // No vtable.
6514 if (!IsUint<16>(num_virtual_methods)) {
6515 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6516 return false;
6517 }
6518 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006519 // Assign each method an IMT index and set the default flag.
6520 for (size_t i = 0; i < num_virtual_methods; ++i) {
6521 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6522 m->SetMethodIndex(i);
6523 if (!m->IsAbstract()) {
Vladimir Marko1c993cd2020-05-28 09:30:06 +00006524 // If the dex file does not support default methods, throw ClassFormatError.
6525 // This check is necessary to protect from odd cases, such as native default
6526 // methods, that the dex file verifier permits for old dex file versions. b/157170505
6527 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
6528 // currently running CTS tests for default methods with dex file version 035 which
6529 // does not support default methods. So, we limit this to native methods. b/157718952
6530 if (m->IsNative()) {
6531 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
6532 ThrowClassFormatError(klass.Get(),
6533 "Dex file does not support default method '%s'",
6534 m->PrettyMethod().c_str());
6535 return false;
6536 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006537 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6538 has_defaults = true;
6539 }
6540 }
6541 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6542 // during initialization. This is a performance optimization. We could simply traverse the
6543 // virtual_methods_ array again during initialization.
6544 if (has_defaults) {
6545 klass->SetHasDefaultMethods();
6546 }
6547 return true;
6548 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006549 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6550 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006551 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006552 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006553 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006554 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006555 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006556 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006557 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006558 return false;
6559 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006560 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006561 vtable->SetElementPtrSize(
6562 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006563 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006564 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6565 // might give us new default methods). If no new interfaces then we can skip the rest since
6566 // the class cannot override any of the super-class's methods. This is required for
6567 // correctness since without it we might not update overridden default method vtable entries
6568 // correctly.
6569 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006570 klass->SetVTable(vtable.Get());
6571 return true;
6572 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006573 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006574 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006575 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006576 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006577 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6578 // might give us new default methods). See comment above.
6579 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006580 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006581 return true;
6582 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006583 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6584 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006585 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006586 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006587 return false;
6588 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006589 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006590 // How the algorithm works:
6591 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6592 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6593 // method which has not been matched to a vtable method, and j if the virtual method at the
6594 // index overrode the super virtual method at index j.
6595 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6596 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6597 // the need for the initial vtable which we later shrink back down).
6598 // 3. Add non overridden methods to the end of the vtable.
6599 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006600 // + 1 so that even if we only have new default methods we will still be able to use this hash
6601 // table (i.e. it will never have 0 size).
6602 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006603 uint32_t* hash_table_ptr;
6604 std::unique_ptr<uint32_t[]> hash_heap_storage;
6605 if (hash_table_size <= kMaxStackHash) {
6606 hash_table_ptr = reinterpret_cast<uint32_t*>(
6607 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6608 } else {
6609 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6610 hash_table_ptr = hash_heap_storage.get();
6611 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006612 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006613 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006614 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006615 DCHECK(klass->GetVirtualMethodDuringLinking(
6616 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006617 hash_table.Add(i);
6618 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006619 // 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 -07006620 // the hash table.
6621 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006622 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006623 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006624 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6625 super_method->GetAccessFlags())) {
6626 // Continue on to the next method since this one is package private and canot be overridden.
6627 // Before Android 4.1, the package-private method super_method might have been incorrectly
6628 // overridden.
6629 continue;
6630 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006631 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006632 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006633 // We remove the method so that subsequent lookups will be faster by making the hash-map
6634 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006635 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6636 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006637 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6638 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006639 if (super_method->IsFinal()) {
6640 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6641 virtual_method->PrettyMethod().c_str(),
6642 super_method->GetDeclaringClassDescriptor());
6643 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006644 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006645 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6646 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006647 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006648 // We didn't directly override this method but we might through default methods...
6649 // Check for default method update.
6650 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006651 switch (FindDefaultMethodImplementation(self,
6652 super_method,
6653 klass,
6654 /*out*/&default_method)) {
6655 case DefaultMethodSearchResult::kDefaultConflict: {
6656 // A conflict was found looking for default methods. Note this (assuming it wasn't
6657 // pre-existing) in the translations map.
6658 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6659 // Don't generate another conflict method to reduce memory use as an optimization.
6660 default_translations->insert(
6661 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6662 }
6663 break;
6664 }
6665 case DefaultMethodSearchResult::kAbstractFound: {
6666 // No conflict but method is abstract.
6667 // We note that this vtable entry must be made abstract.
6668 if (UNLIKELY(!super_method->IsAbstract())) {
6669 default_translations->insert(
6670 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6671 }
6672 break;
6673 }
6674 case DefaultMethodSearchResult::kDefaultFound: {
6675 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6676 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6677 // Found a default method implementation that is new.
6678 // TODO Refactor this add default methods to virtuals here and not in
6679 // LinkInterfaceMethods maybe.
6680 // The problem is default methods might override previously present
6681 // default-method or miranda-method vtable entries from the superclass.
6682 // Unfortunately we need these to be entries in this class's virtuals. We do not
6683 // give these entries there until LinkInterfaceMethods so we pass this map around
6684 // to let it know which vtable entries need to be updated.
6685 // Make a note that vtable entry j must be updated, store what it needs to be updated
6686 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6687 // then.
6688 default_translations->insert(
6689 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006690 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6691 << " overridden by default "
6692 << default_method->PrettyMethod()
6693 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006694 }
6695 break;
6696 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006697 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006698 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006699 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006700 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006701 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006702 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006703 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006704 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6705 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006706 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006707 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006708 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006709 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006710 local_method->SetMethodIndex(actual_count);
6711 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006712 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006713 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006714 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006715 return false;
6716 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006717 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006718 CHECK_LE(actual_count, max_count);
6719 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006720 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6721 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006722 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006723 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006724 return false;
6725 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006726 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006727 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006728 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006729 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006730 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006731 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6732 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006733 return false;
6734 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006735 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006736 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006737 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006738 return false;
6739 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006740 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006741 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6742 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006743 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006744 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006745 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006746 }
6747 return true;
6748}
6749
Alex Light9139e002015-10-09 15:59:48 -07006750// Determine if the given iface has any subinterface in the given list that declares the method
6751// specified by 'target'.
6752//
6753// Arguments
6754// - self: The thread we are running on
6755// - target: A comparator that will match any method that overrides the method we are checking for
6756// - iftable: The iftable we are searching for an overriding method on.
6757// - ifstart: The index of the interface we are checking to see if anything overrides
6758// - iface: The interface we are checking to see if anything overrides.
6759// - image_pointer_size:
6760// The image pointer size.
6761//
6762// Returns
6763// - True: There is some method that matches the target comparator defined in an interface that
6764// is a subtype of iface.
6765// - False: There is no method that matches the target comparator in any interface that is a subtype
6766// of iface.
6767static bool ContainsOverridingMethodOf(Thread* self,
6768 MethodNameAndSignatureComparator& target,
6769 Handle<mirror::IfTable> iftable,
6770 size_t ifstart,
6771 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006772 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006773 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006774 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006775 DCHECK(iface != nullptr);
6776 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006777 DCHECK_GE(ifstart, 0u);
6778 DCHECK_LT(ifstart, iftable->Count());
6779 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6780 DCHECK(iface->IsInterface());
6781
6782 size_t iftable_count = iftable->Count();
6783 StackHandleScope<1> hs(self);
6784 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6785 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6786 // Skip ifstart since our current interface obviously cannot override itself.
6787 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006788 // Iterate through every method on this interface. The order does not matter.
6789 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006790 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006791 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006792 // Check if the i'th interface is a subtype of this one.
6793 if (iface->IsAssignableFrom(current_iface.Get())) {
6794 return true;
6795 }
6796 break;
6797 }
6798 }
6799 }
6800 return false;
6801}
6802
Alex Lighteb7c1442015-08-31 13:17:42 -07006803// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006804// out_default_method and returns kDefaultFound on success. If no default method was found return
6805// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6806// default_method conflict) it will return kDefaultConflict.
6807ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6808 Thread* self,
6809 ArtMethod* target_method,
6810 Handle<mirror::Class> klass,
6811 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006812 DCHECK(self != nullptr);
6813 DCHECK(target_method != nullptr);
6814 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006815
6816 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006817
6818 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6819 // table. This lets us walk the table backwards when searching for default methods. The first one
6820 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6821 // track of it and then continue checking all other interfaces, since we need to throw an error if
6822 // we encounter conflicting default method implementations (one is not a subtype of the other).
6823 //
6824 // The order of unrelated interfaces does not matter and is not defined.
6825 size_t iftable_count = klass->GetIfTableCount();
6826 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006827 // No interfaces. We have already reset out to null so just return kAbstractFound.
6828 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006829 }
6830
Alex Light9139e002015-10-09 15:59:48 -07006831 StackHandleScope<3> hs(self);
6832 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006833 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006834 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006835 MethodNameAndSignatureComparator target_name_comparator(
6836 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6837 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006838 for (size_t k = iftable_count; k != 0; ) {
6839 --k;
6840
Alex Lighteb7c1442015-08-31 13:17:42 -07006841 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006842
6843 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006844 // Iterate through every declared method on this interface. The order does not matter.
6845 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6846 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006847 // Skip abstract methods and methods with different names.
6848 if (current_method->IsAbstract() ||
6849 !target_name_comparator.HasSameNameAndSignature(
6850 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6851 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006852 } else if (!current_method->IsPublic()) {
6853 // The verifier should have caught the non-public method for dex version 37. Just warn and
6854 // skip it since this is from before default-methods so we don't really need to care that it
6855 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006856 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6857 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006858 << "This will be a fatal error in subsequent versions of android. "
6859 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006860 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006861 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006862 // We have multiple default impls of the same method. This is a potential default conflict.
6863 // We need to check if this possibly conflicting method is either a superclass of the chosen
6864 // default implementation or is overridden by a non-default interface method. In either case
6865 // there is no conflict.
6866 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6867 !ContainsOverridingMethodOf(self,
6868 target_name_comparator,
6869 iftable,
6870 k,
6871 iface,
6872 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006873 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006874 << current_method->PrettyMethod() << " and "
6875 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6876 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006877 *out_default_method = nullptr;
6878 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006879 } else {
6880 break; // Continue checking at the next interface.
6881 }
6882 } else {
Alex Light9139e002015-10-09 15:59:48 -07006883 // chosen_iface == null
6884 if (!ContainsOverridingMethodOf(self,
6885 target_name_comparator,
6886 iftable,
6887 k,
6888 iface,
6889 image_pointer_size_)) {
6890 // Don't set this as the chosen interface if something else is overriding it (because that
6891 // other interface would be potentially chosen instead if it was default). If the other
6892 // interface was abstract then we wouldn't select this interface as chosen anyway since
6893 // the abstract method masks it.
6894 *out_default_method = current_method;
6895 chosen_iface.Assign(iface.Get());
6896 // We should now finish traversing the graph to find if we have default methods that
6897 // conflict.
6898 } else {
David Sehr709b0702016-10-13 09:12:37 -07006899 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6900 << "' was "
6901 << "skipped because it was overridden by an abstract method in a "
6902 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006903 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006904 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006905 break;
6906 }
6907 }
Alex Light9139e002015-10-09 15:59:48 -07006908 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006909 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6910 << "' selected "
6911 << "as the implementation for '" << target_method->PrettyMethod()
6912 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006913 return DefaultMethodSearchResult::kDefaultFound;
6914 } else {
6915 return DefaultMethodSearchResult::kAbstractFound;
6916 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006917}
6918
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006919ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006920 ArtMethod* conflict_method,
6921 ArtMethod* interface_method,
6922 ArtMethod* method,
6923 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006924 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006925 Runtime* const runtime = Runtime::Current();
6926 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6927 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6928
6929 // Create a new entry if the existing one is the shared conflict method.
6930 ArtMethod* new_conflict_method = new_entry
6931 ? runtime->CreateImtConflictMethod(linear_alloc)
6932 : conflict_method;
6933
6934 // Allocate a new table. Note that we will leak this table at the next conflict,
6935 // but that's a tradeoff compared to making the table fixed size.
6936 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006937 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6938 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006939 if (data == nullptr) {
6940 LOG(ERROR) << "Failed to allocate conflict table";
6941 return conflict_method;
6942 }
6943 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6944 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006945 method,
6946 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006947
6948 // Do a fence to ensure threads see the data in the table before it is assigned
6949 // to the conflict method.
6950 // Note that there is a race in the presence of multiple threads and we may leak
6951 // memory from the LinearAlloc, but that's a tradeoff compared to using
6952 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006953 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006954 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006955 return new_conflict_method;
6956}
6957
Vladimir Marko921094a2017-01-12 18:37:06 +00006958bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6959 Handle<mirror::Class> klass,
6960 Handle<mirror::IfTable> iftable) {
6961 DCHECK(!klass->IsInterface());
6962 const bool has_superclass = klass->HasSuperClass();
6963 const bool extend_super_iftable = has_superclass;
6964 const size_t ifcount = klass->GetIfTableCount();
6965 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6966 for (size_t i = 0; i < ifcount; ++i) {
6967 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6968 if (num_methods > 0) {
6969 const bool is_super = i < super_ifcount;
6970 // This is an interface implemented by a super-class. Therefore we can just copy the method
6971 // array from the superclass.
6972 const bool super_interface = is_super && extend_super_iftable;
6973 ObjPtr<mirror::PointerArray> method_array;
6974 if (super_interface) {
6975 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6976 DCHECK(if_table != nullptr);
6977 DCHECK(if_table->GetMethodArray(i) != nullptr);
6978 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006979 StackHandleScope<1u> hs(self);
6980 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6981 method_array =
6982 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006983 } else {
6984 method_array = AllocPointerArray(self, num_methods);
6985 }
6986 if (UNLIKELY(method_array == nullptr)) {
6987 self->AssertPendingOOMException();
6988 return false;
6989 }
6990 iftable->SetMethodArray(i, method_array);
6991 }
6992 }
6993 return true;
6994}
6995
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006996void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6997 ArtMethod* imt_conflict_method,
6998 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006999 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007000 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007001 // Place method in imt if entry is empty, place conflict otherwise.
7002 if (*imt_ref == unimplemented_method) {
7003 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00007004 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007005 // If we are not a conflict and we have the same signature and name as the imt
7006 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00007007 // Note that we have checked IsRuntimeMethod, as there may be multiple different
7008 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007009 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007010 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07007011 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007012 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007013 *imt_ref = current_method;
7014 } else {
Alex Light9139e002015-10-09 15:59:48 -07007015 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007016 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07007017 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00007018 } else {
7019 // Place the default conflict method. Note that there may be an existing conflict
7020 // method in the IMT, but it could be one tailored to the super class, with a
7021 // specific ImtConflictTable.
7022 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007023 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07007024 }
7025}
7026
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007027void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07007028 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
7029 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007030 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007031 Runtime* const runtime = Runtime::Current();
7032 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
7033 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007034 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007035 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007036 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007037 FillIMTFromIfTable(klass->GetIfTable(),
7038 unimplemented_method,
7039 conflict_method,
7040 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007041 /*create_conflict_tables=*/true,
7042 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007043 &new_conflict,
7044 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007045 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007046 if (!klass->ShouldHaveImt()) {
7047 return;
7048 }
7049 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
7050 // we can just use the same pointer.
7051 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007052 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007053 if (super_class != nullptr && super_class->ShouldHaveImt()) {
7054 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7055 bool same = true;
7056 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
7057 ArtMethod* method = imt_data[i];
7058 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
7059 if (method != super_method) {
7060 bool is_conflict_table = method->IsRuntimeMethod() &&
7061 method != unimplemented_method &&
7062 method != conflict_method;
7063 // Verify conflict contents.
7064 bool super_conflict_table = super_method->IsRuntimeMethod() &&
7065 super_method != unimplemented_method &&
7066 super_method != conflict_method;
7067 if (!is_conflict_table || !super_conflict_table) {
7068 same = false;
7069 } else {
7070 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
7071 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
7072 same = same && table1->Equals(table2, image_pointer_size_);
7073 }
7074 }
7075 }
7076 if (same) {
7077 imt = super_imt;
7078 }
7079 }
7080 if (imt == nullptr) {
7081 imt = klass->GetImt(image_pointer_size_);
7082 DCHECK(imt != nullptr);
7083 imt->Populate(imt_data, image_pointer_size_);
7084 } else {
7085 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007086 }
7087}
7088
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007089ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
7090 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07007091 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007092 void* data = linear_alloc->Alloc(Thread::Current(),
7093 ImtConflictTable::ComputeSize(count,
7094 image_pointer_size));
7095 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
7096}
7097
7098ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
7099 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
7100}
7101
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007102void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007103 ArtMethod* unimplemented_method,
7104 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007105 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007106 bool create_conflict_tables,
7107 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007108 /*out*/bool* new_conflict,
7109 /*out*/ArtMethod** imt) {
7110 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007111 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007112 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007113 const size_t num_virtuals = interface->NumVirtualMethods();
7114 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7115 // Virtual methods can be larger than the if table methods if there are default methods.
7116 DCHECK_GE(num_virtuals, method_array_count);
7117 if (kIsDebugBuild) {
7118 if (klass->IsInterface()) {
7119 DCHECK_EQ(method_array_count, 0u);
7120 } else {
7121 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
7122 }
7123 }
7124 if (method_array_count == 0) {
7125 continue;
7126 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007127 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007128 for (size_t j = 0; j < method_array_count; ++j) {
7129 ArtMethod* implementation_method =
7130 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7131 if (ignore_copied_methods && implementation_method->IsCopied()) {
7132 continue;
7133 }
7134 DCHECK(implementation_method != nullptr);
7135 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7136 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7137 // or interface methods in the IMT here they will not create extra conflicts since we compare
7138 // names and signatures in SetIMTRef.
7139 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007140 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007141
7142 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7143 // the same implementation method, keep track of this to avoid creating a conflict table in
7144 // this case.
7145
7146 // Conflict table size for each IMT slot.
7147 ++conflict_counts[imt_index];
7148
7149 SetIMTRef(unimplemented_method,
7150 imt_conflict_method,
7151 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007152 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007153 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007154 }
7155 }
7156
7157 if (create_conflict_tables) {
7158 // Create the conflict tables.
7159 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007160 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007161 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007162 if (imt[i] == imt_conflict_method) {
7163 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7164 if (new_table != nullptr) {
7165 ArtMethod* new_conflict_method =
7166 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7167 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7168 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007169 } else {
7170 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007171 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007172 }
7173 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007174 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007175 }
7176 }
7177
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007178 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007179 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007180 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7181 // Virtual methods can be larger than the if table methods if there are default methods.
7182 if (method_array_count == 0) {
7183 continue;
7184 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007185 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007186 for (size_t j = 0; j < method_array_count; ++j) {
7187 ArtMethod* implementation_method =
7188 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7189 if (ignore_copied_methods && implementation_method->IsCopied()) {
7190 continue;
7191 }
7192 DCHECK(implementation_method != nullptr);
7193 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007194 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007195 if (!imt[imt_index]->IsRuntimeMethod() ||
7196 imt[imt_index] == unimplemented_method ||
7197 imt[imt_index] == imt_conflict_method) {
7198 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007199 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007200 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7201 const size_t num_entries = table->NumEntries(image_pointer_size_);
7202 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7203 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007204 }
7205 }
7206 }
7207}
7208
Alex Lighteb7c1442015-08-31 13:17:42 -07007209// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7210// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007211static bool NotSubinterfaceOfAny(
7212 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
7213 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007214 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007215 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007216 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007217 for (ObjPtr<mirror::Class> c : classes) {
7218 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007219 return false;
7220 }
7221 }
7222 return true;
7223}
7224
7225// Fills in and flattens the interface inheritance hierarchy.
7226//
7227// By the end of this function all interfaces in the transitive closure of to_process are added to
7228// the iftable and every interface precedes all of its sub-interfaces in this list.
7229//
7230// all I, J: Interface | I <: J implies J precedes I
7231//
7232// (note A <: B means that A is a subtype of B)
7233//
7234// This returns the total number of items in the iftable. The iftable might be resized down after
7235// this call.
7236//
7237// We order this backwards so that we do not need to reorder superclass interfaces when new
7238// interfaces are added in subclass's interface tables.
7239//
7240// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7241// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7242// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7243// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007244static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007245 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07007246 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07007247 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007248 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007249 // This is the set of all class's already in the iftable. Used to make checking if a class has
7250 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007251 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07007252 // The first super_ifcount elements are from the superclass. We note that they are already added.
7253 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007254 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007255 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
7256 classes_in_iftable.insert(iface);
7257 }
7258 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007259 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007260 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7261 // At this point in the loop current-iface-list has the invariant that:
7262 // for every pair of interfaces I,J within it:
7263 // if index_of(I) < index_of(J) then I is not a subtype of J
7264
7265 // If we have already seen this element then all of its super-interfaces must already be in the
7266 // current-iface-list so we can skip adding it.
7267 if (!ContainsElement(classes_in_iftable, interface)) {
7268 // We haven't seen this interface so add all of its super-interfaces onto the
7269 // current-iface-list, skipping those already on it.
7270 int32_t ifcount = interface->GetIfTableCount();
7271 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007272 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007273 if (!ContainsElement(classes_in_iftable, super_interface)) {
7274 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
7275 classes_in_iftable.insert(super_interface);
7276 iftable->SetInterface(filled_ifcount, super_interface);
7277 filled_ifcount++;
7278 }
7279 }
7280 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7281 // Place this interface onto the current-iface-list after all of its super-interfaces.
7282 classes_in_iftable.insert(interface);
7283 iftable->SetInterface(filled_ifcount, interface);
7284 filled_ifcount++;
7285 } else if (kIsDebugBuild) {
7286 // Check all super-interfaces are already in the list.
7287 int32_t ifcount = interface->GetIfTableCount();
7288 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007289 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007290 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007291 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7292 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007293 }
7294 }
7295 }
7296 if (kIsDebugBuild) {
7297 // Check that the iftable is ordered correctly.
7298 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007299 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007300 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007301 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007302 // !(if_a <: if_b)
7303 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007304 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7305 << ") extends "
7306 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007307 << "interface list.";
7308 }
7309 }
7310 }
7311 return filled_ifcount;
7312}
7313
7314bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
7315 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7316 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007317 const bool has_superclass = klass->HasSuperClass();
7318 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007319 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007320 const size_t num_interfaces =
7321 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007322 if (num_interfaces == 0) {
7323 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007324 if (LIKELY(has_superclass)) {
7325 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7326 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007327 // Class implements no interfaces.
7328 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007329 return true;
7330 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007331 // Class implements same interfaces as parent, are any of these not marker interfaces?
7332 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007333 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007334 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007335 if (super_iftable->GetMethodArrayCount(i) > 0) {
7336 has_non_marker_interface = true;
7337 break;
7338 }
7339 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007340 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007341 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007342 klass->SetIfTable(super_iftable);
7343 return true;
7344 }
7345 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007346 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007347 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007348 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007349 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007350 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007351 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007352 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007353 if (UNLIKELY(!interface->IsInterface())) {
7354 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007355 ThrowIncompatibleClassChangeError(klass.Get(),
7356 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007357 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007358 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7359 return false;
7360 }
7361 ifcount += interface->GetIfTableCount();
7362 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007363 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007364 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007365 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007366 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007367 return false;
7368 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007369 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007370 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007371 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007372 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007373 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007374 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007375 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007376 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007377
7378 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7379 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7380 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007381 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007382
7383 size_t new_ifcount;
7384 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007385 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007386 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007387 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007388 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007389 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007390 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007391 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007392
7393 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007394 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007395
Ian Rogers7b078e82014-09-10 14:44:24 -07007396 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007397
Ian Rogersb52b01a2012-01-12 17:01:38 -08007398 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007399 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007400 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007401 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007402 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007403 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007404 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007405 return false;
7406 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007407 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007408 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007409 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007410 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007411 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007412 return true;
7413}
7414
Alex Light1f3925d2016-09-07 12:04:20 -07007415// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7416// of methods must be unique.
7417static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7418 return nullptr;
7419}
7420
7421template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007422static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007423 const ScopedArenaVector<ArtMethod*>& list,
7424 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007425 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007426 for (ArtMethod* method : list) {
7427 if (cmp.HasSameNameAndSignature(method)) {
7428 return method;
7429 }
7430 }
Alex Light1f3925d2016-09-07 12:04:20 -07007431 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007432}
7433
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007434namespace {
7435
Alex Light1f3925d2016-09-07 12:04:20 -07007436// Check that all vtable entries are present in this class's virtuals or are the same as a
7437// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007438void CheckClassOwnsVTableEntries(Thread* self,
7439 Handle<mirror::Class> klass,
7440 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007441 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007442 StackHandleScope<2> hs(self);
7443 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007444 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007445 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007446 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007447 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7448 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7449 CHECK(m != nullptr);
7450
Alex Lighta41a30782017-03-29 11:33:19 -07007451 if (m->GetMethodIndexDuringLinking() != i) {
7452 LOG(WARNING) << m->PrettyMethod()
7453 << " has an unexpected method index for its spot in the vtable for class"
7454 << klass->PrettyClass();
7455 }
Alex Lighte64300b2015-12-15 15:02:47 -08007456 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7457 auto is_same_method = [m] (const ArtMethod& meth) {
7458 return &meth == m;
7459 };
Alex Light3f980532017-03-17 15:10:32 -07007460 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7461 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7462 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7463 << klass->PrettyClass() << " or any of its superclasses!";
7464 }
Alex Lighte64300b2015-12-15 15:02:47 -08007465 }
7466}
7467
Alex Light1f3925d2016-09-07 12:04:20 -07007468// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7469// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007470template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007471void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007472 REQUIRES_SHARED(Locks::mutator_lock_) {
7473 StackHandleScope<1> hs(self);
7474 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7475 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007476
7477 // Observations:
7478 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7479 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7480 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7481 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7482 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7483 // * The single-pass algorithm will trade memory for speed, but that is OK.
7484
7485 CHECK_GT(num_entries, 0);
7486
7487 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7488 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7489 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7490 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7491 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7492 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7493 << m2->PrettyMethod() << " (0x" << std::hex
7494 << reinterpret_cast<uintptr_t>(m2) << ")";
7495 };
7496 struct BaseHashType {
7497 static size_t HashCombine(size_t seed, size_t val) {
7498 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7499 }
7500 };
7501
7502 // Check assuming all entries come from the same dex file.
7503 {
7504 // Find the first interesting method and its dex file.
7505 int32_t start = 0;
7506 for (; start < num_entries; ++start) {
7507 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7508 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7509 // maybe).
7510 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7511 vtable_entry->GetAccessFlags())) {
7512 continue;
7513 }
7514 break;
7515 }
7516 if (start == num_entries) {
7517 return;
7518 }
7519 const DexFile* dex_file =
7520 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7521 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7522
7523 // Helper function to avoid logging if we have to run the cross-file checks.
7524 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7525 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7526 using PairType = std::pair<uint32_t, uint16_t>;
7527 struct PairHash : BaseHashType {
7528 size_t operator()(const PairType& key) const {
7529 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7530 }
7531 };
7532 std::unordered_map<PairType, int32_t, PairHash> seen;
7533 seen.reserve(2 * num_entries);
7534 bool need_slow_path = false;
7535 bool found_dup = false;
7536 for (int i = start; i < num_entries; ++i) {
7537 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7538 // wrt/ kPointerSize.
7539 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7540 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7541 vtable_entry->GetAccessFlags())) {
7542 continue;
7543 }
7544 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7545 if (dex_file != m->GetDexFile()) {
7546 need_slow_path = true;
7547 break;
7548 }
7549 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7550 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7551 auto it = seen.find(pair);
7552 if (it != seen.end()) {
7553 found_dup = true;
7554 if (log_warn) {
7555 log_fn(it->second, i);
7556 }
7557 } else {
7558 seen.emplace(pair, i);
7559 }
7560 }
7561 return std::make_pair(need_slow_path, found_dup);
7562 };
7563 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7564 if (!result.first) {
7565 if (result.second) {
7566 check_fn(/* log_warn= */ true);
7567 }
7568 return;
7569 }
7570 }
7571
7572 // Need to check across dex files.
7573 struct Entry {
7574 size_t cached_hash = 0;
7575 const char* name = nullptr;
7576 Signature signature = Signature::NoSignature();
7577 uint32_t name_len = 0;
7578
7579 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7580 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7581 signature(dex_file->GetMethodSignature(mid)) {
7582 }
7583
7584 bool operator==(const Entry& other) const {
7585 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7586 return false;
7587 }
7588 return signature == other.signature;
7589 }
7590 };
7591 struct EntryHash {
7592 size_t operator()(const Entry& key) const {
7593 return key.cached_hash;
7594 }
7595 };
7596 std::unordered_map<Entry, int32_t, EntryHash> map;
7597 for (int32_t i = 0; i < num_entries; ++i) {
7598 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7599 // wrt/ kPointerSize.
7600 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7601 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7602 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007603 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7604 vtable_entry->GetAccessFlags())) {
7605 continue;
7606 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007607 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7608 const DexFile* dex_file = m->GetDexFile();
7609 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7610
7611 Entry e(dex_file, mid);
7612
7613 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7614 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7615 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7616 sig_hash);
7617
7618 auto it = map.find(e);
7619 if (it != map.end()) {
7620 log_fn(it->second, i);
7621 } else {
7622 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007623 }
7624 }
7625}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007626
7627void CheckVTableHasNoDuplicates(Thread* self,
7628 Handle<mirror::Class> klass,
7629 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007630 REQUIRES_SHARED(Locks::mutator_lock_) {
7631 switch (pointer_size) {
7632 case PointerSize::k64:
7633 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7634 break;
7635 case PointerSize::k32:
7636 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7637 break;
7638 }
7639}
Alex Light1f3925d2016-09-07 12:04:20 -07007640
7641static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7642 REQUIRES_SHARED(Locks::mutator_lock_) {
7643 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7644 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7645}
7646
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007647} // namespace
7648
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007649void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7650 ArtMethod* unimplemented_method,
7651 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007652 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007653 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007654 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007655 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007656 if (super_class->ShouldHaveImt()) {
7657 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7658 for (size_t i = 0; i < ImTable::kSize; ++i) {
7659 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007660 }
7661 } else {
7662 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007663 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007664 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007665 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007666 FillIMTFromIfTable(if_table,
7667 unimplemented_method,
7668 imt_conflict_method,
7669 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007670 /*create_conflict_tables=*/false,
7671 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007672 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007673 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007674 }
7675 }
7676}
7677
Vladimir Marko921094a2017-01-12 18:37:06 +00007678class ClassLinker::LinkInterfaceMethodsHelper {
7679 public:
7680 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7681 Handle<mirror::Class> klass,
7682 Thread* self,
7683 Runtime* runtime)
7684 : class_linker_(class_linker),
7685 klass_(klass),
7686 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7687 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7688 self_(self),
7689 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7690 allocator_(&stack_),
7691 default_conflict_methods_(allocator_.Adapter()),
7692 overriding_default_conflict_methods_(allocator_.Adapter()),
7693 miranda_methods_(allocator_.Adapter()),
7694 default_methods_(allocator_.Adapter()),
7695 overriding_default_methods_(allocator_.Adapter()),
7696 move_table_(allocator_.Adapter()) {
7697 }
7698
7699 ArtMethod* FindMethod(ArtMethod* interface_method,
7700 MethodNameAndSignatureComparator& interface_name_comparator,
7701 ArtMethod* vtable_impl)
7702 REQUIRES_SHARED(Locks::mutator_lock_);
7703
7704 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7705 MethodNameAndSignatureComparator& interface_name_comparator)
7706 REQUIRES_SHARED(Locks::mutator_lock_);
7707
7708 bool HasNewVirtuals() const {
7709 return !(miranda_methods_.empty() &&
7710 default_methods_.empty() &&
7711 overriding_default_methods_.empty() &&
7712 overriding_default_conflict_methods_.empty() &&
7713 default_conflict_methods_.empty());
7714 }
7715
7716 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7717
7718 ObjPtr<mirror::PointerArray> UpdateVtable(
7719 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007720 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007721
7722 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7723
7724 void UpdateIMT(ArtMethod** out_imt);
7725
7726 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7727 if (kIsDebugBuild) {
7728 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7729 // Check that there are no stale methods are in the dex cache array.
7730 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7731 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007732 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7733 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007734 CHECK(move_table_.find(m) == move_table_.end() ||
7735 // The original versions of copied methods will still be present so allow those too.
7736 // Note that if the first check passes this might fail to GetDeclaringClass().
7737 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7738 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7739 [m] (ArtMethod& meth) {
7740 return &meth == m;
7741 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7742 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7743 }
7744 }
7745 }
7746
7747 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7748 LengthPrefixedArray<ArtMethod>* methods) {
7749 if (kIsDebugBuild) {
7750 CHECK(methods != nullptr);
7751 // Put some random garbage in old methods to help find stale pointers.
7752 if (methods != old_methods && old_methods != nullptr) {
7753 // Need to make sure the GC is not running since it could be scanning the methods we are
7754 // about to overwrite.
7755 ScopedThreadStateChange tsc(self_, kSuspended);
7756 gc::ScopedGCCriticalSection gcs(self_,
7757 gc::kGcCauseClassLinker,
7758 gc::kCollectorTypeClassLinker);
7759 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7760 method_size_,
7761 method_alignment_);
7762 memset(old_methods, 0xFEu, old_size);
7763 }
7764 }
7765 }
7766
7767 private:
7768 size_t NumberOfNewVirtuals() const {
7769 return miranda_methods_.size() +
7770 default_methods_.size() +
7771 overriding_default_conflict_methods_.size() +
7772 overriding_default_methods_.size() +
7773 default_conflict_methods_.size();
7774 }
7775
7776 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7777 return !klass_->IsInterface();
7778 }
7779
7780 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7781 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7782 << "Interfaces should only have default-conflict methods appended to them.";
7783 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7784 << miranda_methods_.size()
7785 << " default_methods=" << default_methods_.size()
7786 << " overriding_default_methods=" << overriding_default_methods_.size()
7787 << " default_conflict_methods=" << default_conflict_methods_.size()
7788 << " overriding_default_conflict_methods="
7789 << overriding_default_conflict_methods_.size();
7790 }
7791
7792 ClassLinker* class_linker_;
7793 Handle<mirror::Class> klass_;
7794 size_t method_alignment_;
7795 size_t method_size_;
7796 Thread* const self_;
7797
7798 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7799 // the virtual methods array.
7800 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7801 // during cross compilation.
7802 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7803 ArenaStack stack_;
7804 ScopedArenaAllocator allocator_;
7805
7806 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7807 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7808 ScopedArenaVector<ArtMethod*> miranda_methods_;
7809 ScopedArenaVector<ArtMethod*> default_methods_;
7810 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7811
7812 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7813};
7814
7815ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7816 ArtMethod* interface_method,
7817 MethodNameAndSignatureComparator& interface_name_comparator,
7818 ArtMethod* vtable_impl) {
7819 ArtMethod* current_method = nullptr;
7820 switch (class_linker_->FindDefaultMethodImplementation(self_,
7821 interface_method,
7822 klass_,
7823 /*out*/&current_method)) {
7824 case DefaultMethodSearchResult::kDefaultConflict: {
7825 // Default method conflict.
7826 DCHECK(current_method == nullptr);
7827 ArtMethod* default_conflict_method = nullptr;
7828 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7829 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7830 default_conflict_method = vtable_impl;
7831 } else {
7832 // See if we already have a conflict method for this method.
7833 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7834 interface_name_comparator,
7835 default_conflict_methods_,
7836 overriding_default_conflict_methods_);
7837 if (LIKELY(preexisting_conflict != nullptr)) {
7838 // We already have another conflict we can reuse.
7839 default_conflict_method = preexisting_conflict;
7840 } else {
7841 // Note that we do this even if we are an interface since we need to create this and
7842 // cannot reuse another classes.
7843 // Create a new conflict method for this to use.
7844 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7845 new(default_conflict_method) ArtMethod(interface_method,
7846 class_linker_->GetImagePointerSize());
7847 if (vtable_impl == nullptr) {
7848 // Save the conflict method. We need to add it to the vtable.
7849 default_conflict_methods_.push_back(default_conflict_method);
7850 } else {
7851 // Save the conflict method but it is already in the vtable.
7852 overriding_default_conflict_methods_.push_back(default_conflict_method);
7853 }
7854 }
7855 }
7856 current_method = default_conflict_method;
7857 break;
7858 } // case kDefaultConflict
7859 case DefaultMethodSearchResult::kDefaultFound: {
7860 DCHECK(current_method != nullptr);
7861 // Found a default method.
7862 if (vtable_impl != nullptr &&
7863 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7864 // We found a default method but it was the same one we already have from our
7865 // superclass. Don't bother adding it to our vtable again.
7866 current_method = vtable_impl;
7867 } else if (LIKELY(FillTables())) {
7868 // Interfaces don't need to copy default methods since they don't have vtables.
7869 // Only record this default method if it is new to save space.
7870 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7871 // would make lookup for interface super much faster. (We would only need to scan
7872 // the iftable to find if there is a NSME or AME.)
7873 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7874 default_methods_,
7875 overriding_default_methods_);
7876 if (old == nullptr) {
7877 // We found a default method implementation and there were no conflicts.
7878 if (vtable_impl == nullptr) {
7879 // Save the default method. We need to add it to the vtable.
7880 default_methods_.push_back(current_method);
7881 } else {
7882 // Save the default method but it is already in the vtable.
7883 overriding_default_methods_.push_back(current_method);
7884 }
7885 } else {
7886 CHECK(old == current_method) << "Multiple default implementations selected!";
7887 }
7888 }
7889 break;
7890 } // case kDefaultFound
7891 case DefaultMethodSearchResult::kAbstractFound: {
7892 DCHECK(current_method == nullptr);
7893 // Abstract method masks all defaults.
7894 if (vtable_impl != nullptr &&
7895 vtable_impl->IsAbstract() &&
7896 !vtable_impl->IsDefaultConflicting()) {
7897 // We need to make this an abstract method but the version in the vtable already is so
7898 // don't do anything.
7899 current_method = vtable_impl;
7900 }
7901 break;
7902 } // case kAbstractFound
7903 }
7904 return current_method;
7905}
7906
7907ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7908 ArtMethod* interface_method,
7909 MethodNameAndSignatureComparator& interface_name_comparator) {
7910 // Find out if there is already a miranda method we can use.
7911 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7912 miranda_methods_);
7913 if (miranda_method == nullptr) {
7914 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7915 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7916 CHECK(miranda_method != nullptr);
7917 // Point the interface table at a phantom slot.
7918 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7919 miranda_methods_.push_back(miranda_method);
7920 }
7921 return miranda_method;
7922}
7923
7924void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7925 LogNewVirtuals();
7926
7927 const size_t old_method_count = klass_->NumMethods();
7928 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7929 DCHECK_NE(old_method_count, new_method_count);
7930
7931 // Attempt to realloc to save RAM if possible.
7932 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7933 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7934 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7935 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7936 // CopyFrom has internal read barriers.
7937 //
7938 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7939 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7940 method_size_,
7941 method_alignment_);
7942 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7943 method_size_,
7944 method_alignment_);
7945 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7946 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007947 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007948 self_, old_methods, old_methods_ptr_size, new_size));
7949 CHECK(methods != nullptr); // Native allocation failure aborts.
7950
7951 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7952 if (methods != old_methods) {
7953 // Maps from heap allocated miranda method to linear alloc miranda method.
7954 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7955 // Copy over the old methods.
7956 for (auto& m : klass_->GetMethods(pointer_size)) {
7957 move_table_.emplace(&m, &*out);
7958 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7959 // barriers when it copies.
7960 out->CopyFrom(&m, pointer_size);
7961 ++out;
7962 }
7963 }
7964 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7965 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7966 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007967 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7968 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007969 ArtMethod& new_method = *out;
7970 new_method.CopyFrom(mir_method, pointer_size);
7971 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7972 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7973 << "Miranda method should be abstract!";
7974 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007975 // Update the entry in the method array, as the array will be used for future lookups,
7976 // where thread suspension is allowed.
7977 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7978 // would not see them.
7979 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007980 ++out;
7981 }
7982 // We need to copy the default methods into our own method table since the runtime requires that
7983 // every method on a class's vtable be in that respective class's virtual method table.
7984 // NOTE This means that two classes might have the same implementation of a method from the same
7985 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7986 // default method found on a class with one found on the declaring interface directly and must
7987 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007988 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7989 &overriding_default_methods_}) {
7990 for (size_t i = 0; i < methods_vec->size(); ++i) {
7991 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007992 ArtMethod& new_method = *out;
7993 new_method.CopyFrom(def_method, pointer_size);
7994 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7995 // verified yet it shouldn't have methods that are skipping access checks.
7996 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7997 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007998 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007999 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
8000 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
8001 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
8002 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008003 // Update the entry in the method array, as the array will be used for future lookups,
8004 // where thread suspension is allowed.
8005 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
8006 // would not see them.
8007 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00008008 ++out;
8009 }
8010 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008011 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
8012 &overriding_default_conflict_methods_}) {
8013 for (size_t i = 0; i < methods_vec->size(); ++i) {
8014 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00008015 ArtMethod& new_method = *out;
8016 new_method.CopyFrom(conf_method, pointer_size);
8017 // This is a type of default method (there are default method impls, just a conflict) so
8018 // mark this as a default, non-abstract method, since thats what it is. Also clear the
8019 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
8020 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01008021 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
8022 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01008023 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00008024 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01008025 constexpr uint32_t kMaskFlags =
8026 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00008027 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
8028 DCHECK(new_method.IsDefaultConflicting());
8029 // The actual method might or might not be marked abstract since we just copied it from a
8030 // (possibly default) interface method. We need to set it entry point to be the bridge so
8031 // that the compiler will not invoke the implementation of whatever method we copied from.
8032 EnsureThrowsInvocationError(class_linker_, &new_method);
8033 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008034 // Update the entry in the method array, as the array will be used for future lookups,
8035 // where thread suspension is allowed.
8036 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
8037 // would not see them.
8038 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00008039 ++out;
8040 }
8041 }
8042 methods->SetSize(new_method_count);
8043 class_linker_->UpdateClassMethods(klass_.Get(), methods);
8044}
8045
8046ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
8047 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01008048 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008049 // Update the vtable to the new method structures. We can skip this for interfaces since they
8050 // do not have vtables.
8051 const size_t old_vtable_count = old_vtable->GetLength();
8052 const size_t new_vtable_count = old_vtable_count +
8053 miranda_methods_.size() +
8054 default_methods_.size() +
8055 default_conflict_methods_.size();
8056
Vladimir Marko3068d582019-05-28 16:39:29 +01008057 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
8058 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00008059 if (UNLIKELY(vtable == nullptr)) {
8060 self_->AssertPendingOOMException();
8061 return nullptr;
8062 }
8063
8064 size_t vtable_pos = old_vtable_count;
8065 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8066 // Update all the newly copied method's indexes so they denote their placement in the vtable.
8067 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
8068 default_conflict_methods_,
8069 miranda_methods_}) {
8070 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008071 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008072 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
8073 // fields are references into the dex file the method was defined in. Since the ArtMethod
8074 // does not store that information it uses declaring_class_->dex_cache_.
8075 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
8076 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
8077 ++vtable_pos;
8078 }
8079 }
8080 DCHECK_EQ(vtable_pos, new_vtable_count);
8081
8082 // Update old vtable methods. We use the default_translations map to figure out what each
8083 // vtable entry should be updated to, if they need to be at all.
8084 for (size_t i = 0; i < old_vtable_count; ++i) {
8085 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
8086 // Try and find what we need to change this method to.
8087 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008088 if (translation_it != default_translations.end()) {
8089 if (translation_it->second.IsInConflict()) {
8090 // Find which conflict method we are to use for this method.
8091 MethodNameAndSignatureComparator old_method_comparator(
8092 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8093 // We only need to look through overriding_default_conflict_methods since this is an
8094 // overridden method we are fixing up here.
8095 ArtMethod* new_conflict_method = FindSameNameAndSignature(
8096 old_method_comparator, overriding_default_conflict_methods_);
8097 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
8098 translated_method = new_conflict_method;
8099 } else if (translation_it->second.IsAbstract()) {
8100 // Find which miranda method we are to use for this method.
8101 MethodNameAndSignatureComparator old_method_comparator(
8102 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8103 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
8104 miranda_methods_);
8105 DCHECK(miranda_method != nullptr);
8106 translated_method = miranda_method;
8107 } else {
8108 // Normal default method (changed from an older default or abstract interface method).
8109 DCHECK(translation_it->second.IsTranslation());
8110 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008111 auto it = move_table_.find(translated_method);
8112 DCHECK(it != move_table_.end());
8113 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00008114 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008115 } else {
8116 auto it = move_table_.find(translated_method);
8117 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008118 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008119
8120 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008121 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008122 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008123 if (kIsDebugBuild) {
8124 auto* methods = klass_->GetMethodsPtr();
8125 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008126 reinterpret_cast<uintptr_t>(translated_method));
8127 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008128 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8129 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008130 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008131 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008132 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008133 }
8134 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008135 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008136 return vtable;
8137}
8138
8139void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8140 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8141 const size_t ifcount = klass_->GetIfTableCount();
8142 // Go fix up all the stale iftable pointers.
8143 for (size_t i = 0; i < ifcount; ++i) {
8144 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008145 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8146 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008147 DCHECK(m != nullptr) << klass_->PrettyClass();
8148 auto it = move_table_.find(m);
8149 if (it != move_table_.end()) {
8150 auto* new_m = it->second;
8151 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8152 method_array->SetElementPtrSize(j, new_m, pointer_size);
8153 }
8154 }
8155 }
8156}
8157
8158void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8159 // Fix up IMT next.
8160 for (size_t i = 0; i < ImTable::kSize; ++i) {
8161 auto it = move_table_.find(out_imt[i]);
8162 if (it != move_table_.end()) {
8163 out_imt[i] = it->second;
8164 }
8165 }
8166}
8167
Alex Light705ad492015-09-21 11:36:30 -07008168// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008169bool ClassLinker::LinkInterfaceMethods(
8170 Thread* self,
8171 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07008172 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008173 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008174 ArtMethod** out_imt) {
8175 StackHandleScope<3> hs(self);
8176 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008177
8178 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008179 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008180 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008181 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008182 const size_t ifcount = klass->GetIfTableCount();
8183
Vladimir Marko921094a2017-01-12 18:37:06 +00008184 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008185
8186 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8187 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008188 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008189 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008190 const bool extend_super_iftable = has_superclass;
8191 if (has_superclass && fill_tables) {
8192 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008193 unimplemented_method,
8194 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008195 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008196 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008197 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008198 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8199 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008200 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008201 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8202 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008203 }
8204 }
8205
Vladimir Marko921094a2017-01-12 18:37:06 +00008206 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8207
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008208 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008209 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008210 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8211 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8212 // they will already be null. This has the additional benefit that the declarer of a miranda
8213 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008214 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008215 --i;
Alex Light9139e002015-10-09 15:59:48 -07008216 DCHECK_LT(i, ifcount);
8217
Alex Light705ad492015-09-21 11:36:30 -07008218 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008219 if (num_methods > 0) {
8220 StackHandleScope<2> hs2(self);
8221 const bool is_super = i < super_ifcount;
8222 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008223 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8224 // conflict methods. Just set this as nullptr in those cases.
8225 Handle<mirror::PointerArray> method_array(fill_tables
8226 ? hs2.NewHandle(iftable->GetMethodArray(i))
8227 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008228
Alex Lighte64300b2015-12-15 15:02:47 -08008229 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008230 ScopedNullHandle<mirror::PointerArray> null_handle;
8231 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008232 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008233
Alex Light9139e002015-10-09 15:59:48 -07008234 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8235 // and confusing. Default methods should always look through all the superclasses
8236 // because they are the last choice of an implementation. We get around this by looking
8237 // at the super-classes iftable methods (copied into method_array previously) when we are
8238 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008239 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008240 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008241 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008242 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008243 using_virtuals = true;
Alex Lighta467a6e2020-03-23 16:07:29 -07008244 input_virtual_methods = klass->GetDeclaredVirtualMethodsSlice(image_pointer_size_);
Alex Lighte64300b2015-12-15 15:02:47 -08008245 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008246 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008247 // For a new interface, however, we need the whole vtable in case a new
8248 // interface method is implemented in the whole superclass.
8249 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008250 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008251 input_vtable_array = vtable;
8252 input_array_length = input_vtable_array->GetLength();
8253 }
Alex Lighte64300b2015-12-15 15:02:47 -08008254
Alex Lighteb7c1442015-08-31 13:17:42 -07008255 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008256 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008257 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008258 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008259 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008260 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008261 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008262 // For each method listed in the interface's method list, find the
8263 // matching method in our class's method list. We want to favor the
8264 // subclass over the superclass, which just requires walking
8265 // back from the end of the vtable. (This only matters if the
8266 // superclass defines a private method and this class redefines
8267 // it -- otherwise it would use the same vtable slot. In .dex files
8268 // those don't end up in the virtual method table, so it shouldn't
8269 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008270 //
8271 // To find defaults we need to do the same but also go over interfaces.
8272 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008273 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008274 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008275 ArtMethod* vtable_method = using_virtuals ?
8276 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008277 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8278 ArtMethod* vtable_method_for_name_comparison =
8279 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Alex Lighta467a6e2020-03-23 16:07:29 -07008280 DCHECK(!vtable_method->IsStatic()) << vtable_method->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008281 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008282 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008283 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008284 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8285 // allocations.
8286 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008287 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008288 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008289 vtable_method->PrettyMethod().c_str(),
8290 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008291 return false;
Alex Light9139e002015-10-09 15:59:48 -07008292 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008293 // We might have a newer, better, default method for this, so we just skip it. If we
8294 // are still using this we will select it again when scanning for default methods. To
8295 // obviate the need to copy the method again we will make a note that we already found
8296 // a default here.
8297 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008298 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008299 break;
8300 } else {
8301 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008302 if (LIKELY(fill_tables)) {
8303 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8304 // Place method in imt if entry is empty, place conflict otherwise.
8305 SetIMTRef(unimplemented_method,
8306 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008307 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008308 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008309 /*out*/imt_ptr);
8310 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008311 break;
8312 }
8313 }
Alex Light9139e002015-10-09 15:59:48 -07008314 }
8315 // Continue on to the next method if we are done.
8316 if (LIKELY(found_impl)) {
8317 continue;
8318 } else if (LIKELY(super_interface)) {
8319 // Don't look for a default implementation when the super-method is implemented directly
8320 // by the class.
8321 //
8322 // See if we can use the superclasses method and skip searching everything else.
8323 // Note: !found_impl && super_interface
8324 CHECK(extend_super_iftable);
8325 // If this is a super_interface method it is possible we shouldn't override it because a
8326 // superclass could have implemented it directly. We get the method the superclass used
8327 // to implement this to know if we can override it with a default method. Doing this is
8328 // safe since we know that the super_iftable is filled in so we can simply pull it from
8329 // there. We don't bother if this is not a super-classes interface since in that case we
8330 // have scanned the entire vtable anyway and would have found it.
8331 // TODO This is rather dirty but it is faster than searching through the entire vtable
8332 // every time.
8333 ArtMethod* supers_method =
8334 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8335 DCHECK(supers_method != nullptr);
8336 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008337 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008338 // The method is not overridable by a default method (i.e. it is directly implemented
8339 // in some class). Therefore move onto the next interface method.
8340 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008341 } else {
8342 // If the super-classes method is override-able by a default method we need to keep
8343 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8344 // 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 -07008345 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8346 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8347 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008348 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008349 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8350 << " and not 'nullptr' or "
8351 << supers_method->PrettyMethod()
8352 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008353 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008354 }
8355 }
8356 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008357 ArtMethod* current_method = helper.FindMethod(interface_method,
8358 interface_name_comparator,
8359 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008360 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008361 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008362 // We could not find an implementation for this method and since it is a brand new
8363 // interface we searched the entire vtable (and all default methods) for an
8364 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008365 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8366 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008367 }
8368
8369 if (current_method != nullptr) {
8370 // We found a default method implementation. Record it in the iftable and IMT.
8371 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8372 SetIMTRef(unimplemented_method,
8373 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008374 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008375 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008376 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008377 }
8378 }
Alex Light705ad492015-09-21 11:36:30 -07008379 } // For each method in interface end.
8380 } // if (num_methods > 0)
8381 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008382 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008383 if (helper.HasNewVirtuals()) {
8384 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8385 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8386 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8387
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008388 // 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 -07008389 // suspension assert.
8390 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008391
Alex Light705ad492015-09-21 11:36:30 -07008392 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008393 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008394 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008395 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008396 return false;
8397 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008398 helper.UpdateIfTable(iftable);
8399 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008400 }
Alex Light705ad492015-09-21 11:36:30 -07008401
Vladimir Marko921094a2017-01-12 18:37:06 +00008402 helper.CheckNoStaleMethodsInDexCache();
8403 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008404 } else {
8405 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008406 }
Alex Light705ad492015-09-21 11:36:30 -07008407 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008408 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008409 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008410 return true;
8411}
8412
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008413bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008414 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008415 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008416}
8417
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008418bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008419 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008420 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008421}
8422
Brian Carlstromdbc05252011-09-09 01:59:59 -07008423struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008424 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008425 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008426 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008427 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008428 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008429 // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008430 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8431 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008432 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008433 if (type1 == Primitive::kPrimNot) {
8434 // Reference always goes first.
8435 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008436 }
Vladimir Markod5777482014-11-12 17:02:02 +00008437 if (type2 == Primitive::kPrimNot) {
8438 // Reference always goes first.
8439 return false;
8440 }
8441 size_t size1 = Primitive::ComponentSize(type1);
8442 size_t size2 = Primitive::ComponentSize(type2);
8443 if (size1 != size2) {
8444 // Larger primitive types go first.
8445 return size1 > size2;
8446 }
8447 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8448 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008449 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008450 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8451 // by name and for equal names by type id index.
8452 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8453 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008454 }
8455};
8456
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008457bool ClassLinker::LinkFields(Thread* self,
8458 Handle<mirror::Class> klass,
8459 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008460 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008461 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008462 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008463 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8464 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008465
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008466 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008467 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008468 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008469 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008470 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008471 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008472 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008473 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008474 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008475 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008476 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008477 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008478
David Sehr709b0702016-10-13 09:12:37 -07008479 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008480
Brian Carlstromdbc05252011-09-09 01:59:59 -07008481 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008482 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008483 //
8484 // The overall sort order order is:
8485 // 1) All object reference fields, sorted alphabetically.
8486 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8487 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8488 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8489 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8490 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8491 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8492 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8493 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8494 //
8495 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8496 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008497 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008498 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008499 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008500 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008501 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008502 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008503 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8504 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008505
Fred Shih381e4ca2014-08-25 17:24:27 -07008506 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008507 size_t current_field = 0;
8508 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008509 FieldGaps gaps;
8510
Brian Carlstromdbc05252011-09-09 01:59:59 -07008511 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008512 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008513 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008514 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008515 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008516 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008517 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008518 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8519 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008520 MemberOffset old_offset = field_offset;
8521 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8522 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8523 }
Roland Levillain14d90572015-07-16 10:52:26 +01008524 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008525 grouped_and_sorted_fields.pop_front();
8526 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008527 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008528 field_offset = MemberOffset(field_offset.Uint32Value() +
8529 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008530 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008531 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8532 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008533 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8534 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8535 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8536 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008537 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8538 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008539 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008540
Elliott Hughesadb460d2011-10-05 17:02:34 -07008541 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07008542 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008543 // We know there are no non-reference fields in the Reference classes, and we know
8544 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008545 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008546 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008547 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008548 --num_reference_fields;
8549 }
8550
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008551 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008552 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008553 if (is_static) {
8554 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008555 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008556 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008557 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008558 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008559 if (num_reference_fields == 0 || super_class == nullptr) {
8560 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008561 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008562 if (super_class == nullptr ||
8563 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8564 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008565 }
8566 }
8567 if (kIsDebugBuild) {
8568 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8569 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008570 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008571 while (cur_super != nullptr) {
8572 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8573 cur_super = cur_super->GetSuperClass();
8574 }
8575 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008576 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008577 } else {
8578 // Check that there is at least num_reference_fields other than Object.class.
8579 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008580 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008581 }
8582 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008583 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008584 std::string temp;
8585 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8586 size_t previous_size = klass->GetObjectSize();
8587 if (previous_size != 0) {
8588 // Make sure that we didn't originally have an incorrect size.
8589 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008590 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008591 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008592 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008593 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008594
8595 if (kIsDebugBuild) {
8596 // Make sure that the fields array is ordered by name but all reference
8597 // offsets are at the beginning as far as alignment allows.
8598 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008599 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008600 : klass->GetFirstReferenceInstanceFieldOffset();
8601 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8602 num_reference_fields *
8603 sizeof(mirror::HeapReference<mirror::Object>));
8604 MemberOffset current_ref_offset = start_ref_offset;
8605 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008606 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008607 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008608 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8609 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008610 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008611 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008612 // NOTE: The field names can be the same. This is not possible in the Java language
8613 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008614 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008615 }
8616 Primitive::Type type = field->GetTypeAsPrimitiveType();
8617 bool is_primitive = type != Primitive::kPrimNot;
8618 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8619 strcmp("referent", field->GetName()) == 0) {
8620 is_primitive = true; // We lied above, so we have to expect a lie here.
8621 }
8622 MemberOffset offset = field->GetOffsetDuringLinking();
8623 if (is_primitive) {
8624 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8625 // Shuffled before references.
8626 size_t type_size = Primitive::ComponentSize(type);
8627 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8628 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8629 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8630 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8631 }
8632 } else {
8633 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8634 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8635 sizeof(mirror::HeapReference<mirror::Object>));
8636 }
8637 }
8638 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8639 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008640 return true;
8641}
8642
Vladimir Marko76649e82014-11-10 18:32:59 +00008643// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008644void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008645 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008646 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008647 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008648 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008649 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008650 // Compute reference offsets unless our superclass overflowed.
8651 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8652 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008653 if (num_reference_fields != 0u) {
8654 // All of the fields that contain object references are guaranteed be grouped in memory
8655 // starting at an appropriately aligned address after super class object data.
8656 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8657 sizeof(mirror::HeapReference<mirror::Object>));
8658 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008659 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008660 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008661 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008662 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008663 reference_offsets |= (0xffffffffu << start_bit) &
8664 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008665 }
8666 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008667 }
8668 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008669 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008670}
8671
Vladimir Marko18090d12018-06-01 16:53:12 +01008672ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8673 ObjPtr<mirror::DexCache> dex_cache) {
8674 StackHandleScope<1> hs(Thread::Current());
8675 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8676 return DoResolveString(string_idx, h_dex_cache);
8677}
8678
8679ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8680 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008681 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008682 uint32_t utf16_length;
8683 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008684 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008685 if (string != nullptr) {
8686 dex_cache->SetResolvedString(string_idx, string);
8687 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008688 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008689}
8690
Vladimir Marko18090d12018-06-01 16:53:12 +01008691ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8692 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008693 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008694 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008695 uint32_t utf16_length;
8696 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008697 ObjPtr<mirror::String> string =
8698 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008699 if (string != nullptr) {
8700 dex_cache->SetResolvedString(string_idx, string);
8701 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008702 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008703}
8704
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008705ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008706 ObjPtr<mirror::Class> referrer) {
8707 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8708}
8709
8710ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008711 ObjPtr<mirror::DexCache> dex_cache,
8712 ObjPtr<mirror::ClassLoader> class_loader) {
8713 const DexFile& dex_file = *dex_cache->GetDexFile();
8714 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8715 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8716 ObjPtr<mirror::Class> type = nullptr;
8717 if (descriptor[1] == '\0') {
8718 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8719 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008720 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008721 } else {
8722 Thread* const self = Thread::Current();
8723 DCHECK(self != nullptr);
8724 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8725 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008726 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008727 }
8728 if (type != nullptr) {
8729 if (type->IsResolved()) {
8730 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008731 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008732 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008733 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008734 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008735 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008736}
8737
Andreas Gampeb0625e02019-05-01 12:43:31 -07008738template <typename RefType>
8739ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008740 StackHandleScope<2> hs(Thread::Current());
8741 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8742 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8743 return DoResolveType(type_idx, dex_cache, class_loader);
8744}
8745
Andreas Gampe4835d212018-11-21 14:55:10 -08008746// Instantiate the above.
8747template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8748 ArtField* referrer);
8749template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8750 ArtMethod* referrer);
8751template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8752 ObjPtr<mirror::Class> referrer);
8753
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008754ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008755 Handle<mirror::DexCache> dex_cache,
8756 Handle<mirror::ClassLoader> class_loader) {
8757 Thread* self = Thread::Current();
8758 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8759 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8760 if (resolved != nullptr) {
8761 // TODO: we used to throw here if resolved's class loader was not the
8762 // boot class loader. This was to permit different classes with the
8763 // same name to be loaded simultaneously by different loaders
8764 dex_cache->SetResolvedType(type_idx, resolved);
8765 } else {
8766 CHECK(self->IsExceptionPending())
8767 << "Expected pending exception for failed resolution of: " << descriptor;
8768 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8769 StackHandleScope<1> hs(self);
8770 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008771 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008772 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8773 self->ClearException();
8774 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8775 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008776 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008777 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008778 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008779 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008780 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008781}
8782
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008783ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8784 ObjPtr<mirror::DexCache> dex_cache,
8785 ObjPtr<mirror::ClassLoader> class_loader,
8786 uint32_t method_idx) {
8787 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8788 // functions can optimize the search if the dex_cache is the same as the DexCache
8789 // of the class, with fall-back to name and signature search otherwise.
8790 ArtMethod* resolved = nullptr;
8791 if (klass->IsInterface()) {
8792 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8793 } else {
8794 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8795 }
8796 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008797 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008798 hiddenapi::ShouldDenyAccessToMember(resolved,
8799 hiddenapi::AccessContext(class_loader, dex_cache),
8800 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008801 resolved = nullptr;
8802 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008803 if (resolved != nullptr) {
8804 // In case of jmvti, the dex file gets verified before being registered, so first
8805 // check if it's registered before checking class tables.
8806 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008807 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8808 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008809 << "DexFile referrer: " << dex_file.GetLocation()
8810 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8811 // Be a good citizen and update the dex cache to speed subsequent calls.
8812 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008813 // Disable the following invariant check as the verifier breaks it. b/73760543
8814 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8815 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8816 // << "Method: " << resolved->PrettyMethod() << ", "
8817 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8818 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008819 }
8820 return resolved;
8821}
8822
David Brazdil4525e0b2018-04-05 16:57:32 +01008823// Returns true if `method` is either null or hidden.
8824// Does not print any warnings if it is hidden.
8825static bool CheckNoSuchMethod(ArtMethod* method,
8826 ObjPtr<mirror::DexCache> dex_cache,
8827 ObjPtr<mirror::ClassLoader> class_loader)
8828 REQUIRES_SHARED(Locks::mutator_lock_) {
8829 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008830 hiddenapi::ShouldDenyAccessToMember(method,
8831 hiddenapi::AccessContext(class_loader, dex_cache),
8832 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008833}
8834
8835ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8836 ObjPtr<mirror::DexCache> dex_cache,
8837 ObjPtr<mirror::ClassLoader> class_loader,
8838 uint32_t method_idx) {
8839 if (klass->IsInterface()) {
8840 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8841 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8842 } else {
8843 // If there was an interface method with the same signature, we would have
8844 // found it in the "copied" methods. Only DCHECK that the interface method
8845 // really does not exist.
8846 if (kIsDebugBuild) {
8847 ArtMethod* method =
8848 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8849 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8850 }
8851 return nullptr;
8852 }
8853}
8854
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008855template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008856ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008857 Handle<mirror::DexCache> dex_cache,
8858 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008859 ArtMethod* referrer,
8860 InvokeType type) {
Nicolas Geoffray605c5912020-04-08 15:12:39 +01008861 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Andreas Gampefa4333d2017-02-14 11:10:34 -08008862 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008863 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008864 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008865 PointerSize pointer_size = image_pointer_size_;
8866 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008867 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008868 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8869 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008870 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8871 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008872 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008873 return resolved;
8874 }
Vladimir Marko89011192017-12-11 13:45:05 +00008875 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008876 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008877 ObjPtr<mirror::Class> klass = nullptr;
8878 if (valid_dex_cache_method) {
8879 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8880 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008881 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008882 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008883 // We normaly should not end up here. However the verifier currently doesn't guarantee
8884 // the invariant of having the klass in the class table. b/73760543
8885 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Nicolas Geoffray07614192020-04-28 17:31:31 +01008886 if (klass == nullptr) {
8887 // This can only happen if the current thread is not allowed to load
8888 // classes.
8889 DCHECK(!Thread::Current()->CanLoadClasses());
8890 DCHECK(Thread::Current()->IsExceptionPending());
8891 return nullptr;
8892 }
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008893 }
Vladimir Markoba118822017-06-12 15:41:56 +01008894 } else {
8895 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008896 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008897 if (klass == nullptr) {
8898 DCHECK(Thread::Current()->IsExceptionPending());
8899 return nullptr;
8900 }
8901 }
8902
8903 // Check if the invoke type matches the class type.
8904 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008905 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008906 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008907 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008908 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008909 }
Vladimir Markoba118822017-06-12 15:41:56 +01008910
8911 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008912 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008913 }
Vladimir Markoba118822017-06-12 15:41:56 +01008914
8915 // Note: We can check for IllegalAccessError only if we have a referrer.
8916 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8917 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8918 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8919 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8920 resolved,
8921 dex_cache.Get(),
8922 method_idx,
8923 type)) {
8924 DCHECK(Thread::Current()->IsExceptionPending());
8925 return nullptr;
8926 }
8927 }
8928
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008929 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008930 if (LIKELY(resolved != nullptr) &&
8931 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8932 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008933 return resolved;
8934 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008935 // If we had a method, or if we can find one with another lookup type,
8936 // it's an incompatible-class-change error.
8937 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008938 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008939 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008940 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008941 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008942 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008943 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008944 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8945 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008946 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008947 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008948 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008949 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008950 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008951}
8952
Vladimir Marko89011192017-12-11 13:45:05 +00008953ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008954 Handle<mirror::DexCache> dex_cache,
8955 Handle<mirror::ClassLoader> class_loader) {
8956 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008957 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008958 if (resolved != nullptr) {
8959 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008960 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8961 return resolved;
8962 }
8963 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008964 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008965 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008966 if (klass == nullptr) {
8967 Thread::Current()->AssertPendingException();
8968 return nullptr;
8969 }
8970 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008971 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8972 } else {
8973 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008974 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008975 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008976 hiddenapi::ShouldDenyAccessToMember(
8977 resolved,
8978 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8979 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008980 resolved = nullptr;
8981 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008982 return resolved;
8983}
8984
Vladimir Markof44d36c2017-03-14 14:18:46 +00008985ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8986 ObjPtr<mirror::DexCache> dex_cache,
8987 ObjPtr<mirror::ClassLoader> class_loader,
8988 bool is_static) {
8989 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008990 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008991 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8992 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008993 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008994 }
8995 if (klass == nullptr) {
8996 // The class has not been resolved yet, so the field is also unresolved.
8997 return nullptr;
8998 }
8999 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009000
David Brazdil1ab0fa82018-05-04 11:28:03 +01009001 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009002}
9003
Vladimir Markoe11dd502017-12-08 14:09:45 +00009004ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009005 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009006 Handle<mirror::ClassLoader> class_loader,
9007 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009008 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayf3688822020-03-25 15:04:03 +00009009 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07009010 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009011 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009012 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009013 return resolved;
9014 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009015 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009016 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009017 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009018 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08009019 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07009020 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009021 }
9022
David Brazdil1ab0fa82018-05-04 11:28:03 +01009023 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07009024 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08009025 const char* name = dex_file.GetFieldName(field_id);
9026 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009027 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009028 }
Ian Rogersb067ac22011-12-13 18:05:09 -08009029 return resolved;
9030}
9031
Vladimir Markoe11dd502017-12-08 14:09:45 +00009032ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009033 Handle<mirror::DexCache> dex_cache,
9034 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009035 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009036 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009037 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009038 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009039 return resolved;
9040 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009041 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009042 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009043 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009044 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009045 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009046 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009047 }
9048
David Brazdil1ab0fa82018-05-04 11:28:03 +01009049 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9050 if (resolved == nullptr) {
9051 const char* name = dex_file.GetFieldName(field_id);
9052 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009053 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009054 }
9055 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009056}
9057
David Brazdil1ab0fa82018-05-04 11:28:03 +01009058ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9059 ObjPtr<mirror::DexCache> dex_cache,
9060 ObjPtr<mirror::ClassLoader> class_loader,
9061 uint32_t field_idx,
9062 bool is_static) {
9063 ArtField* resolved = nullptr;
9064 Thread* self = is_static ? Thread::Current() : nullptr;
9065 const DexFile& dex_file = *dex_cache->GetDexFile();
9066
9067 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
9068 : klass->FindInstanceField(dex_cache, field_idx);
9069
9070 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009071 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009072 const char* name = dex_file.GetFieldName(field_id);
9073 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9074 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
9075 : klass->FindInstanceField(name, type);
9076 }
9077
9078 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009079 hiddenapi::ShouldDenyAccessToMember(resolved,
9080 hiddenapi::AccessContext(class_loader, dex_cache),
9081 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009082 resolved = nullptr;
9083 }
9084
9085 if (resolved != nullptr) {
9086 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9087 }
9088
9089 return resolved;
9090}
9091
9092ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9093 ObjPtr<mirror::DexCache> dex_cache,
9094 ObjPtr<mirror::ClassLoader> class_loader,
9095 uint32_t field_idx) {
9096 ArtField* resolved = nullptr;
9097 Thread* self = Thread::Current();
9098 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009099 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009100
9101 const char* name = dex_file.GetFieldName(field_id);
9102 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9103 resolved = mirror::Class::FindField(self, klass, name, type);
9104
9105 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009106 hiddenapi::ShouldDenyAccessToMember(resolved,
9107 hiddenapi::AccessContext(class_loader, dex_cache),
9108 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009109 resolved = nullptr;
9110 }
9111
9112 if (resolved != nullptr) {
9113 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9114 }
9115
9116 return resolved;
9117}
9118
Vladimir Markoaf940202017-12-08 15:01:18 +00009119ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9120 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009121 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009122 Handle<mirror::DexCache> dex_cache,
9123 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009124 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009125 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009126
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009127 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009128 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009129 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009130 }
9131
Narayan Kamath25352fc2016-08-03 12:46:58 +01009132 StackHandleScope<4> hs(self);
9133
9134 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009135 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009136 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009137 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009138 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009139 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009140 DCHECK(self->IsExceptionPending());
9141 return nullptr;
9142 }
9143
9144 // Then resolve the argument types.
9145 //
9146 // TODO: Is there a better way to figure out the number of method arguments
9147 // other than by looking at the shorty ?
9148 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9149
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009150 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009151 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9152 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009153 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009154 DCHECK(self->IsExceptionPending());
9155 return nullptr;
9156 }
9157
9158 DexFileParameterIterator it(dex_file, proto_id);
9159 int32_t i = 0;
9160 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9161 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009162 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009163 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009164 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009165 DCHECK(self->IsExceptionPending());
9166 return nullptr;
9167 }
9168
9169 method_params->Set(i++, param_class.Get());
9170 }
9171
9172 DCHECK(!it.HasNext());
9173
9174 Handle<mirror::MethodType> type = hs.NewHandle(
9175 mirror::MethodType::Create(self, return_type, method_params));
9176 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9177
9178 return type.Get();
9179}
9180
Vladimir Markoaf940202017-12-08 15:01:18 +00009181ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009182 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009183 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009184 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009185 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9186 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009187 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009188}
9189
Vladimir Marko5aead702019-03-27 11:00:36 +00009190ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009191 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009192 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009193 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009194 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009195 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9196 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009197 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009198 bool is_static;
9199 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009200 switch (handle_type) {
9201 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009202 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009203 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009204 is_static = true;
9205 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009206 break;
9207 }
9208 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009209 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009210 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009211 is_static = true;
9212 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009213 break;
9214 }
9215 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009216 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009217 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009218 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009219 num_params = 2;
9220 break;
9221 }
9222 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009223 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009224 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009225 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009226 num_params = 1;
9227 break;
9228 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009229 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009230 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009231 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009232 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009233 case DexFile::MethodHandleType::kInvokeInterface:
9234 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009235 }
9236
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009237 ArtField* target_field =
9238 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9239 if (LIKELY(target_field != nullptr)) {
9240 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9241 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9242 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9243 ThrowIllegalAccessErrorField(referring_class, target_field);
9244 return nullptr;
9245 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009246 if (UNLIKELY(is_put && target_field->IsFinal())) {
9247 ThrowIllegalAccessErrorField(referring_class, target_field);
9248 return nullptr;
9249 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009250 } else {
9251 DCHECK(Thread::Current()->IsExceptionPending());
9252 return nullptr;
9253 }
9254
9255 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009256 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009257 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9258 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009259 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009260 DCHECK(self->IsExceptionPending());
9261 return nullptr;
9262 }
9263
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009264 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009265 Handle<mirror::Class> return_type;
9266 switch (handle_type) {
9267 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009268 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009269 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009270 break;
9271 }
9272 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009273 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009274 break;
9275 }
9276 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009277 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009278 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009279 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009280 break;
9281 }
9282 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009283 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009284 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009285 break;
9286 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009287 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009288 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009289 case DexFile::MethodHandleType::kInvokeConstructor:
9290 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009291 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009292 UNREACHABLE();
9293 }
9294
9295 for (int32_t i = 0; i < num_params; ++i) {
9296 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9297 DCHECK(self->IsExceptionPending());
9298 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009299 }
9300 }
9301
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009302 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009303 DCHECK(self->IsExceptionPending());
9304 return nullptr;
9305 }
9306
9307 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009308 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9309 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009310 DCHECK(self->IsExceptionPending());
9311 return nullptr;
9312 }
Orion Hodson631827d2017-04-10 14:53:47 +01009313
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009314 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9315 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9316}
9317
Vladimir Marko5aead702019-03-27 11:00:36 +00009318ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009319 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009320 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009321 ArtMethod* referrer) {
9322 DexFile::MethodHandleType handle_type =
9323 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9324 mirror::MethodHandle::Kind kind;
9325 uint32_t receiver_count = 0;
9326 ArtMethod* target_method = nullptr;
9327 switch (handle_type) {
9328 case DexFile::MethodHandleType::kStaticPut:
9329 case DexFile::MethodHandleType::kStaticGet:
9330 case DexFile::MethodHandleType::kInstancePut:
9331 case DexFile::MethodHandleType::kInstanceGet:
9332 UNREACHABLE();
9333 case DexFile::MethodHandleType::kInvokeStatic: {
9334 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9335 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009336 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9337 method_handle.field_or_method_idx_,
9338 referrer,
9339 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009340 break;
9341 }
9342 case DexFile::MethodHandleType::kInvokeInstance: {
9343 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9344 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009345 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9346 method_handle.field_or_method_idx_,
9347 referrer,
9348 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009349 break;
9350 }
9351 case DexFile::MethodHandleType::kInvokeConstructor: {
9352 // Constructors are currently implemented as a transform. They
9353 // are special cased later in this method.
9354 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9355 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009356 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9357 method_handle.field_or_method_idx_,
9358 referrer,
9359 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009360 break;
9361 }
9362 case DexFile::MethodHandleType::kInvokeDirect: {
9363 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9364 receiver_count = 1;
9365 StackHandleScope<2> hs(self);
9366 // A constant method handle with type kInvokeDirect can refer to
9367 // a method that is private or to a method in a super class. To
9368 // disambiguate the two options, we resolve the method ignoring
9369 // the invocation type to determine if the method is private. We
9370 // then resolve again specifying the intended invocation type to
9371 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009372 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009373 hs.NewHandle(referrer->GetDexCache()),
9374 hs.NewHandle(referrer->GetClassLoader()));
9375 if (UNLIKELY(target_method == nullptr)) {
9376 break;
9377 }
9378
9379 if (target_method->IsPrivate()) {
9380 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009381 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9382 method_handle.field_or_method_idx_,
9383 referrer,
9384 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009385 } else {
9386 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009387 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9388 method_handle.field_or_method_idx_,
9389 referrer,
9390 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009391 if (UNLIKELY(target_method == nullptr)) {
9392 break;
9393 }
9394 // Find the method specified in the parent in referring class
9395 // so invoke-super invokes the method in the parent of the
9396 // referrer.
9397 target_method =
9398 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9399 kRuntimePointerSize);
9400 }
9401 break;
9402 }
9403 case DexFile::MethodHandleType::kInvokeInterface: {
9404 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9405 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009406 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9407 method_handle.field_or_method_idx_,
9408 referrer,
9409 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009410 break;
9411 }
Orion Hodson631827d2017-04-10 14:53:47 +01009412 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009413
9414 if (UNLIKELY(target_method == nullptr)) {
9415 DCHECK(Thread::Current()->IsExceptionPending());
9416 return nullptr;
9417 }
9418
9419 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9420 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9421 uint32_t access_flags = target_method->GetAccessFlags();
9422 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9423 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9424 return nullptr;
9425 }
9426
9427 // Calculate the number of parameters from the method shorty. We add the
9428 // receiver count (0 or 1) and deduct one for the return value.
9429 uint32_t shorty_length;
9430 target_method->GetShorty(&shorty_length);
9431 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9432
Orion Hodsonecd58562018-09-24 11:27:33 +01009433 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009434 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009435 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9436 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9437 if (method_params.Get() == nullptr) {
9438 DCHECK(self->IsExceptionPending());
9439 return nullptr;
9440 }
9441
Orion Hodsonecd58562018-09-24 11:27:33 +01009442 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009443 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009444 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009445 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009446 // Insert receiver. Use the class identified in the method handle rather than the declaring
9447 // class of the resolved method which may be super class or default interface method
9448 // (b/115964401).
9449 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9450 // receiver_class should have been resolved when resolving the target method.
9451 DCHECK(receiver_class != nullptr);
9452 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009453 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009454
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009455 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009456 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009457 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009458 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009459 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009460 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009461 if (nullptr == klass) {
9462 DCHECK(self->IsExceptionPending());
9463 return nullptr;
9464 }
9465 method_params->Set(index++, klass);
9466 it.Next();
9467 }
9468
Orion Hodsonecd58562018-09-24 11:27:33 +01009469 Handle<mirror::Class> return_type =
9470 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009471 if (UNLIKELY(return_type.IsNull())) {
9472 DCHECK(self->IsExceptionPending());
9473 return nullptr;
9474 }
9475
9476 Handle<mirror::MethodType>
9477 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9478 if (UNLIKELY(method_type.IsNull())) {
9479 DCHECK(self->IsExceptionPending());
9480 return nullptr;
9481 }
9482
9483 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9484 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9485 Handle<mirror::MethodHandlesLookup> lookup =
9486 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9487 return lookup->FindConstructor(self, constructor_class, method_type);
9488 }
9489
9490 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9491 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9492}
9493
Vladimir Markoaf940202017-12-08 15:01:18 +00009494ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9495 uint32_t method_handle_idx,
9496 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009497 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009498 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009499 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009500 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9501 case DexFile::MethodHandleType::kStaticPut:
9502 case DexFile::MethodHandleType::kStaticGet:
9503 case DexFile::MethodHandleType::kInstancePut:
9504 case DexFile::MethodHandleType::kInstanceGet:
9505 return ResolveMethodHandleForField(self, method_handle, referrer);
9506 case DexFile::MethodHandleType::kInvokeStatic:
9507 case DexFile::MethodHandleType::kInvokeInstance:
9508 case DexFile::MethodHandleType::kInvokeConstructor:
9509 case DexFile::MethodHandleType::kInvokeDirect:
9510 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009511 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009512 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009513}
9514
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009515bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9516 return (entry_point == GetQuickResolutionStub()) ||
9517 (quick_resolution_trampoline_ == entry_point);
9518}
9519
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009520bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9521 return (entry_point == GetQuickToInterpreterBridge()) ||
9522 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9523}
9524
9525bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9526 return (entry_point == GetQuickGenericJniStub()) ||
9527 (quick_generic_jni_trampoline_ == entry_point);
9528}
9529
David Sehra49e0532017-08-25 08:05:29 -07009530bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009531 return entry_point == GetJniDlsymLookupStub() ||
9532 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009533}
9534
Vladimir Markofa458ac2020-02-12 14:08:07 +00009535bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9536 return entry_point == GetJniDlsymLookupCriticalStub() ||
9537 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9538}
9539
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009540const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9541 return GetQuickGenericJniStub();
9542}
9543
Mathieu Chartiere401d142015-04-22 13:56:20 -07009544void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009545 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009546 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9547 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009548 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009549 }
9550}
9551
Alex Lightdb01a092017-04-03 15:39:55 -07009552void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9553 DCHECK(method->IsObsolete());
9554 // We cannot mess with the entrypoints of native methods because they are used to determine how
9555 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9556 if (!method->IsNative()) {
9557 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9558 }
9559}
9560
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009561void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009562 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009563 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009564 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9565 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009566 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9567 os << "Dumping registered class loaders\n";
9568 size_t class_loader_index = 0;
9569 for (const ClassLoaderData& class_loader : class_loaders_) {
9570 ObjPtr<mirror::ClassLoader> loader =
9571 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9572 if (loader != nullptr) {
9573 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9574 bool saw_one_dex_file = false;
9575 for (const DexCacheData& dex_cache : dex_caches_) {
9576 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9577 if (saw_one_dex_file) {
9578 os << ":";
9579 }
9580 saw_one_dex_file = true;
9581 os << dex_cache.dex_file->GetLocation();
9582 }
9583 }
9584 os << "]";
9585 bool found_parent = false;
9586 if (loader->GetParent() != nullptr) {
9587 size_t parent_index = 0;
9588 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9589 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9590 soa.Self()->DecodeJObject(class_loader2.weak_root));
9591 if (loader2 == loader->GetParent()) {
9592 os << ", parent #" << parent_index;
9593 found_parent = true;
9594 break;
9595 }
9596 parent_index++;
9597 }
9598 if (!found_parent) {
9599 os << ", unregistered parent of type "
9600 << loader->GetParent()->GetClass()->PrettyDescriptor();
9601 }
9602 } else {
9603 os << ", no parent";
9604 }
9605 os << "\n";
9606 }
9607 }
9608 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009609 Runtime* runtime = Runtime::Current();
9610 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9611 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009612}
9613
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009614class CountClassesVisitor : public ClassLoaderVisitor {
9615 public:
9616 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9617
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009618 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009619 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009620 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009621 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009622 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9623 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009624 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009625 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009626
9627 size_t num_zygote_classes;
9628 size_t num_non_zygote_classes;
9629};
9630
9631size_t ClassLinker::NumZygoteClasses() const {
9632 CountClassesVisitor visitor;
9633 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009634 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009635}
9636
9637size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009638 CountClassesVisitor visitor;
9639 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009640 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009641}
9642
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009643size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009644 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009645 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009646 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009647}
9648
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009649pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009650 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009651}
9652
9653pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009654 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009655}
9656
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009657void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009658 DCHECK(!init_done_);
9659
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009660 DCHECK(klass != nullptr);
9661 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009662
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009663 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009664 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009665 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9666 int32_t index = static_cast<int32_t>(class_root);
9667 DCHECK(class_roots->Get(index) == nullptr);
9668 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009669}
9670
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009671ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9672 Thread* self,
9673 const std::vector<const DexFile*>& dex_files,
9674 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009675 Handle<mirror::ClassLoader> parent_loader,
9676 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009677
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009678 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009679
Mathieu Chartierc7853442015-03-27 14:35:38 -07009680 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009681 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009682
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009683 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009684 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009685 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009686 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009687 mirror::ObjectArray<mirror::Object>::Alloc(self,
9688 dex_elements_class.Get(),
9689 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009690 Handle<mirror::Class> h_dex_element_class =
9691 hs.NewHandle(dex_elements_class->GetComponentType());
9692
Mathieu Chartierc7853442015-03-27 14:35:38 -07009693 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009694 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009695 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009696
Andreas Gampe08883de2016-11-08 13:20:52 -08009697 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009698 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009699
Andreas Gampe08883de2016-11-08 13:20:52 -08009700 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009701 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009702
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009703 // Fill the elements array.
9704 int32_t index = 0;
9705 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009706 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009707
Calin Juravle7865ac72017-06-28 11:03:12 -07009708 // CreateWellKnownClassLoader is only used by gtests and compiler.
9709 // 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 -07009710 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9711 self,
9712 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009713 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009714 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009715
Mathieu Chartier3738e982017-05-12 16:07:28 -07009716 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9717 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009718 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009719 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009720 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009721 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009722
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009723 Handle<mirror::String> h_file_name = hs2.NewHandle(
9724 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009725 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009726 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9727
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009728 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009729 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009730 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009731
9732 h_dex_elements->Set(index, h_element.Get());
9733 index++;
9734 }
9735 DCHECK_EQ(index, h_dex_elements->GetLength());
9736
9737 // Create DexPathList.
9738 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009739 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009740 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009741 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009742 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009743 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9744 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9745 // elements.
9746 {
9747 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9748 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9749 DCHECK(native_lib_dirs != nullptr);
9750 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9751 DCHECK(list_class != nullptr);
9752 {
9753 StackHandleScope<1> h_list_scope(self);
9754 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9755 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9756 DCHECK(list_init);
9757 list_class = h_list_class.Get();
9758 }
9759 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9760 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9761 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9762 // normally never null), as long as one does not try to add elements, this will still
9763 // work.
9764 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9765 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009766
Calin Juravle7865ac72017-06-28 11:03:12 -07009767 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009768 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9769 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009770 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009771 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009772 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009773 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009774 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009775 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009776
9777 // Make a pretend boot-classpath.
9778 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009779 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009780 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009781 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009782 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009783 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009784 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009785 if (parent_loader.Get() == nullptr) {
9786 ScopedObjectAccessUnchecked soa(self);
9787 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9788 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9789 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9790 } else {
9791 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9792 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009793
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009794 ArtField* shared_libraries_field =
9795 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9796 DCHECK(shared_libraries_field != nullptr);
9797 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9798
9799 return h_class_loader.Get();
9800}
9801
9802jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9803 const std::vector<const DexFile*>& dex_files,
9804 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009805 jobject parent_loader,
9806 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009807 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9808 WellKnownClasses::dalvik_system_PathClassLoader) ||
9809 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009810 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9811 self->GetJniEnv()->IsSameObject(loader_class,
9812 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009813
9814 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9815 // We could move the jobject to the callers, but all call-sites do this...
9816 ScopedObjectAccessUnchecked soa(self);
9817
9818 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009819 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009820
9821 Handle<mirror::Class> h_loader_class =
9822 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009823 Handle<mirror::ClassLoader> h_parent =
9824 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9825 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9826 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009827
9828 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9829 self,
9830 dex_files,
9831 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009832 h_parent,
9833 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009834
9835 // Make it a global ref and return.
9836 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009837 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009838 return soa.Env()->NewGlobalRef(local_ref.get());
9839}
9840
Calin Juravle7865ac72017-06-28 11:03:12 -07009841jobject ClassLinker::CreatePathClassLoader(Thread* self,
9842 const std::vector<const DexFile*>& dex_files) {
9843 return CreateWellKnownClassLoader(self,
9844 dex_files,
9845 WellKnownClasses::dalvik_system_PathClassLoader,
9846 nullptr);
9847}
9848
Andreas Gampe8ac75952015-06-02 21:01:45 -07009849void ClassLinker::DropFindArrayClassCache() {
9850 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9851 find_array_class_cache_next_victim_ = 0;
9852}
9853
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009854void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009855 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009856 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009857 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009858 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9859 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009860 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009861 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009862 }
9863 }
9864}
9865
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009866void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9867 for (const ClassLoaderData& data : class_loaders_) {
9868 LinearAlloc* alloc = data.allocator;
9869 if (alloc != nullptr && !visitor->Visit(alloc)) {
9870 break;
9871 }
9872 }
9873}
9874
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009875void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9876 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009877 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009878 Thread* const self = Thread::Current();
9879 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009880 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009881 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009882 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009883 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9884 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009885 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009886 }
9887}
9888
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009889void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009890 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009891 std::vector<ClassLoaderData> to_delete;
9892 // Do the delete outside the lock to avoid lock violation in jit code cache.
9893 {
9894 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9895 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9896 const ClassLoaderData& data = *it;
9897 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009898 ObjPtr<mirror::ClassLoader> class_loader =
9899 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009900 if (class_loader != nullptr) {
9901 ++it;
9902 } else {
9903 VLOG(class_linker) << "Freeing class loader";
9904 to_delete.push_back(data);
9905 it = class_loaders_.erase(it);
9906 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009907 }
9908 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009909 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009910 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009911 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009912 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009913}
9914
Mathieu Chartier65975772016-08-05 10:46:36 -07009915class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9916 public:
9917 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9918 : method_(method),
9919 pointer_size_(pointer_size) {}
9920
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009921 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009922 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9923 holder_ = klass;
9924 }
9925 // Return false to stop searching if holder_ is not null.
9926 return holder_ == nullptr;
9927 }
9928
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009929 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009930 const ArtMethod* const method_;
9931 const PointerSize pointer_size_;
9932};
9933
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009934ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009935 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9936 CHECK(method->IsCopied());
9937 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9938 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009939 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009940}
9941
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009942ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9943 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009944 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009945 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009946 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009947}
9948
Vladimir Markod1f73512020-04-02 10:50:35 +01009949bool ClassLinker::IsUpdatableBootClassPathDescriptor(const char* descriptor ATTRIBUTE_UNUSED) {
9950 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
9951 LOG(FATAL) << "UNREACHABLE";
9952 UNREACHABLE();
9953}
9954
Roland Levillain0e840272018-08-23 19:55:30 +01009955// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009956template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009957 uint32_t method_idx,
9958 Handle<mirror::DexCache> dex_cache,
9959 Handle<mirror::ClassLoader> class_loader,
9960 ArtMethod* referrer,
9961 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009962template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009963 uint32_t method_idx,
9964 Handle<mirror::DexCache> dex_cache,
9965 Handle<mirror::ClassLoader> class_loader,
9966 ArtMethod* referrer,
9967 InvokeType type);
9968
Roland Levillain0e840272018-08-23 19:55:30 +01009969// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009970template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009971 Thread* self,
9972 ObjPtr<mirror::Class> java_lang_Class,
9973 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009974template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009975 Thread* self,
9976 ObjPtr<mirror::Class> java_lang_Class,
9977 uint32_t class_size);
9978
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009979} // namespace art