blob: 56ae30799f05219d72db83205d3baba11be34fc4 [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 Markob4eb1b12018-05-24 11:09:38 +010060#include "class_root.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"
Chris Wailes0c61be42018-09-26 17:27:34 -0700119#include "mirror/object_reference.h"
120#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800121#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700122#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800123#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700124#include "mirror/string-inl.h"
Andreas Gampe501c3b02019-04-17 21:54:27 +0000125#include "mirror/throwable.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100126#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700127#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700128#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700129#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700130#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700131#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700132#include "oat_file_assistant.h"
133#include "oat_file_manager.h"
134#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700135#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700136#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800137#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700138#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700139#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700140#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700141#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100142#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700143#include "verifier/class_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700144#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700145
Nicolas Geoffray00391822019-12-10 10:17:23 +0000146#include "interpreter/interpreter_mterp_impl.h"
147
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700148namespace art {
149
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800150using android::base::StringPrintf;
151
Mathieu Chartierc7853442015-03-27 14:35:38 -0700152static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700153static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700154
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155static void ThrowNoClassDefFoundError(const char* fmt, ...)
156 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700157 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700158static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700159 va_list args;
160 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800161 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000162 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800163 va_end(args);
164}
165
Andreas Gampe99babb62015-11-02 16:20:00 -0800166static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700167 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700168 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700169 StackHandleScope<1> hs(self);
170 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700171 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700172 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700173
174 if (exception_class == nullptr) {
175 // No exc class ~ no <init>-with-string.
176 CHECK(self->IsExceptionPending());
177 self->ClearException();
178 return false;
179 }
180
Vladimir Markoba118822017-06-12 15:41:56 +0100181 ArtMethod* exception_init_method = exception_class->FindConstructor(
182 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700183 return exception_init_method != nullptr;
184}
185
Vladimir Markobb206de2019-03-28 10:30:32 +0000186static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700187 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700188 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
189 if (ext == nullptr) {
190 return nullptr;
191 } else {
192 return ext->GetVerifyError();
193 }
194}
195
196// Helper for ThrowEarlierClassFailure. Throws the stored error.
197static void HandleEarlierVerifyError(Thread* self,
198 ClassLinker* class_linker,
199 ObjPtr<mirror::Class> c)
200 REQUIRES_SHARED(Locks::mutator_lock_) {
201 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800202 DCHECK(obj != nullptr);
203 self->AssertNoPendingException();
204 if (obj->IsClass()) {
205 // Previous error has been stored as class. Create a new exception of that type.
206
207 // It's possible the exception doesn't have a <init>(String).
208 std::string temp;
209 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
210
211 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700212 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800213 } else {
214 self->ThrowNewException(descriptor, nullptr);
215 }
216 } else {
217 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100218 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700219 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800220 CHECK(throwable_class->IsAssignableFrom(error_class));
221 self->SetException(obj->AsThrowable());
222 }
223 self->AssertPendingException();
224}
225
Andreas Gampe5b20b352018-10-11 19:03:20 -0700226// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
227// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
228// before.
Andreas Gampe5b20b352018-10-11 19:03:20 -0700229static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
230 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000231 Runtime* runtime = Runtime::Current();
232 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampe5b20b352018-10-11 19:03:20 -0700233 if (!klass->WasVerificationAttempted()) {
234 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
235 klass->SetVerificationAttempted();
Nicolas Geoffray00391822019-12-10 10:17:23 +0000236 // Now that the class has passed verification, try to set nterp entrypoints
237 // to methods that currently use the switch interpreter.
238 if (interpreter::CanRuntimeUseNterp()) {
239 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
240 if (class_linker->IsQuickToInterpreterBridge(m.GetEntryPointFromQuickCompiledCode()) &&
241 interpreter::CanMethodUseNterp(&m)) {
242 if (klass->IsVisiblyInitialized() || !NeedsClinitCheckBeforeCall(&m)) {
243 runtime->GetInstrumentation()->UpdateMethodsCode(&m, interpreter::GetNterpEntryPoint());
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +0000244 } else {
245 // Put the resolution stub, which will initialize the class and then
246 // call the method with nterp.
247 runtime->GetInstrumentation()->UpdateMethodsCode(&m, GetQuickResolutionStub());
Nicolas Geoffray00391822019-12-10 10:17:23 +0000248 }
249 }
250 }
251 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700252 }
253}
254
Vladimir Markobf121912019-06-04 13:49:05 +0100255// Callback responsible for making a batch of classes visibly initialized
256// after all threads have called it from a checkpoint, ensuring visibility.
257class ClassLinker::VisiblyInitializedCallback final
258 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
259 public:
260 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
261 : class_linker_(class_linker),
262 num_classes_(0u),
263 thread_visibility_counter_(0),
264 barriers_() {
265 std::fill_n(classes_, kMaxClasses, nullptr);
266 }
267
268 bool IsEmpty() const {
269 DCHECK_LE(num_classes_, kMaxClasses);
270 return num_classes_ == 0u;
271 }
272
273 bool IsFull() const {
274 DCHECK_LE(num_classes_, kMaxClasses);
275 return num_classes_ == kMaxClasses;
276 }
277
278 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
279 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
280 DCHECK(!IsFull());
281 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
282 ++num_classes_;
283 }
284
285 void AddBarrier(Barrier* barrier) {
286 barriers_.push_front(barrier);
287 }
288
289 std::forward_list<Barrier*> GetAndClearBarriers() {
290 std::forward_list<Barrier*> result;
291 result.swap(barriers_);
292 result.reverse(); // Return barriers in insertion order.
293 return result;
294 }
295
296 void MakeVisible(Thread* self) {
297 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
298 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
299 AdjustThreadVisibilityCounter(self, count);
300 }
301
302 void Run(Thread* self) override {
303 self->ClearMakeVisiblyInitializedCounter();
304 AdjustThreadVisibilityCounter(self, -1);
305 }
306
307 private:
308 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
309 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
310 if (old + adjustment == 0) {
311 // All threads passed the checkpoint. Mark classes as visibly initialized.
312 {
313 ScopedObjectAccess soa(self);
314 StackHandleScope<1u> hs(self);
315 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
316 JavaVMExt* vm = self->GetJniEnv()->GetVm();
317 for (size_t i = 0, num = num_classes_; i != num; ++i) {
318 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
319 vm->DeleteWeakGlobalRef(self, classes_[i]);
320 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100321 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Markocce414f2019-10-07 08:51:33 +0100322 class_linker_->FixupStaticTrampolines(klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100323 }
324 }
325 num_classes_ = 0u;
326 }
327 class_linker_->VisiblyInitializedCallbackDone(self, this);
328 }
329 }
330
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100331 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100332
333 ClassLinker* const class_linker_;
334 size_t num_classes_;
335 jweak classes_[kMaxClasses];
336
337 // The thread visibility counter starts at 0 and it is incremented by the number of
338 // threads that need to run this callback (by the thread that request the callback
339 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
340 // whether after the increment or after a decrement, we know that `Run()` was executed
341 // for all threads and therefore we can mark the classes as visibly initialized.
342 std::atomic<ssize_t> thread_visibility_counter_;
343
344 // List of barries to `Pass()` for threads that wait for the callback to complete.
345 std::forward_list<Barrier*> barriers_;
346};
347
348void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
349 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
350 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
351 }
352 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
353 if (wait) {
354 maybe_barrier.emplace(0);
355 }
356 int wait_count = 0;
357 VisiblyInitializedCallback* callback = nullptr;
358 {
359 MutexLock lock(self, visibly_initialized_callback_lock_);
360 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
361 callback = visibly_initialized_callback_.release();
362 running_visibly_initialized_callbacks_.push_front(*callback);
363 }
364 if (wait) {
365 DCHECK(maybe_barrier.has_value());
366 Barrier* barrier = std::addressof(*maybe_barrier);
367 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
368 cb.AddBarrier(barrier);
369 ++wait_count;
370 }
371 }
372 }
373 if (callback != nullptr) {
374 callback->MakeVisible(self);
375 }
376 if (wait_count != 0) {
377 DCHECK(maybe_barrier.has_value());
378 maybe_barrier->Increment(self, wait_count);
379 }
380}
381
382void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
383 VisiblyInitializedCallback* callback) {
384 MutexLock lock(self, visibly_initialized_callback_lock_);
385 // Pass the barriers if requested.
386 for (Barrier* barrier : callback->GetAndClearBarriers()) {
387 barrier->Pass(self);
388 }
389 // Remove the callback from the list of running callbacks.
390 auto before = running_visibly_initialized_callbacks_.before_begin();
391 auto it = running_visibly_initialized_callbacks_.begin();
392 DCHECK(it != running_visibly_initialized_callbacks_.end());
393 while (std::addressof(*it) != callback) {
394 before = it;
395 ++it;
396 DCHECK(it != running_visibly_initialized_callbacks_.end());
397 }
398 running_visibly_initialized_callbacks_.erase_after(before);
399 // Reuse or destroy the callback object.
400 if (visibly_initialized_callback_ == nullptr) {
401 visibly_initialized_callback_.reset(callback);
402 } else {
403 delete callback;
404 }
405}
406
Alex Lightfb119572019-09-18 15:04:53 -0700407void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
408 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
409 if (cb != nullptr) {
410 cb->MakeVisible(self);
411 }
412 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
413 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
414}
415
Vladimir Markobf121912019-06-04 13:49:05 +0100416ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
417 Thread* self, Handle<mirror::Class> klass) {
418 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
419 // Thanks to the x86 memory model, we do not need any memory fences and
420 // we can immediately mark the class as visibly initialized.
421 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Markocce414f2019-10-07 08:51:33 +0100422 FixupStaticTrampolines(klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100423 return nullptr;
424 }
425 if (Runtime::Current()->IsActiveTransaction()) {
426 // Transactions are single-threaded, so we can mark the class as visibly intialized.
427 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
428 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Markocce414f2019-10-07 08:51:33 +0100429 FixupStaticTrampolines(klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100430 return nullptr;
431 }
432 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
433 MutexLock lock(self, visibly_initialized_callback_lock_);
434 if (visibly_initialized_callback_ == nullptr) {
435 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
436 }
437 DCHECK(!visibly_initialized_callback_->IsFull());
438 visibly_initialized_callback_->AddClass(self, klass.Get());
439
440 if (visibly_initialized_callback_->IsFull()) {
441 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
442 running_visibly_initialized_callbacks_.push_front(*callback);
443 return callback;
444 } else {
445 return nullptr;
446 }
447}
448
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800449void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
450 bool wrap_in_no_class_def,
451 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700452 // The class failed to initialize on a previous attempt, so we want to throw
453 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
454 // failed in verification, in which case v2 5.4.1 says we need to re-throw
455 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800456 Runtime* const runtime = Runtime::Current();
457 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700458 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000459 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
460 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800461 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700462 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800463 } else {
464 extra = verify_error->AsThrowable()->Dump();
465 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700466 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800467 if (log) {
468 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
469 << ": " << extra;
470 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700471 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700472
David Sehr709b0702016-10-13 09:12:37 -0700473 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800474 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800475 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700476 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700477 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000478 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700479 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000480 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
481 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800482 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800483 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800484 }
Alex Lightd6251582016-10-31 11:12:30 -0700485 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
486 // might have meant to go down the earlier if statement with the original error but it got
487 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000488 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800489 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
490 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
491 // exception will be a cause.
492 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700493 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700494 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700495 }
496}
497
Brian Carlstromb23eab12014-10-08 17:55:21 -0700498static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700499 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700500 if (VLOG_IS_ON(class_linker)) {
501 std::string temp;
502 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000503 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700504 }
505}
506
507static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700508 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700509 Thread* self = Thread::Current();
510 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700511
512 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700513 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700514
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800515 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
516 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
517 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800518 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800519 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
520 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
521 // could have caused the error.
522 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
523 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
524 << " failed initialization: "
525 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800526 }
527
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700528 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700529 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
530 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700531
Elliott Hughesa4f94742012-05-29 16:28:38 -0700532 // We only wrap non-Error exceptions; an Error can just be used as-is.
533 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000534 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700535 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700536 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700537}
538
Fred Shih381e4ca2014-08-25 17:24:27 -0700539// Gap between two fields in object layout.
540struct FieldGap {
541 uint32_t start_offset; // The offset from the start of the object.
542 uint32_t size; // The gap size of 1, 2, or 4 bytes.
543};
544struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800545 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700546 }
547 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
548 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800549 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700550 // Note that the priority queue returns the largest element, so operator()
551 // should return true if lhs is less than rhs.
552 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700553 }
554};
Andreas Gampec55bb392018-09-21 00:02:02 +0000555using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700556
557// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800558static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700559 DCHECK(gaps != nullptr);
560
561 uint32_t current_offset = gap_start;
562 while (current_offset != gap_end) {
563 size_t remaining = gap_end - current_offset;
564 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
565 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
566 current_offset += sizeof(uint32_t);
567 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
568 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
569 current_offset += sizeof(uint16_t);
570 } else {
571 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
572 current_offset += sizeof(uint8_t);
573 }
574 DCHECK_LE(current_offset, gap_end) << "Overran gap";
575 }
576}
577// Shuffle fields forward, making use of gaps whenever possible.
578template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000579static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700580 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700581 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700582 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700583 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700584 DCHECK(current_field_idx != nullptr);
585 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700586 DCHECK(gaps != nullptr);
587 DCHECK(field_offset != nullptr);
588
589 DCHECK(IsPowerOfTwo(n));
590 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700591 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700592 Primitive::Type type = field->GetTypeAsPrimitiveType();
593 if (Primitive::ComponentSize(type) < n) {
594 break;
595 }
596 if (!IsAligned<n>(field_offset->Uint32Value())) {
597 MemberOffset old_offset = *field_offset;
598 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
599 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
600 }
David Sehr709b0702016-10-13 09:12:37 -0700601 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700602 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700603 if (!gaps->empty() && gaps->top().size >= n) {
604 FieldGap gap = gaps->top();
605 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100606 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700607 field->SetOffset(MemberOffset(gap.start_offset));
608 if (gap.size > n) {
609 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
610 }
611 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100612 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700613 field->SetOffset(*field_offset);
614 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
615 }
616 ++(*current_field_idx);
617 }
618}
619
Andreas Gampe87658f32019-04-18 18:39:02 +0000620ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700621 : boot_class_table_(new ClassTable()),
622 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800623 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800624 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700625 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000626 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700627 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000628 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000629 jni_dlsym_lookup_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800630 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800631 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100632 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800633 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700634 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100635 visibly_initialized_callback_lock_("visibly initialized callback lock"),
636 visibly_initialized_callback_(nullptr),
Andreas Gampe7dface32017-07-25 21:32:59 -0700637 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
638 // For CHA disabled during Aot, see b/34193647.
639
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700640 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700641 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
642 "Array cache size wrong.");
643 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700644}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700645
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800646void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700647 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800648 if (c2 == nullptr) {
649 LOG(FATAL) << "Could not find class " << descriptor;
650 UNREACHABLE();
651 }
652 if (c1.Get() != c2) {
653 std::ostringstream os1, os2;
654 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
655 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
656 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
657 << ". This is most likely the result of a broken build. Make sure that "
658 << "libcore and art projects match.\n\n"
659 << os1.str() << "\n\n" << os2.str();
660 UNREACHABLE();
661 }
662}
663
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800664bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
665 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800666 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700667
Mathieu Chartiere401d142015-04-22 13:56:20 -0700668 Thread* const self = Thread::Current();
669 Runtime* const runtime = Runtime::Current();
670 gc::Heap* const heap = runtime->GetHeap();
671
Jeff Haodcdc85b2015-12-04 14:06:18 -0800672 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700673 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700674
Mathieu Chartiere401d142015-04-22 13:56:20 -0700675 // Use the pointer size from the runtime since we are probably creating the image.
676 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
677
Elliott Hughes30646832011-10-13 16:59:46 -0700678 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700679 // 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 -0800680 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700681 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700682 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700683 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
684 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000685 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100686 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800687 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100688 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700689 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700690 if (kUseBakerReadBarrier) {
691 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800692 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700693 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700694 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800695 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700696 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700697
Elliott Hughes418d20f2011-09-22 14:00:39 -0700698 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700699 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700700 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700701 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700702 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700703
Ian Rogers23435d02012-09-24 11:23:12 -0700704 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700705 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700706 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800707 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700708 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700709 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000710 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700711
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700712 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800713 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
714 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100715 runtime->SetSentinel(heap->AllocNonMovableObject(self,
716 java_lang_Object.Get(),
717 java_lang_Object->GetObjectSize(),
718 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700719
Igor Murashkin86083f72017-10-27 10:59:04 -0700720 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000721 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700722 // It might seem the lock here is unnecessary, however all the SubtypeCheck
723 // functions are annotated to require locks all the way down.
724 //
725 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
726 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000727 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
728 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700729 }
730
Ian Rogers23435d02012-09-24 11:23:12 -0700731 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700732 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700733 AllocClass(self, java_lang_Class.Get(),
734 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700735 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700736
Roland Levillain0e840272018-08-23 19:55:30 +0100737 // Setup java.lang.String.
738 //
739 // We make this class non-movable for the unlikely case where it were to be
740 // moved by a sticky-bit (minor) collection when using the Generational
741 // Concurrent Copying (CC) collector, potentially creating a stale reference
742 // in the `klass_` field of one of its instances allocated in the Large-Object
743 // Space (LOS) -- see the comment about the dirty card scanning logic in
744 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700745 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700746 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100747 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700748 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000749 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400750
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700751 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700752 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700753 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700754 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000755 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700756
Ian Rogers23435d02012-09-24 11:23:12 -0700757 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700758 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100759 mirror::ObjectArray<mirror::Class>::Alloc(self,
760 object_array_class.Get(),
761 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700762 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100763 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
764 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
765 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
766 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100767 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
768 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700769
Mathieu Chartier6beced42016-11-15 15:51:31 -0800770 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
771 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
772
Vladimir Marko02610552018-06-04 14:38:00 +0100773 // Create array interface entries to populate once we can load system classes.
774 object_array_class->SetIfTable(AllocIfTable(self, 2));
775 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
776
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700777 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100778 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
779 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
780 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
781 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
782 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
783 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
784 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
785 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
786 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700787
Vladimir Marko70e2a762019-07-12 16:49:00 +0100788 // Allocate the primitive array classes. We need only the native pointer
789 // array at this point (int[] or long[], depending on architecture) but
790 // we shall perform the same setup steps for all primitive array classes.
791 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
792 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
793 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
794 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
795 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
796 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
797 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
798 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700799
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700800 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700801
Ian Rogers52813c92012-10-11 11:50:38 -0700802 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700803 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700804 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100805 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100806 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700807 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000808 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700809
Alex Lightd6251582016-10-31 11:12:30 -0700810
811 // Setup dalvik.system.ClassExt
812 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
813 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100814 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000815 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700816
Mathieu Chartier66f19252012-09-18 08:57:04 -0700817 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700818 Handle<mirror::Class> object_array_string(hs.NewHandle(
819 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700820 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700821 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100822 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700823
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000824 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700825 // Create runtime resolution and imt conflict methods.
826 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000827 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
828 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700829
Ian Rogers23435d02012-09-24 11:23:12 -0700830 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
831 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
832 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800833 if (boot_class_path.empty()) {
834 *error_msg = "Boot classpath is empty.";
835 return false;
836 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800837 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800838 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800839 *error_msg = "Null dex file.";
840 return false;
841 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800842 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800843 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700844 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700845
846 // now we can use FindSystemClass
847
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700848 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
849 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700850 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800851 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700852 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000853 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700854 quick_resolution_trampoline_ = GetQuickResolutionStub();
855 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000856 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700857 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700858 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700859
Alex Lightd6251582016-10-31 11:12:30 -0700860 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000861 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800862 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700863 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000864 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800865 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000866 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800867 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700868 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000869 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700870 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
871 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700872
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800873 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
874 // in class_table_.
875 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700876
Vladimir Marko70e2a762019-07-12 16:49:00 +0100877 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
878 // arrays - can't be done until Object has a vtable and component classes are loaded.
879 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
880 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
881 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
882 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
883 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
884 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
885 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
886 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
887 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
888 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
889 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700890
Ian Rogers23435d02012-09-24 11:23:12 -0700891 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700892 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800893 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700894 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800895 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700896 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
897 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100898 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
899 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700900
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700901 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
902 // suspension.
903 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000904 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700905 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000906 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700907 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000908 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700909 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000910 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700911
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700912 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100913 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700914
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800915 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700916
Ian Rogers23435d02012-09-24 11:23:12 -0700917 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100918 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
919 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700920
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700921 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100922 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700923 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100924 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700925
926 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700927 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
928 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100929 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700930
931 // Create java.lang.reflect.Constructor.class root and array root.
932 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
933 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100934 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700935 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
936 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100937 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700938
939 // Create java.lang.reflect.Method.class root and array root.
940 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
941 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100942 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700943 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
944 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100945 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700946
Orion Hodson005ac512017-10-24 15:43:43 +0100947 // Create java.lang.invoke.CallSite.class root
948 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
949 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100950 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100951
Narayan Kamathafa48272016-08-03 12:46:58 +0100952 // Create java.lang.invoke.MethodType.class root
953 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
954 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100955 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100956
957 // Create java.lang.invoke.MethodHandleImpl.class root
958 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
959 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100960 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100961 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100962
Orion Hodsonc069a302017-01-18 09:23:12 +0000963 // Create java.lang.invoke.MethodHandles.Lookup.class root
964 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
965 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100966 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000967
Orion Hodson005ac512017-10-24 15:43:43 +0100968 // Create java.lang.invoke.VarHandle.class root
969 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000970 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100971 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100972
973 // Create java.lang.invoke.FieldVarHandle.class root
974 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
975 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100976 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100977
978 // Create java.lang.invoke.ArrayElementVarHandle.class root
979 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
980 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100981 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100982
983 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
984 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
985 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100986 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100987
988 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
989 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
990 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100991 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000992
Narayan Kamath000e1882016-10-24 17:14:25 +0100993 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
994 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100995 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100996
Brian Carlstrom1f870082011-08-23 16:02:11 -0700997 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700998 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000999 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -08001000 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -07001001 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001002 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
1003 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001004 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001005 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001006 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001007 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001008 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001009 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001010 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001011 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001012 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001013 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001014 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001015 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001016
Ian Rogers23435d02012-09-24 11:23:12 -07001017 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001018 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001019 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001020 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001021 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001022
jeffhao8cd6dda2012-02-22 10:15:34 -08001023 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -07001024 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001025 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001026 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -07001027 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001028 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
1029 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
1030 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001031 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001032 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1033 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001034
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001035 // Create conflict tables that depend on the class linker.
1036 runtime->FixupConflictTables();
1037
Ian Rogers98379392014-02-24 16:53:16 -08001038 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001039
Brian Carlstroma004aa92012-02-08 18:05:09 -08001040 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001041
1042 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001043}
1044
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001045static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1046 REQUIRES_SHARED(Locks::mutator_lock_) {
1047 // Find String.<init> -> StringFactory bindings.
1048 ObjPtr<mirror::Class> string_factory_class =
1049 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1050 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001051 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001052 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1053 // Update the primordial thread.
1054 self->InitStringEntryPoints();
1055}
1056
Ian Rogers98379392014-02-24 16:53:16 -08001057void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001058 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001059
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001060 CreateStringInitBindings(self, this);
1061
Brian Carlstrom16192862011-09-12 17:50:06 -07001062 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001063 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001064 // as the types of the field can't be resolved prior to the runtime being
1065 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001066 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001067 Handle<mirror::Class> java_lang_ref_Reference =
1068 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001069 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1070 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001071
Mathieu Chartierc7853442015-03-27 14:35:38 -07001072 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001073 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1074 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001075
Mathieu Chartierc7853442015-03-27 14:35:38 -07001076 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001077 CHECK_STREQ(queue->GetName(), "queue");
1078 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001079
Mathieu Chartierc7853442015-03-27 14:35:38 -07001080 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001081 CHECK_STREQ(queueNext->GetName(), "queueNext");
1082 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001083
Mathieu Chartierc7853442015-03-27 14:35:38 -07001084 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001085 CHECK_STREQ(referent->GetName(), "referent");
1086 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001087
Mathieu Chartierc7853442015-03-27 14:35:38 -07001088 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001089 CHECK_STREQ(zombie->GetName(), "zombie");
1090 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001091
Brian Carlstroma663ea52011-08-19 23:33:41 -07001092 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001093 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001094 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001095 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001096 CHECK(klass != nullptr);
1097 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001098 // note SetClassRoot does additional validation.
1099 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001100 }
1101
Vladimir Marko02610552018-06-04 14:38:00 +01001102 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001103
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001104 // disable the slow paths in FindClass and CreatePrimitiveClass now
1105 // that Object, Class, and Object[] are setup
1106 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001107
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001108 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1109 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1110 // ensure that the class will be initialized.
1111 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001112 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001113
1114 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1115 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1116 // Strange, but don't crash.
1117 LOG(WARNING) << "Could not prepare StackOverflowError.";
1118 self->ClearException();
1119 }
1120 }
1121
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001122 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001123}
1124
Vladimir Markodcfcce42018-06-27 10:00:28 +00001125void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001126 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1127 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001128 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001129 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001130 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -07001131 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001132 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +00001133 } else {
1134 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001135 }
1136 }
1137}
1138
Jeff Haodcdc85b2015-12-04 14:06:18 -08001139struct TrampolineCheckData {
1140 const void* quick_resolution_trampoline;
1141 const void* quick_imt_conflict_trampoline;
1142 const void* quick_generic_jni_trampoline;
1143 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001144 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001145 ArtMethod* m;
1146 bool error;
1147};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001148
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001149bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1150 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001151 CHECK(!init_done_);
1152
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001153 Runtime* const runtime = Runtime::Current();
1154 Thread* const self = Thread::Current();
1155 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001156 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1157 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001158 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1159 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001160 if (!ValidPointerSize(pointer_size_unchecked)) {
1161 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001162 return false;
1163 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001164 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001165 if (!runtime->IsAotCompiler()) {
1166 // Only the Aot compiler supports having an image with a different pointer size than the
1167 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1168 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001169 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001170 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001171 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001172 sizeof(void*));
1173 return false;
1174 }
1175 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001176 DCHECK(!runtime->HasResolutionMethod());
1177 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1178 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1179 runtime->SetImtUnimplementedMethod(
1180 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1181 runtime->SetCalleeSaveMethod(
1182 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1183 CalleeSaveType::kSaveAllCalleeSaves);
1184 runtime->SetCalleeSaveMethod(
1185 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1186 CalleeSaveType::kSaveRefsOnly);
1187 runtime->SetCalleeSaveMethod(
1188 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1189 CalleeSaveType::kSaveRefsAndArgs);
1190 runtime->SetCalleeSaveMethod(
1191 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1192 CalleeSaveType::kSaveEverything);
1193 runtime->SetCalleeSaveMethod(
1194 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1195 CalleeSaveType::kSaveEverythingForClinit);
1196 runtime->SetCalleeSaveMethod(
1197 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1198 CalleeSaveType::kSaveEverythingForSuspendCheck);
1199
Jeff Haodcdc85b2015-12-04 14:06:18 -08001200 std::vector<const OatFile*> oat_files =
1201 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1202 DCHECK(!oat_files.empty());
1203 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001204 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001205 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1206 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1207 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1208 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1209 if (kIsDebugBuild) {
1210 // Check that the other images use the same trampoline.
1211 for (size_t i = 1; i < oat_files.size(); ++i) {
1212 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001213 const void* ith_jni_dlsym_lookup_trampoline_ =
1214 ith_oat_header.GetJniDlsymLookupTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001215 const void* ith_quick_resolution_trampoline =
1216 ith_oat_header.GetQuickResolutionTrampoline();
1217 const void* ith_quick_imt_conflict_trampoline =
1218 ith_oat_header.GetQuickImtConflictTrampoline();
1219 const void* ith_quick_generic_jni_trampoline =
1220 ith_oat_header.GetQuickGenericJniTrampoline();
1221 const void* ith_quick_to_interpreter_bridge_trampoline =
1222 ith_oat_header.GetQuickToInterpreterBridge();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001223 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
1224 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001225 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1226 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1227 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1228 // Make sure that all methods in this image do not contain those trampolines as
1229 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1230 TrampolineCheckData data;
1231 data.error = false;
1232 data.pointer_size = GetImagePointerSize();
1233 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1234 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1235 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1236 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1237 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001238 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1239 if (obj->IsClass()) {
1240 ObjPtr<mirror::Class> klass = obj->AsClass();
1241 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1242 const void* entrypoint =
1243 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1244 if (entrypoint == data.quick_resolution_trampoline ||
1245 entrypoint == data.quick_imt_conflict_trampoline ||
1246 entrypoint == data.quick_generic_jni_trampoline ||
1247 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1248 data.m = &m;
1249 data.error = true;
1250 return;
1251 }
1252 }
1253 }
1254 };
1255 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001256 if (data.error) {
1257 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001258 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001259 *error_msg = "Found an ArtMethod with a bad entrypoint";
1260 return false;
1261 }
1262 }
1263 }
1264 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001265
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001266 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001267 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001268 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001269 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001270
Vladimir Marko024d69f2019-06-13 10:52:32 +01001271 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1272 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1273 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1274 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1275 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1276 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001277
Vladimir Marko4433c432018-12-04 14:57:47 +00001278 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1279 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001280 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001281 // Boot class loader, use a null handle.
1282 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001283 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001284 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Marko4433c432018-12-04 14:57:47 +00001285 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001286 /*out*/&dex_files,
1287 error_msg)) {
1288 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001289 }
David Brazdil3e8aae02019-03-26 18:48:02 +00001290 // Assert that if absolute boot classpath locations were provided, they were
1291 // assigned to the loaded dex files.
1292 if (kIsDebugBuild && IsAbsoluteLocation(boot_class_path_locations[i])) {
1293 for (const auto& dex_file : dex_files) {
1294 DCHECK_EQ(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1295 boot_class_path_locations[i]);
1296 }
1297 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001298 // Append opened dex files at the end.
1299 boot_dex_files_.insert(boot_dex_files_.end(),
1300 std::make_move_iterator(dex_files.begin()),
1301 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001302 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001303 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1304 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1305 }
Ian Rogers98379392014-02-24 16:53:16 -08001306 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001307
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001308 VLOG(startup) << __FUNCTION__ << " exiting";
1309 return true;
1310}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001311
Vladimir Marko4433c432018-12-04 14:57:47 +00001312void ClassLinker::AddExtraBootDexFiles(
1313 Thread* self,
1314 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1315 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001316 AppendToBootClassPath(self, dex_file.get());
Vladimir Marko4433c432018-12-04 14:57:47 +00001317 boot_dex_files_.push_back(std::move(dex_file));
1318 }
1319}
1320
Jeff Hao5872d7c2016-04-27 11:07:41 -07001321bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001322 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001323 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001324 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1325 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001326}
1327
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001328class CHAOnDeleteUpdateClassVisitor {
1329 public:
1330 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1331 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1332 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1333 self_(Thread::Current()) {}
1334
1335 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1336 // This class is going to be unloaded. Tell CHA about it.
1337 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1338 return true;
1339 }
1340 private:
1341 const LinearAlloc* allocator_;
1342 const ClassHierarchyAnalysis* cha_;
1343 const PointerSize pointer_size_;
1344 const Thread* self_;
1345};
1346
Chris Wailes0c61be42018-09-26 17:27:34 -07001347/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001348 * A class used to ensure that all references to strings interned in an AppImage have been
1349 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001350 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001351class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001352 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001353 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1354 const InternTable::UnorderedSet& image_interns)
1355 : space_(space),
1356 image_interns_(image_interns),
1357 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001358
Chris Wailes0c61be42018-09-26 17:27:34 -07001359 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001360 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001361 if (referred_obj != nullptr &&
1362 space_.HasAddress(referred_obj.Ptr()) &&
1363 referred_obj->IsString()) {
1364 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001365 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1366 if (it != image_interns_.end() && it->Read() == referred_str) {
1367 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001368 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001369 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001370 }
1371
Chris Wailes0c61be42018-09-26 17:27:34 -07001372 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001373 mirror::CompressedReference<mirror::Object>* root) const
1374 REQUIRES_SHARED(Locks::mutator_lock_) {
1375 if (!root->IsNull()) {
1376 VisitRoot(root);
1377 }
1378 }
1379
Chris Wailes0c61be42018-09-26 17:27:34 -07001380 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001381 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001382 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001383 }
1384
1385 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001386 void operator()(ObjPtr<mirror::Object> obj,
1387 MemberOffset offset,
1388 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001389 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001390 // References within image or across images don't need a read barrier.
1391 ObjPtr<mirror::Object> referred_obj =
1392 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1393 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001394 }
1395
1396 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1397 ObjPtr<mirror::Reference> ref) const
1398 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001399 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001400 }
1401
Vladimir Marko8e05f092019-06-10 11:10:38 +01001402 size_t GetCount() const {
1403 return count_;
1404 }
1405
1406 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001407 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001408 const InternTable::UnorderedSet& image_interns_;
1409 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001410};
1411
Chris Wailes0c61be42018-09-26 17:27:34 -07001412/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001413 * This function counts references to strings interned in the AppImage.
1414 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001415 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001416size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1417 const InternTable::UnorderedSet& image_interns)
1418 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001419 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1420 const ImageHeader& image_header = space.GetImageHeader();
1421 const uint8_t* target_base = space.GetMemMap()->Begin();
1422 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001423
1424 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1425 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001426
Vladimir Marko8e05f092019-06-10 11:10:38 +01001427 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001428 bitmap->VisitMarkedRange(objects_begin,
1429 objects_end,
1430 [&space, &visitor](mirror::Object* obj)
1431 REQUIRES_SHARED(Locks::mutator_lock_) {
1432 if (space.HasAddress(obj)) {
1433 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001434 obj->VisitReferences</* kVisitNativeRoots= */ true,
1435 kVerifyNone,
1436 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001437 } else {
1438 // Don't visit native roots for non-dex-cache as they can't contain
1439 // native references to strings. This is verified during compilation
1440 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001441 obj->VisitReferences</* kVisitNativeRoots= */ false,
1442 kVerifyNone,
1443 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001444 }
1445 }
1446 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001447 return visitor.GetCount();
1448}
1449
1450template <typename Visitor>
1451static void VisitInternedStringReferences(
1452 gc::space::ImageSpace* space,
1453 bool use_preresolved_strings,
1454 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1455 const uint8_t* target_base = space->Begin();
1456 const ImageSection& sro_section =
1457 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1458 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1459
1460 VLOG(image)
1461 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1462 << num_string_offsets;
1463
1464 const auto* sro_base =
1465 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1466
1467 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1468 uint32_t base_offset = sro_base[offset_index].first;
1469
1470 if (HasDexCacheStringNativeRefTag(base_offset)) {
1471 base_offset = ClearDexCacheNativeRefTags(base_offset);
1472 DCHECK_ALIGNED(base_offset, 2);
1473
1474 ObjPtr<mirror::DexCache> dex_cache =
1475 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1476 uint32_t string_slot_index = sro_base[offset_index].second;
1477
1478 mirror::StringDexCachePair source =
1479 dex_cache->GetStrings()[string_slot_index].load(std::memory_order_relaxed);
1480 ObjPtr<mirror::String> referred_string = source.object.Read();
1481 DCHECK(referred_string != nullptr);
1482
1483 ObjPtr<mirror::String> visited = visitor(referred_string);
1484 if (visited != referred_string) {
1485 // Because we are not using a helper function we need to mark the GC card manually.
1486 WriteBarrier::ForEveryFieldWrite(dex_cache);
1487 dex_cache->GetStrings()[string_slot_index].store(
1488 mirror::StringDexCachePair(visited, source.index), std::memory_order_relaxed);
1489 }
1490 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1491 if (use_preresolved_strings) {
1492 base_offset = ClearDexCacheNativeRefTags(base_offset);
1493 DCHECK_ALIGNED(base_offset, 2);
1494
1495 ObjPtr<mirror::DexCache> dex_cache =
1496 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1497 uint32_t string_index = sro_base[offset_index].second;
1498
Mathieu Chartier77f84fc2019-06-14 12:49:54 -07001499 GcRoot<mirror::String>* preresolved_strings =
1500 dex_cache->GetPreResolvedStrings();
1501 // Handle calls to ClearPreResolvedStrings that might occur concurrently by the profile
1502 // saver that runs shortly after startup. In case the strings are cleared, there is nothing
1503 // to fix up.
1504 if (preresolved_strings != nullptr) {
1505 ObjPtr<mirror::String> referred_string =
1506 preresolved_strings[string_index].Read();
1507 if (referred_string != nullptr) {
1508 ObjPtr<mirror::String> visited = visitor(referred_string);
1509 if (visited != referred_string) {
1510 // Because we are not using a helper function we need to mark the GC card manually.
1511 WriteBarrier::ForEveryFieldWrite(dex_cache);
1512 preresolved_strings[string_index] = GcRoot<mirror::String>(visited);
1513 }
1514 }
Vladimir Marko8e05f092019-06-10 11:10:38 +01001515 }
1516 }
1517 } else {
1518 uint32_t raw_member_offset = sro_base[offset_index].second;
1519 DCHECK_ALIGNED(base_offset, 2);
1520 DCHECK_ALIGNED(raw_member_offset, 2);
1521
1522 ObjPtr<mirror::Object> obj_ptr =
1523 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1524 MemberOffset member_offset(raw_member_offset);
1525 ObjPtr<mirror::String> referred_string =
1526 obj_ptr->GetFieldObject<mirror::String,
1527 kVerifyNone,
1528 kWithoutReadBarrier,
1529 /* kIsVolatile= */ false>(member_offset);
1530 DCHECK(referred_string != nullptr);
1531
1532 ObjPtr<mirror::String> visited = visitor(referred_string);
1533 if (visited != referred_string) {
1534 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1535 /* kCheckTransaction= */ false,
1536 kVerifyNone,
1537 /* kIsVolatile= */ false>(member_offset, visited);
1538 }
1539 }
1540 }
1541}
1542
1543static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1544 REQUIRES_SHARED(Locks::mutator_lock_) {
1545 InternTable::UnorderedSet image_interns;
1546 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1547 if (section.Size() > 0) {
1548 size_t read_count;
1549 const uint8_t* data = space->Begin() + section.Offset();
1550 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1551 image_set.swap(image_interns);
1552 }
1553 size_t num_recorded_refs = 0u;
1554 VisitInternedStringReferences(
1555 space,
1556 /*use_preresolved_strings=*/ true,
1557 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1558 REQUIRES_SHARED(Locks::mutator_lock_) {
1559 auto it = image_interns.find(GcRoot<mirror::String>(str));
1560 CHECK(it != image_interns.end());
1561 CHECK(it->Read() == str);
1562 ++num_recorded_refs;
1563 return str;
1564 });
1565 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1566 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001567}
1568
Andreas Gampe2af99022017-04-25 08:32:59 -07001569// new_class_set is the set of classes that were read from the class table section in the image.
1570// If there was no class table section, it is null.
1571// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001572class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001573 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001574 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001575 ClassLinker* class_linker,
1576 gc::space::ImageSpace* space,
1577 Handle<mirror::ClassLoader> class_loader,
1578 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001579 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001580 REQUIRES(!Locks::dex_lock_)
1581 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001582
Chris Wailesfbeef462018-10-19 14:16:35 -07001583 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001584 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001585};
1586
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001587void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001588 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001589 gc::space::ImageSpace* space,
1590 Handle<mirror::ClassLoader> class_loader,
1591 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001592 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001593 REQUIRES(!Locks::dex_lock_)
1594 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001595 ScopedTrace app_image_timing("AppImage:Updating");
1596
Vladimir Marko8e05f092019-06-10 11:10:38 +01001597 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1598 // In debug build, verify the string references before applying
1599 // the Runtime::LoadAppImageStartupCache() option.
1600 VerifyInternedStringReferences(space);
1601 }
1602
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001603 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001604 Runtime* const runtime = Runtime::Current();
1605 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001606 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001607 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001608 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001609 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001610 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001611 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001612 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001613 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001614 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001615 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1616 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001617 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001618
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001619 if (!load_app_image_startup_cache) {
1620 dex_cache->ClearPreResolvedStrings();
1621 }
1622
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001623 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001624 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001625 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001626 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001627 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001628 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001629 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001630
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001631 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001632 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001633 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001634 DCHECK(it != new_class_set->end());
1635 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001636 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001637
Vladimir Marko1a1de672016-10-13 12:53:15 +01001638 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001639 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001640 DCHECK(it2 != new_class_set->end());
1641 DCHECK_EQ(it2->Read(), super_class);
1642 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001643
Vladimir Marko1a1de672016-10-13 12:53:15 +01001644 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1645 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001646 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1647 if (!class_linker->IsQuickResolutionStub(code) &&
1648 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001649 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001650 !m.IsNative()) {
1651 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001652 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001653 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001654
Vladimir Marko1a1de672016-10-13 12:53:15 +01001655 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1656 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001657 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1658 if (!class_linker->IsQuickResolutionStub(code) &&
1659 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001660 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001661 !m.IsNative()) {
1662 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001663 }
1664 }
1665 }
1666 }
1667 }
1668 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001669 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001670
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001671 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001672 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001673 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001674
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001675 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001676 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001677 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001678 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1679 header.VisitPackedArtMethods([&](ArtMethod& method)
1680 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1681 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1682 if (klass != nullptr) {
1683 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1684 }
1685 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001686 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001687}
1688
Chris Wailesfbeef462018-10-19 14:16:35 -07001689void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001690 // Iterate over the string reference offsets stored in the image and intern
1691 // the strings they point to.
1692 ScopedTrace timing("AppImage:InternString");
1693
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001694 Runtime* const runtime = Runtime::Current();
1695 InternTable* const intern_table = runtime->GetInternTable();
1696
1697 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001698
1699 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1700 // for faster lookup.
1701 // TODO: Optimize with a bitmap or bloom filter
1702 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001703 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001704 REQUIRES_SHARED(Locks::mutator_lock_)
1705 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001706 const size_t non_boot_image_strings = intern_table->CountInterns(
1707 /*visit_boot_images=*/false,
1708 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001709 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001710 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1711 // Visit the smaller of the two sets to compute the intersection.
1712 if (interns.size() < non_boot_image_strings) {
1713 for (auto it = interns.begin(); it != interns.end(); ) {
1714 ObjPtr<mirror::String> string = it->Read();
1715 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1716 if (existing == nullptr) {
1717 existing = intern_table->LookupStrongLocked(string);
1718 }
1719 if (existing != nullptr) {
1720 intern_remap.Put(string.Ptr(), existing.Ptr());
1721 it = interns.erase(it);
1722 } else {
1723 ++it;
1724 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001725 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001726 } else {
1727 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1728 REQUIRES_SHARED(Locks::mutator_lock_)
1729 REQUIRES(Locks::intern_table_lock_) {
1730 auto it = interns.find(root);
1731 if (it != interns.end()) {
1732 ObjPtr<mirror::String> existing = root.Read();
1733 intern_remap.Put(it->Read(), existing.Ptr());
1734 it = interns.erase(it);
1735 }
1736 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1737 }
1738 // Sanity check to ensure correctness.
1739 if (kIsDebugBuild) {
1740 for (GcRoot<mirror::String>& root : interns) {
1741 ObjPtr<mirror::String> string = root.Read();
1742 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1743 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001744 }
1745 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001746 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001747 intern_table->AddImageStringsToTable(space, func);
1748 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001749 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001750 VisitInternedStringReferences(
1751 space,
1752 load_startup_cache,
1753 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1754 auto it = intern_remap.find(str.Ptr());
1755 if (it != intern_remap.end()) {
1756 return ObjPtr<mirror::String>(it->second);
1757 }
1758 return str;
1759 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001760 }
1761}
1762
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001763static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1764 const char* location,
1765 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001766 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001767 DCHECK(error_msg != nullptr);
1768 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001769 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001770 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001771 return std::unique_ptr<const DexFile>();
1772 }
1773 std::string inner_error_msg;
1774 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1775 if (dex_file == nullptr) {
1776 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1777 location,
1778 oat_file->GetLocation().c_str(),
1779 inner_error_msg.c_str());
1780 return std::unique_ptr<const DexFile>();
1781 }
1782
1783 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1784 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1785 location,
1786 dex_file->GetLocationChecksum(),
1787 oat_dex_file->GetDexFileLocationChecksum());
1788 return std::unique_ptr<const DexFile>();
1789 }
1790 return dex_file;
1791}
1792
1793bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1794 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1795 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001796 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001797 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001798 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001799 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001800 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001801 dex_caches_object->AsObjectArray<mirror::DexCache>();
1802 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001803 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001804 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1805 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1806 dex_file_location.c_str(),
1807 error_msg);
1808 if (dex_file == nullptr) {
1809 return false;
1810 }
1811 dex_cache->SetDexFile(dex_file.get());
1812 out_dex_files->push_back(std::move(dex_file));
1813 }
1814 return true;
1815}
1816
Andreas Gampe0793bec2016-12-01 11:37:33 -08001817// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1818// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001819class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001820 public:
1821 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1822 REQUIRES_SHARED(Locks::mutator_lock_) {
1823 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001824 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1825 DCHECK(obj != nullptr);
1826 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1827 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1828 if (obj->IsClass()) {
1829 auto klass = obj->AsClass();
1830 for (ArtField& field : klass->GetIFields()) {
1831 CHECK_EQ(field.GetDeclaringClass(), klass);
1832 }
1833 for (ArtField& field : klass->GetSFields()) {
1834 CHECK_EQ(field.GetDeclaringClass(), klass);
1835 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001836 const PointerSize pointer_size = isc.pointer_size_;
1837 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001838 isc.SanityCheckArtMethod(&m, klass);
1839 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001840 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001841 if (vtable != nullptr) {
1842 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1843 }
1844 if (klass->ShouldHaveImt()) {
1845 ImTable* imt = klass->GetImt(pointer_size);
1846 for (size_t i = 0; i < ImTable::kSize; ++i) {
1847 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1848 }
1849 }
1850 if (klass->ShouldHaveEmbeddedVTable()) {
1851 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1852 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1853 }
1854 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001855 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001856 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1857 if (iftable->GetMethodArrayCount(i) > 0) {
1858 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1859 }
1860 }
1861 }
1862 };
1863 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001864 }
1865
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001866 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1867 ClassLinker* class_linker,
1868 mirror::MethodDexCacheType* arr,
1869 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001870 REQUIRES_SHARED(Locks::mutator_lock_) {
1871 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001872 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001873 }
1874
Andreas Gampe0793bec2016-12-01 11:37:33 -08001875 private:
1876 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1877 : spaces_(heap->GetBootImageSpaces()),
1878 pointer_size_(class_linker->GetImagePointerSize()) {
1879 space_begin_.reserve(spaces_.size());
1880 method_sections_.reserve(spaces_.size());
1881 runtime_method_sections_.reserve(spaces_.size());
1882 for (gc::space::ImageSpace* space : spaces_) {
1883 space_begin_.push_back(space->Begin());
1884 auto& header = space->GetImageHeader();
1885 method_sections_.push_back(&header.GetMethodsSection());
1886 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1887 }
1888 }
1889
1890 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1891 REQUIRES_SHARED(Locks::mutator_lock_) {
1892 if (m->IsRuntimeMethod()) {
1893 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1894 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1895 } else if (m->IsCopied()) {
1896 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1897 } else if (expected_class != nullptr) {
1898 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1899 }
1900 if (!spaces_.empty()) {
1901 bool contains = false;
1902 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1903 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1904 contains = method_sections_[i]->Contains(offset) ||
1905 runtime_method_sections_[i]->Contains(offset);
1906 }
1907 CHECK(contains) << m << " not found";
1908 }
1909 }
1910
1911 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1912 ObjPtr<mirror::Class> expected_class)
1913 REQUIRES_SHARED(Locks::mutator_lock_) {
1914 CHECK(arr != nullptr);
1915 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1916 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1917 // expected_class == null means we are a dex cache.
1918 if (expected_class != nullptr) {
1919 CHECK(method != nullptr);
1920 }
1921 if (method != nullptr) {
1922 SanityCheckArtMethod(method, expected_class);
1923 }
1924 }
1925 }
1926
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001927 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001928 REQUIRES_SHARED(Locks::mutator_lock_) {
1929 CHECK_EQ(arr != nullptr, size != 0u);
1930 if (arr != nullptr) {
1931 bool contains = false;
1932 for (auto space : spaces_) {
1933 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001934 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001935 contains = true;
1936 break;
1937 }
1938 }
1939 CHECK(contains);
1940 }
1941 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001942 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1943 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001944 // expected_class == null means we are a dex cache.
1945 if (method != nullptr) {
1946 SanityCheckArtMethod(method, nullptr);
1947 }
1948 }
1949 }
1950
1951 const std::vector<gc::space::ImageSpace*>& spaces_;
1952 const PointerSize pointer_size_;
1953
1954 // Cached sections from the spaces.
1955 std::vector<const uint8_t*> space_begin_;
1956 std::vector<const ImageSection*> method_sections_;
1957 std::vector<const ImageSection*> runtime_method_sections_;
1958};
1959
Andreas Gampebe7af222017-07-25 09:57:28 -07001960static void VerifyAppImage(const ImageHeader& header,
1961 const Handle<mirror::ClassLoader>& class_loader,
1962 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1963 ClassTable* class_table, gc::space::ImageSpace* space)
1964 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001965 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1966 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1967 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1968 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1969 << mirror::Class::PrettyClass(klass);
1970 }
1971 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001972 {
1973 // Verify that all direct interfaces of classes in the class table are also resolved.
1974 std::vector<ObjPtr<mirror::Class>> classes;
1975 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1976 REQUIRES_SHARED(Locks::mutator_lock_) {
1977 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1978 classes.push_back(klass);
1979 }
1980 return true;
1981 };
1982 class_table->Visit(verify_direct_interfaces_in_table);
1983 Thread* self = Thread::Current();
1984 for (ObjPtr<mirror::Class> klass : classes) {
1985 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1986 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1987 << klass->PrettyDescriptor() << " iface #" << i;
1988 }
1989 }
1990 }
1991 // Check that all non-primitive classes in dex caches are also in the class table.
Alex Lighta9bbc082019-11-14 14:51:41 -08001992 for (auto dex_cache : dex_caches.ConstIterate<mirror::DexCache>()) {
Andreas Gampebe7af222017-07-25 09:57:28 -07001993 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1994 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1995 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1996 if (klass != nullptr && !klass->IsPrimitive()) {
1997 CHECK(class_table->Contains(klass))
1998 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1999 }
2000 }
2001 }
2002}
2003
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002004bool ClassLinker::AddImageSpace(
2005 gc::space::ImageSpace* space,
2006 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002007 const char* dex_location,
2008 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
2009 std::string* error_msg) {
2010 DCHECK(out_dex_files != nullptr);
2011 DCHECK(error_msg != nullptr);
2012 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002013 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002014 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002015 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002016 DCHECK(dex_caches_object != nullptr);
2017 Runtime* const runtime = Runtime::Current();
2018 gc::Heap* const heap = runtime->GetHeap();
2019 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002020 // Check that the image is what we are expecting.
2021 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
2022 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
2023 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
2024 image_pointer_size_);
2025 return false;
2026 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002027 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
2028 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
2029 *error_msg = StringPrintf("Expected %zu image roots but got %d",
2030 expected_image_roots,
2031 header.GetImageRoots()->GetLength());
2032 return false;
2033 }
2034 StackHandleScope<3> hs(self);
2035 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
2036 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2037 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2038 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002039 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002040 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2041 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002042 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002043 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002044 *error_msg = StringPrintf("Expected %d class roots but got %d",
2045 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002046 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002047 return false;
2048 }
2049 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002050 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2051 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2052 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002053 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2054 return false;
2055 }
2056 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002057 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002058 if (oat_file->GetOatHeader().GetDexFileCount() !=
2059 static_cast<uint32_t>(dex_caches->GetLength())) {
2060 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2061 "image";
2062 return false;
2063 }
2064
Alex Lighta9bbc082019-11-14 14:51:41 -08002065 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00002066 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Andreas Gamped5d807b2019-04-18 14:46:51 -07002067 if (class_loader == nullptr) {
2068 // For app images, we'll see the relative location. b/130666977.
2069 DCHECK_EQ(dex_location, DexFileLoader::GetBaseLocation(dex_file_location));
2070 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002071 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2072 dex_file_location.c_str(),
2073 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002074 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002075 return false;
2076 }
2077
2078 if (app_image) {
2079 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2080 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002081 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002082 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002083 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002084 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002085 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002086 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002087 }
2088 }
2089 } else {
2090 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002091 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2092 this,
2093 dex_cache->GetResolvedMethods(),
2094 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002095 }
2096 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002097 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002098 }
2099 out_dex_files->push_back(std::move(dex_file));
2100 }
2101
2102 if (app_image) {
2103 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002104 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002105 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2106 *error_msg = "Unexpected BootClassLoader in app image";
2107 return false;
2108 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002109 }
2110
2111 if (kSanityCheckObjects) {
Alex Lighta9bbc082019-11-14 14:51:41 -08002112 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002113 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2114 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2115 if (field != nullptr) {
2116 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2117 }
2118 }
2119 }
2120 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002121 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002122 }
2123 }
2124
2125 // Set entry point to interpreter if in InterpretOnly mode.
2126 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002127 // Set image methods' entry point to interpreter.
2128 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2129 if (!method.IsRuntimeMethod()) {
2130 DCHECK(method.GetDeclaringClass() != nullptr);
2131 if (!method.IsNative() && !method.IsResolutionMethod()) {
2132 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2133 image_pointer_size_);
2134 }
2135 }
2136 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002137 }
2138
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002139 if (interpreter::CanRuntimeUseNterp()) {
2140 // Set image methods' entry point that point to the interpreter bridge to the nterp entry point.
2141 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2142 if (IsQuickToInterpreterBridge(method.GetEntryPointFromQuickCompiledCode()) &&
2143 interpreter::CanMethodUseNterp(&method)) {
2144 method.SetEntryPointFromQuickCompiledCodePtrSize(interpreter::GetNterpEntryPoint(),
2145 image_pointer_size_);
2146 }
2147 }, space->Begin(), image_pointer_size_);
2148 }
2149
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002150 ClassTable* class_table = nullptr;
2151 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002152 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002153 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002154 }
2155 // If we have a class table section, read it and use it for verification in
2156 // UpdateAppImageClassLoadersAndDexCaches.
2157 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002158 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002159 const bool added_class_table = class_table_section.Size() > 0u;
2160 if (added_class_table) {
2161 const uint64_t start_time2 = NanoTime();
2162 size_t read_count = 0;
2163 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2164 /*make copy*/false,
2165 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002166 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002167 }
2168 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002169 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002170
2171 {
2172 ScopedTrace trace("AppImage:UpdateClassLoaders");
2173 // Update class loader and resolved strings. If added_class_table is false, the resolved
2174 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002175 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002176 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002177 // Note: We probably don't need the read barrier unless we copy the app image objects into
2178 // the region space.
2179 ObjPtr<mirror::Class> klass(root.Read());
2180 // Do not update class loader for boot image classes where the app image
2181 // class loader is only the initiating loader but not the defining loader.
2182 // Avoid read barrier since we are comparing against null.
2183 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2184 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2185 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002186 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002187 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002188
Vladimir Marko305c38b2018-02-14 11:50:07 +00002189 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002190 // Every class in the app image has initially SubtypeCheckInfo in the
2191 // Uninitialized state.
2192 //
2193 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2194 // after class initialization is complete. The app image ClassStatus as-is
2195 // are almost all ClassStatus::Initialized, and being in the
2196 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2197 //
2198 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2199 //
2200 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002201 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002202 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2203 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002204 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002205 }
2206 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002207 }
2208 if (!oat_file->GetBssGcRoots().empty()) {
2209 // Insert oat file to class table for visiting .bss GC roots.
2210 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002211 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002212
Mathieu Chartier69731002016-03-02 16:08:31 -08002213 if (added_class_table) {
2214 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2215 class_table->AddClassSet(std::move(temp_set));
2216 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002217
Mathieu Chartier69731002016-03-02 16:08:31 -08002218 if (kIsDebugBuild && app_image) {
2219 // This verification needs to happen after the classes have been added to the class loader.
2220 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002221 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002222 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002223 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002224
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002225 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002226 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002227}
2228
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002229bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002230 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2231 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002232}
2233
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002234void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002235 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2236 // enabling tracing requires the mutator lock, there are no race conditions here.
2237 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002238 Thread* const self = Thread::Current();
2239 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002240 if (kUseReadBarrier) {
2241 // We do not track new roots for CC.
2242 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2243 kVisitRootFlagClearRootLog |
2244 kVisitRootFlagStartLoggingNewRoots |
2245 kVisitRootFlagStopLoggingNewRoots));
2246 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002247 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002248 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2249 // There is 3 GC cases to handle:
2250 // Non moving concurrent:
2251 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002252 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002253 //
2254 // Moving non-concurrent:
2255 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2256 // To prevent missing roots, this case needs to ensure that there is no
2257 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2258 // class which is in the class table.
2259 //
2260 // Moving concurrent:
2261 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2262 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002263 //
2264 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2265 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2266 // these objects.
2267 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002268 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002269 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002270 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002271 for (const ClassLoaderData& data : class_loaders_) {
2272 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2273 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2274 }
2275 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002276 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002277 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002278 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002279 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002280 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002281 // Concurrent moving GC marked new roots through the to-space invariant.
2282 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002283 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002284 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2285 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2286 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2287 if (old_ref != nullptr) {
2288 DCHECK(old_ref->IsClass());
2289 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2290 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2291 // Concurrent moving GC marked new roots through the to-space invariant.
2292 CHECK_EQ(new_ref, old_ref);
2293 }
2294 }
2295 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002296 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002297 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002298 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002299 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002300 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002301 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002302 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002303 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002304 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002305 }
2306 // We deliberately ignore the class roots in the image since we
2307 // handle image roots by using the MS/CMS rescanning of dirty cards.
2308}
2309
Brian Carlstroma663ea52011-08-19 23:33:41 -07002310// Keep in sync with InitCallback. Anything we visit, we need to
2311// reinit references to when reinitializing a ClassLinker from a
2312// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002313void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002314 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002315 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002316 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2317 // unloading if we are marking roots.
2318 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002319}
2320
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002321class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2322 public:
2323 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2324 : visitor_(visitor),
2325 done_(false) {}
2326
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002327 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002328 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002329 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002330 if (!done_ && class_table != nullptr) {
2331 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2332 if (!class_table->Visit(visitor)) {
2333 // If the visitor ClassTable returns false it means that we don't need to continue.
2334 done_ = true;
2335 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002336 }
2337 }
2338
2339 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002340 // Class visitor that limits the class visits from a ClassTable to the classes with
2341 // the provided defining class loader. This filter is used to avoid multiple visits
2342 // of the same class which can be recorded for multiple initiating class loaders.
2343 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2344 public:
2345 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2346 ClassVisitor* visitor)
2347 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2348
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002349 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002350 if (klass->GetClassLoader() != defining_class_loader_) {
2351 return true;
2352 }
2353 return (*visitor_)(klass);
2354 }
2355
Vladimir Marko0984e482019-03-27 16:41:41 +00002356 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002357 ClassVisitor* const visitor_;
2358 };
2359
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002360 ClassVisitor* const visitor_;
2361 // If done is true then we don't need to do any more visiting.
2362 bool done_;
2363};
2364
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002365void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002366 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002367 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2368 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002369 }
2370}
2371
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002372void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002373 Thread* const self = Thread::Current();
2374 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2375 // Not safe to have thread suspension when we are holding a lock.
2376 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002377 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002378 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002379 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002380 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002381 }
2382}
2383
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002384class GetClassesInToVector : public ClassVisitor {
2385 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002386 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002387 classes_.push_back(klass);
2388 return true;
2389 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002390 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002391};
2392
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002393class GetClassInToObjectArray : public ClassVisitor {
2394 public:
2395 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2396 : arr_(arr), index_(0) {}
2397
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002398 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002399 ++index_;
2400 if (index_ <= arr_->GetLength()) {
2401 arr_->Set(index_ - 1, klass);
2402 return true;
2403 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002404 return false;
2405 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002406
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002407 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002408 return index_ <= arr_->GetLength();
2409 }
2410
2411 private:
2412 mirror::ObjectArray<mirror::Class>* const arr_;
2413 int32_t index_;
2414};
2415
2416void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002417 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2418 // is avoiding duplicates.
2419 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002420 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002421 GetClassesInToVector accumulator;
2422 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002423 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002424 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002425 return;
2426 }
2427 }
2428 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002429 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002430 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002431 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002432 // We size the array assuming classes won't be added to the class table during the visit.
2433 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002434 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002435 size_t class_table_size;
2436 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002437 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002438 // Add 100 in case new classes get loaded when we are filling in the object array.
2439 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002440 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002441 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002442 classes.Assign(
2443 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002444 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002445 GetClassInToObjectArray accumulator(classes.Get());
2446 VisitClasses(&accumulator);
2447 if (accumulator.Succeeded()) {
2448 break;
2449 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002450 }
2451 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2452 // If the class table shrank during creation of the clases array we expect null elements. If
2453 // the class table grew then the loop repeats. If classes are created after the loop has
2454 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002455 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002456 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002457 return;
2458 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002459 }
2460 }
2461}
2462
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002463ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002464 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002465 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002466 // CHA unloading analysis is not needed. No negative consequences are expected because
2467 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002468 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002469 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002470 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002471 while (!running_visibly_initialized_callbacks_.empty()) {
2472 std::unique_ptr<VisiblyInitializedCallback> callback(
2473 std::addressof(running_visibly_initialized_callbacks_.front()));
2474 running_visibly_initialized_callbacks_.pop_front();
2475 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002476}
2477
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002478void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002479 Runtime* const runtime = Runtime::Current();
2480 JavaVMExt* const vm = runtime->GetJavaVM();
2481 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002482 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002483 if (runtime->GetJit() != nullptr) {
2484 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2485 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002486 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002487 code_cache->RemoveMethodsIn(self, *data.allocator);
2488 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002489 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002490 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002491 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002492 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002493 // Cleanup references to single implementation ArtMethods that will be deleted.
2494 if (cleanup_cha) {
2495 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2496 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2497 }
2498
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002499 delete data.allocator;
2500 delete data.class_table;
2501}
2502
Vladimir Markobcf17522018-06-01 13:14:32 +01002503ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2504 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002505 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002506 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2507 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002508}
2509
Vladimir Markobcf17522018-06-01 13:14:32 +01002510ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2511 Thread* self,
2512 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002513 StackHandleScope<1> hs(self);
2514 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002515 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002516 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002517 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002518 self->AssertPendingOOMException();
2519 return nullptr;
2520 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002521 // Use InternWeak() so that the location String can be collected when the ClassLoader
2522 // with this DexCache is collected.
2523 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002524 if (location == nullptr) {
2525 self->AssertPendingOOMException();
2526 return nullptr;
2527 }
2528 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002529 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002530}
2531
Vladimir Markobcf17522018-06-01 13:14:32 +01002532ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2533 const DexFile& dex_file,
2534 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002535 ObjPtr<mirror::String> location = nullptr;
2536 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002537 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002538 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002539 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002540 mirror::DexCache::InitializeDexCache(self,
2541 dex_cache,
2542 location,
2543 &dex_file,
2544 linear_alloc,
2545 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002546 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002547 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002548}
2549
Vladimir Marko70e2a762019-07-12 16:49:00 +01002550template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002551ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2552 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002553 uint32_t class_size,
2554 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002555 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002556 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002557 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002558 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2559 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002560 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002561 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002562 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002563 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002564 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002565}
2566
Vladimir Marko70e2a762019-07-12 16:49:00 +01002567template <bool kMovable>
2568ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2569 ObjPtr<mirror::Class> java_lang_Class,
2570 uint32_t class_size) {
2571 mirror::Class::InitializeClassVisitor visitor(class_size);
2572 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2573}
2574
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002575ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002576 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002577}
2578
Vladimir Marko70e2a762019-07-12 16:49:00 +01002579void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2580 ClassRoot primitive_root,
2581 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002582 // We make this class non-movable for the unlikely case where it were to be
2583 // moved by a sticky-bit (minor) collection when using the Generational
2584 // Concurrent Copying (CC) collector, potentially creating a stale reference
2585 // in the `klass_` field of one of its instances allocated in the Large-Object
2586 // Space (LOS) -- see the comment about the dirty card scanning logic in
2587 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002588 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2589 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2590 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2591 DCHECK(component_type->IsPrimitive());
2592 array_class->SetComponentType(component_type);
2593 SetClassRoot(array_root, array_class);
2594}
2595
2596void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2597 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2598 array_class->SetSuperClass(java_lang_Object);
2599 array_class->SetVTable(java_lang_Object->GetVTable());
2600 array_class->SetPrimitiveType(Primitive::kPrimNot);
2601 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2602 array_class->SetClassFlags(component_type->IsPrimitive()
2603 ? mirror::kClassFlagNoReferenceFields
2604 : mirror::kClassFlagObjectArray);
2605 array_class->SetClassLoader(component_type->GetClassLoader());
2606 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2607 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2608 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2609 array_class->SetImt(object_imt, image_pointer_size_);
2610 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2611 // the kAccVerificationAttempted flag is added below, and there are no
2612 // methods that need the kAccSkipAccessChecks flag.
2613 DCHECK_EQ(array_class->NumMethods(), 0u);
2614
2615 // don't need to set new_class->SetObjectSize(..)
2616 // because Object::SizeOf delegates to Array::SizeOf
2617
2618 // All arrays have java/lang/Cloneable and java/io/Serializable as
2619 // interfaces. We need to set that up here, so that stuff like
2620 // "instanceof" works right.
2621
2622 // Use the single, global copies of "interfaces" and "iftable"
2623 // (remember not to free them for arrays).
2624 {
2625 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2626 CHECK(array_iftable != nullptr);
2627 array_class->SetIfTable(array_iftable);
2628 }
2629
2630 // Inherit access flags from the component type.
2631 int access_flags = component_type->GetAccessFlags();
2632 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2633 access_flags &= kAccJavaFlagsMask;
2634 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2635 // and remove "interface".
2636 access_flags |= kAccAbstract | kAccFinal;
2637 access_flags &= ~kAccInterface;
2638 // Arrays are access-checks-clean and preverified.
2639 access_flags |= kAccVerificationAttempted;
2640
2641 array_class->SetAccessFlags(access_flags);
2642
Vladimir Markobf121912019-06-04 13:49:05 +01002643 // Array classes are fully initialized either during single threaded startup,
2644 // or from a pre-fence visitor, so visibly initialized.
2645 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002646}
2647
2648void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2649 // Do not hold lock on the array class object, the initialization of
2650 // core array classes is done while the process is still single threaded.
2651 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2652 FinishArrayClassSetup(array_class);
2653
2654 std::string temp;
2655 const char* descriptor = array_class->GetDescriptor(&temp);
2656 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2657 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2658 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002659}
2660
Vladimir Markobcf17522018-06-01 13:14:32 +01002661ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002662 Thread* self,
2663 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002664 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002665 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002666}
2667
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002668ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2669 const char* descriptor,
2670 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002671 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002672 if (kIsDebugBuild) {
2673 StackHandleScope<1> hs(self);
2674 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2675 Thread::PoisonObjectPointersIfDebug();
2676 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002677
2678 // For temporary classes we must wait for them to be retired.
2679 if (init_done_ && klass->IsTemp()) {
2680 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002681 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002682 ThrowEarlierClassFailure(klass);
2683 return nullptr;
2684 }
2685 StackHandleScope<1> hs(self);
2686 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2687 ObjectLock<mirror::Class> lock(self, h_class);
2688 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002689 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002690 lock.WaitIgnoringInterrupts();
2691 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002692 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002693 ThrowEarlierClassFailure(h_class.Get());
2694 return nullptr;
2695 }
2696 CHECK(h_class->IsRetired());
2697 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002698 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002699 }
2700
Brian Carlstromaded5f72011-10-07 17:15:04 -07002701 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002702 size_t index = 0;
2703 // Maximum number of yield iterations until we start sleeping.
2704 static const size_t kNumYieldIterations = 1000;
2705 // How long each sleep is in us.
2706 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002707 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002708 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002709 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002710 {
2711 ObjectTryLock<mirror::Class> lock(self, h_class);
2712 // Can not use a monitor wait here since it may block when returning and deadlock if another
2713 // thread has locked klass.
2714 if (lock.Acquired()) {
2715 // Check for circular dependencies between classes, the lock is required for SetStatus.
2716 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2717 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002718 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002719 return nullptr;
2720 }
2721 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002722 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002723 {
2724 // Handle wrapper deals with klass moving.
2725 ScopedThreadSuspension sts(self, kSuspended);
2726 if (index < kNumYieldIterations) {
2727 sched_yield();
2728 } else {
2729 usleep(kSleepDurationUS);
2730 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002731 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002732 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002733 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002734
Vladimir Marko72ab6842017-01-20 19:32:50 +00002735 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002736 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002737 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002738 }
2739 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002740 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002741 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002742 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002743}
2744
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002745using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002746
2747// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002748ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002749 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002750 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002751 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002752 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002753 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002754 return ClassPathEntry(dex_file, dex_class_def);
2755 }
2756 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002757 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002758}
2759
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002760bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2761 Thread* self,
2762 const char* descriptor,
2763 size_t hash,
2764 Handle<mirror::ClassLoader> class_loader,
2765 /*out*/ ObjPtr<mirror::Class>* result) {
2766 ArtField* field =
2767 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2768 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2769 if (raw_shared_libraries == nullptr) {
2770 return true;
2771 }
2772
2773 StackHandleScope<2> hs(self);
2774 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2775 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2776 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002777 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2778 temp_loader.Assign(loader);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002779 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2780 return false; // One of the shared libraries is not supported.
2781 }
2782 if (*result != nullptr) {
2783 return true; // Found the class up the chain.
2784 }
2785 }
2786 return true;
2787}
2788
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002789bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2790 Thread* self,
2791 const char* descriptor,
2792 size_t hash,
2793 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002794 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002795 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002796 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002797 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002798 return true;
2799 }
2800
David Brazdil05909d82018-12-06 16:25:16 +00002801 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002802 // For regular path or dex class loader the search order is:
2803 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002804 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002805 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002806
Calin Juravlecdd49122017-07-05 20:09:53 -07002807 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2808 StackHandleScope<1> hs(self);
2809 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2810 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2811 return false; // One of the parents is not supported.
2812 }
2813 if (*result != nullptr) {
2814 return true; // Found the class up the chain.
2815 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002816
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002817 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2818 return false; // One of the shared library loader is not supported.
2819 }
2820 if (*result != nullptr) {
2821 return true; // Found the class in a shared library.
2822 }
2823
Calin Juravlecdd49122017-07-05 20:09:53 -07002824 // Search the current class loader classpath.
2825 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002826 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002827 }
2828
Calin Juravlecdd49122017-07-05 20:09:53 -07002829 if (IsDelegateLastClassLoader(soa, class_loader)) {
2830 // For delegate last, the search order is:
2831 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002832 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002833 // - class loader dex files
2834 // - parent
2835 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2836 if (*result != nullptr) {
2837 return true; // The class is part of the boot class path.
2838 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002839 if (self->IsExceptionPending()) {
2840 // Pending exception means there was an error other than ClassNotFound that must be returned
2841 // to the caller.
2842 return false;
2843 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002844
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002845 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2846 return false; // One of the shared library loader is not supported.
2847 }
2848 if (*result != nullptr) {
2849 return true; // Found the class in a shared library.
2850 }
2851
Calin Juravlecdd49122017-07-05 20:09:53 -07002852 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2853 if (*result != nullptr) {
2854 return true; // Found the class in the current class loader
2855 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002856 if (self->IsExceptionPending()) {
2857 // Pending exception means there was an error other than ClassNotFound that must be returned
2858 // to the caller.
2859 return false;
2860 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002861
2862 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2863 StackHandleScope<1> hs(self);
2864 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2865 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2866 }
2867
2868 // Unsupported class loader.
2869 *result = nullptr;
2870 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002871}
2872
Andreas Gampe501c3b02019-04-17 21:54:27 +00002873namespace {
2874
2875// Matches exceptions caught in DexFile.defineClass.
2876ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2877 ClassLinker* class_linker)
2878 REQUIRES_SHARED(Locks::mutator_lock_) {
2879 return
2880 // ClassNotFoundException.
2881 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2882 class_linker))
2883 ||
2884 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2885 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2886}
2887
2888// Clear exceptions caught in DexFile.defineClass.
2889ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2890 REQUIRES_SHARED(Locks::mutator_lock_) {
2891 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2892 self->ClearException();
2893 }
2894}
2895
2896} // namespace
2897
Calin Juravle415dc3d2017-06-28 11:03:12 -07002898// Finds the class in the boot class loader.
2899// If the class is found the method returns the resolved class. Otherwise it returns null.
2900ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2901 const char* descriptor,
2902 size_t hash) {
2903 ObjPtr<mirror::Class> result = nullptr;
2904 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2905 if (pair.second != nullptr) {
2906 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2907 if (klass != nullptr) {
2908 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002909 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002910 result = DefineClass(self,
2911 descriptor,
2912 hash,
2913 ScopedNullHandle<mirror::ClassLoader>(),
2914 *pair.first,
2915 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002916 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002917 if (result == nullptr) {
2918 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002919 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002920 }
2921 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002922 return result;
2923}
Andreas Gampef865ea92015-04-13 22:14:19 -07002924
Calin Juravle415dc3d2017-06-28 11:03:12 -07002925ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2926 ScopedObjectAccessAlreadyRunnable& soa,
2927 const char* descriptor,
2928 size_t hash,
2929 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002930 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2931 IsInMemoryDexClassLoader(soa, class_loader) ||
2932 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002933 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002934
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002935 ObjPtr<mirror::Class> ret;
2936 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002937 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002938 if (dex_class_def != nullptr) {
2939 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2940 descriptor,
2941 hash,
2942 class_loader,
2943 *cp_dex_file,
2944 *dex_class_def);
2945 if (klass == nullptr) {
2946 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002947 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002948 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00002949 } else {
2950 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002951 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002952 ret = klass;
2953 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002954 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002955 return true; // Continue with the next DexFile.
2956 };
2957
2958 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2959 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002960}
2961
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002962ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2963 const char* descriptor,
2964 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002965 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002966 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002967 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002968 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002969 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002970 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2971 // for primitive classes that aren't backed by dex files.
2972 return FindPrimitiveClass(descriptor[0]);
2973 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002974 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002975 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002976 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002977 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002978 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002979 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002980 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002981 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002982 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002983 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002984 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002985 return DefineClass(self,
2986 descriptor,
2987 hash,
2988 ScopedNullHandle<mirror::ClassLoader>(),
2989 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002990 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002991 } else {
2992 // The boot class loader is searched ahead of the application class loader, failures are
2993 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2994 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002995 ObjPtr<mirror::Throwable> pre_allocated =
2996 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002997 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002998 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002999 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003000 }
3001 ObjPtr<mirror::Class> result_ptr;
3002 bool descriptor_equals;
3003 if (descriptor[0] == '[') {
3004 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
3005 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
3006 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
3007 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05003008 } else {
Ian Rogers98379392014-02-24 16:53:16 -08003009 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003010 bool known_hierarchy =
3011 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
3012 if (result_ptr != nullptr) {
3013 // The chain was understood and we found the class. We still need to add the class to
3014 // the class table to protect from racy programs that can try and redefine the path list
3015 // which would change the Class<?> returned for subsequent evaluation of const-class.
3016 DCHECK(known_hierarchy);
3017 DCHECK(result_ptr->DescriptorEquals(descriptor));
3018 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003019 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003020 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00003021 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
3022 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003023 //
3024 // If the chain was understood but we did not find the class, let the Java-side
3025 // rediscover all this and throw the exception with the right stack trace. Note that
3026 // the Java-side could still succeed for racy programs if another thread is actively
3027 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07003028
Alex Light185a4612018-10-04 15:54:25 -07003029 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07003030 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00003031 // Oops, we can't call into java so we can't run actual class-loader code.
3032 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003033 ObjPtr<mirror::Throwable> pre_allocated =
3034 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3035 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003036 return nullptr;
3037 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003038
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003039 // Inlined DescriptorToDot(descriptor) with extra validation.
3040 //
3041 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
3042 // the DescriptorEquals() check below and give a confusing error message. For example,
3043 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
3044 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
3045 // "class loader [...] returned class java.lang.String instead of java.lang.String".
3046 size_t descriptor_length = strlen(descriptor);
3047 if (UNLIKELY(descriptor[0] != 'L') ||
3048 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
3049 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
3050 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
3051 return nullptr;
3052 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003053
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003054 std::string class_name_string(descriptor + 1, descriptor_length - 2);
3055 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00003056 if (known_hierarchy &&
3057 fast_class_not_found_exceptions_ &&
3058 !Runtime::Current()->IsJavaDebuggable()) {
3059 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
3060 // debuggable, optimize this path by throwing directly here without going back to Java
3061 // language. This reduces how many ClassNotFoundExceptions happen.
3062 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
3063 "%s",
3064 class_name_string.c_str());
3065 } else {
3066 ScopedLocalRef<jobject> class_loader_object(
3067 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
3068 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
3069 {
3070 ScopedThreadStateChange tsc(self, kNative);
3071 ScopedLocalRef<jobject> class_name_object(
3072 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
3073 if (class_name_object.get() == nullptr) {
3074 DCHECK(self->IsExceptionPending()); // OOME.
3075 return nullptr;
3076 }
3077 CHECK(class_loader_object.get() != nullptr);
3078 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
3079 WellKnownClasses::java_lang_ClassLoader_loadClass,
3080 class_name_object.get()));
3081 }
3082 if (result.get() == nullptr && !self->IsExceptionPending()) {
3083 // broken loader - throw NPE to be compatible with Dalvik
3084 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
3085 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003086 return nullptr;
3087 }
Andreas Gampe87658f32019-04-18 18:39:02 +00003088 result_ptr = soa.Decode<mirror::Class>(result.get());
3089 // Check the name of the returned class.
3090 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003091 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003092 } else {
3093 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003094 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003095 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003096
3097 if (self->IsExceptionPending()) {
3098 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3099 // However, to comply with the RI behavior, first check if another thread succeeded.
3100 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3101 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3102 self->ClearException();
3103 return EnsureResolved(self, descriptor, result_ptr);
3104 }
3105 return nullptr;
3106 }
3107
3108 // Try to insert the class to the class table, checking for mismatch.
3109 ObjPtr<mirror::Class> old;
3110 {
3111 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3112 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3113 old = class_table->Lookup(descriptor, hash);
3114 if (old == nullptr) {
3115 old = result_ptr; // For the comparison below, after releasing the lock.
3116 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003117 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003118 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003119 } // else throw below, after releasing the lock.
3120 }
3121 }
3122 if (UNLIKELY(old != result_ptr)) {
3123 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3124 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003125 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003126 const char* loader_class_name =
3127 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3128 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3129 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3130 << DescriptorToDot(descriptor) << "\").";
3131 return EnsureResolved(self, descriptor, old);
3132 }
3133 if (UNLIKELY(!descriptor_equals)) {
3134 std::string result_storage;
3135 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3136 std::string loader_storage;
3137 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3138 ThrowNoClassDefFoundError(
3139 "Initiating class loader of type %s returned class %s instead of %s.",
3140 DescriptorToDot(loader_class_name).c_str(),
3141 DescriptorToDot(result_name).c_str(),
3142 DescriptorToDot(descriptor).c_str());
3143 return nullptr;
3144 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003145 // Success.
3146 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003147}
3148
Vladimir Markob9c29f62019-03-20 14:22:51 +00003149static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3150 std::string_view descriptor_sv(descriptor);
Vladimir Marko29885b32019-04-03 10:09:26 +01003151 return
3152 // Reserved conscrypt packages (includes sub-packages under these paths).
3153 StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3154 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/") ||
3155 // Reserved updatable-media package (includes sub-packages under this path).
3156 StartsWith(descriptor_sv, "Landroid/media/");
Vladimir Markob9c29f62019-03-20 14:22:51 +00003157}
3158
Alex Light270db1c2019-12-03 12:20:01 +00003159// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3160// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3161// like pausing class definition.
3162struct ScopedDefiningClass {
3163 public:
3164 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3165 : self_(self), returned_(false) {
3166 Locks::mutator_lock_->AssertSharedHeld(self_);
3167 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3168 self_->IncrDefineClassCount();
3169 }
3170 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3171 Locks::mutator_lock_->AssertSharedHeld(self_);
3172 CHECK(returned_);
3173 }
3174
3175 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3176 REQUIRES_SHARED(Locks::mutator_lock_) {
3177 CHECK(!returned_);
3178 self_->DecrDefineClassCount();
3179 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3180 Thread::PoisonObjectPointersIfDebug();
3181 returned_ = true;
3182 return h_klass.Get();
3183 }
3184
3185 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3186 REQUIRES_SHARED(Locks::mutator_lock_) {
3187 StackHandleScope<1> hs(self_);
3188 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3189 return Finish(h_klass);
3190 }
3191
3192 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3193 REQUIRES_SHARED(Locks::mutator_lock_) {
3194 ScopedNullHandle<mirror::Class> snh;
3195 return Finish(snh);
3196 }
3197
3198 private:
3199 Thread* self_;
3200 bool returned_;
3201};
3202
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003203ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3204 const char* descriptor,
3205 size_t hash,
3206 Handle<mirror::ClassLoader> class_loader,
3207 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003208 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003209 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003210 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003211 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003212
Brian Carlstromaded5f72011-10-07 17:15:04 -07003213 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003214 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003215 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003216 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003217 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003218 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003219 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003220 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003221 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003222 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003223 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003224 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003225 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003226 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003227 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003228 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003229 }
3230
Vladimir Markob9c29f62019-03-20 14:22:51 +00003231 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3232 // some runtime modules. Prevent definition of classes in app class loader that could clash
3233 // with these modules as these classes could be resolved differently during execution.
3234 if (class_loader != nullptr &&
3235 Runtime::Current()->IsAotCompiler() &&
3236 IsReservedBootClassPathDescriptor(descriptor)) {
3237 ObjPtr<mirror::Throwable> pre_allocated =
3238 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3239 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003240 return sdc.Finish(nullptr);
Vladimir Markob9c29f62019-03-20 14:22:51 +00003241 }
3242
Alex Lighte9f61032018-09-24 16:04:51 -07003243 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3244 // code to be executed. We put it up here so we can avoid all the allocations associated with
3245 // creating the class. This can happen with (eg) jit threads.
3246 if (!self->CanLoadClasses()) {
3247 // Make sure we don't try to load anything, potentially causing an infinite loop.
3248 ObjPtr<mirror::Throwable> pre_allocated =
3249 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3250 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003251 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003252 }
3253
Andreas Gampefa4333d2017-02-14 11:10:34 -08003254 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003255 // Allocate a class with the status of not ready.
3256 // Interface object should get the right size here. Regular class will
3257 // figure out the right size later and be replaced with one of the right
3258 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003259 if (CanAllocClass()) {
3260 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3261 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003262 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003263 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003264 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003265 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003266 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003267 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003268 }
Alex Lightb0f11922017-01-23 14:25:17 -08003269 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3270 // nothing.
3271 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003272 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003273 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3274 // will only be called once.
3275 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3276 klass,
3277 class_loader,
3278 dex_file,
3279 dex_class_def,
3280 &new_dex_file,
3281 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003282 // Check to see if an exception happened during runtime callbacks. Return if so.
3283 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003284 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003285 }
Alex Lightb0f11922017-01-23 14:25:17 -08003286 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003287 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003288 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003289 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003290 }
3291 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003292 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003293
Jeff Hao848f70a2014-01-15 13:49:50 -08003294 // Mark the string class by setting its access flag.
3295 if (UNLIKELY(!init_done_)) {
3296 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3297 klass->SetStringClass();
3298 }
3299 }
3300
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003301 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003302 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003303 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003304 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003305
Mathieu Chartier590fee92013-09-13 13:46:47 -07003306 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003307 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003308 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003309 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3310 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003311 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003312 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003313
Mathieu Chartierc7853442015-03-27 14:35:38 -07003314 // Load the fields and other things after we are inserted in the table. This is so that we don't
3315 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3316 // other reason is that the field roots are only visited from the class table. So we need to be
3317 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003318 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003319 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003320 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003321 // An exception occured during load, set status to erroneous while holding klass' lock in case
3322 // notification is necessary.
3323 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003324 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003325 }
Alex Light270db1c2019-12-03 12:20:01 +00003326 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003327 }
3328
Brian Carlstromaded5f72011-10-07 17:15:04 -07003329 // Finish loading (if necessary) by finding parents
3330 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003331 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003332 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003333 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003334 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003335 }
Alex Light270db1c2019-12-03 12:20:01 +00003336 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003337 }
3338 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003339
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003340 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003341 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003342 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003343
Brian Carlstromaded5f72011-10-07 17:15:04 -07003344 // Link the class (if necessary)
3345 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003346 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003347 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003348
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003349 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003350 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003351 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003352 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003353 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003354 }
Alex Light270db1c2019-12-03 12:20:01 +00003355 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003356 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003357 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003358 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003359 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003360
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003361 // Instrumentation may have updated entrypoints for all methods of all
3362 // classes. However it could not update methods of this class while we
3363 // were loading it. Now the class is resolved, we can update entrypoints
3364 // as required by instrumentation.
3365 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3366 // We must be in the kRunnable state to prevent instrumentation from
3367 // suspending all threads to update entrypoints while we are doing it
3368 // for this class.
3369 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003370 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003371 }
3372
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003373 /*
3374 * We send CLASS_PREPARE events to the debugger from here. The
3375 * definition of "preparation" is creating the static fields for a
3376 * class and initializing them to the standard default values, but not
3377 * executing any code (that comes later, during "initialization").
3378 *
3379 * We did the static preparation in LinkClass.
3380 *
3381 * The class has been prepared and resolved but possibly not yet verified
3382 * at this point.
3383 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003384 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003385
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003386 // Notify native debugger of the new class and its layout.
3387 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3388
Alex Light270db1c2019-12-03 12:20:01 +00003389 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003390}
3391
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003392uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003393 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003394 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003395 size_t num_8 = 0;
3396 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003397 size_t num_32 = 0;
3398 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003399 ClassAccessor accessor(dex_file, dex_class_def);
3400 // We allow duplicate definitions of the same field in a class_data_item
3401 // but ignore the repeated indexes here, b/21868015.
3402 uint32_t last_field_idx = dex::kDexNoIndex;
3403 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3404 uint32_t field_idx = field.GetIndex();
3405 // Ordering enforced by DexFileVerifier.
3406 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3407 if (UNLIKELY(field_idx == last_field_idx)) {
3408 continue;
3409 }
3410 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003411 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003412 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3413 char c = descriptor[0];
3414 switch (c) {
3415 case 'L':
3416 case '[':
3417 num_ref++;
3418 break;
3419 case 'J':
3420 case 'D':
3421 num_64++;
3422 break;
3423 case 'I':
3424 case 'F':
3425 num_32++;
3426 break;
3427 case 'S':
3428 case 'C':
3429 num_16++;
3430 break;
3431 case 'B':
3432 case 'Z':
3433 num_8++;
3434 break;
3435 default:
3436 LOG(FATAL) << "Unknown descriptor: " << c;
3437 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003438 }
3439 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003440 return mirror::Class::ComputeClassSize(false,
3441 0,
3442 num_8,
3443 num_16,
3444 num_32,
3445 num_64,
3446 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003447 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003448}
3449
Alex Lightfc49fec2018-01-16 22:28:36 +00003450// Special case to get oat code without overwriting a trampoline.
3451const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003452 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003453 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003454 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003455 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003456 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003457 if (code != nullptr) {
3458 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003459 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003460
3461 jit::Jit* jit = Runtime::Current()->GetJit();
3462 if (jit != nullptr) {
3463 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3464 if (code != nullptr) {
3465 return code;
3466 }
3467 }
3468
Alex Lightfc49fec2018-01-16 22:28:36 +00003469 if (method->IsNative()) {
3470 // No code and native? Use generic trampoline.
3471 return GetQuickGenericJniStub();
3472 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003473
3474 if (interpreter::CanRuntimeUseNterp() && interpreter::CanMethodUseNterp(method)) {
3475 return interpreter::GetNterpEntryPoint();
3476 }
3477
Alex Lightfc49fec2018-01-16 22:28:36 +00003478 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003479}
3480
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003481bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003482 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003483 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3484 return false;
3485 }
3486
Elliott Hughes956af0f2014-12-11 14:34:28 -08003487 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003488 return true;
3489 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003490
3491 Runtime* runtime = Runtime::Current();
3492 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3493 if (instr->InterpretOnly()) {
3494 return true;
3495 }
3496
3497 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3498 // Doing this check avoids doing compiled/interpreter transitions.
3499 return true;
3500 }
3501
Alex Lightfc588092020-01-23 15:39:08 -08003502 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003503 // Force the use of interpreter when it is required by the debugger.
3504 return true;
3505 }
3506
Alex Light8f34aba2017-10-09 13:46:32 -07003507 if (Thread::Current()->IsAsyncExceptionPending()) {
3508 // Force use of interpreter to handle async-exceptions
3509 return true;
3510 }
3511
Alex Light2d441b12018-06-08 15:33:21 -07003512 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3513 const void* instr_target = instr->GetCodeForInvoke(method);
3514 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3515 return ShouldUseInterpreterEntrypoint(method, instr_target);
3516 }
3517
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003518 if (runtime->IsJavaDebuggable()) {
3519 // For simplicity, we ignore precompiled code and go to the interpreter
3520 // assuming we don't already have jitted code.
3521 // We could look at the oat file where `quick_code` is being defined,
3522 // and check whether it's been compiled debuggable, but we decided to
3523 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003524 jit::Jit* jit = Runtime::Current()->GetJit();
3525 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3526 }
3527
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003528 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003529 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003530 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003531 // since we want to JIT it (at first use) with extra stackmaps for native
3532 // debugging. We keep however all AOT code from the boot image,
3533 // since the JIT-at-first-use is blocking and would result in non-negligible
3534 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003535 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003536 }
3537
3538 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003539}
3540
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003541void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003542 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003543 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003544 if (klass->NumDirectMethods() == 0) {
3545 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003546 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003547 if (UNLIKELY(klass->IsProxyClass())) {
3548 return;
3549 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003550 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003551 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003552 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003553 return; // OAT file unavailable.
3554 }
Ian Rogers19846512012-02-24 11:42:47 -08003555 }
Alex Light64ad14d2014-08-19 14:23:13 -07003556
Mathieu Chartierf8322842014-05-16 10:59:25 -07003557 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003558 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3559 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3560 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003561 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003562 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003563 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003564 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3565 klass->GetDexClassDefIndex(),
3566 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003567 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003568 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003569 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003570 if (!method->IsStatic()) {
3571 // Only update static methods.
3572 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003573 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003574 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003575
3576 // In order:
3577 // 1) Check if we have AOT Code.
3578 // 2) Check if we have JIT Code.
3579 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003580 if (has_oat_class) {
3581 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003582 quick_code = oat_method.GetQuickCode();
3583 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003584
Vladimir Markocce414f2019-10-07 08:51:33 +01003585 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003586 if (quick_code == nullptr && jit != nullptr) {
3587 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003588 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003589
3590 if (quick_code == nullptr &&
3591 interpreter::CanRuntimeUseNterp() &&
3592 interpreter::CanMethodUseNterp(method)) {
3593 quick_code = interpreter::GetNterpEntryPoint();
3594 }
3595
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003596 // Check whether the method is native, in which case it's generic JNI.
3597 if (quick_code == nullptr && method->IsNative()) {
3598 quick_code = GetQuickGenericJniStub();
3599 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003600 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003601 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3602 // If we have the trampoline or the bridge already, no need to update.
3603 // This saves in not dirtying boot image memory.
3604 continue;
3605 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003606 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003607 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003608 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003609 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003610 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003611 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003612}
3613
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003614// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3615// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003616inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3617 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003618 DCHECK(method != nullptr);
3619 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003620 method->SetEntryPointFromQuickCompiledCodePtrSize(
3621 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3622 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003623}
3624
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003625static void LinkCode(ClassLinker* class_linker,
3626 ArtMethod* method,
3627 const OatFile::OatClass* oat_class,
3628 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003629 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003630 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003631 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003632 // The following code only applies to a non-compiler runtime.
3633 return;
3634 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003635
Ian Rogers62d6c772013-02-27 08:32:07 -08003636 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003637 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003638
Alex Light9139e002015-10-09 15:59:48 -07003639 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003640 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003641 return;
3642 }
Ian Rogers19846512012-02-24 11:42:47 -08003643
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003644 const void* quick_code = nullptr;
3645 if (oat_class != nullptr) {
3646 // Every kind of method should at least get an invoke stub from the oat_method.
3647 // non-abstract methods also get their code pointers.
3648 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3649 quick_code = oat_method.GetQuickCode();
3650 }
3651
3652 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3653
3654 // Note: this mimics the logic in image_writer.cc that installs the resolution
3655 // stub only if we have compiled code and the method needs a class initialization
3656 // check.
3657 if (quick_code == nullptr) {
3658 method->SetEntryPointFromQuickCompiledCode(
3659 method->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge());
3660 } else if (enter_interpreter) {
3661 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003662 } else if (NeedsClinitCheckBeforeCall(method)) {
3663 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3664 // If we do have code but the method needs a class initialization check before calling
3665 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003666 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3667 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003668 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003669 } else {
3670 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003671 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003672
Ian Rogers62d6c772013-02-27 08:32:07 -08003673 if (method->IsNative()) {
3674 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003675 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003676
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003677 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003678 // We have a native method here without code. Then it should have the generic JNI
3679 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003680 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003681 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003682 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003683 }
3684}
3685
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003686void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003687 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003688 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003689 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003690 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003691 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003692 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003693 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003694 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003695
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003696 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003697 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003698 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003699 klass->SetAccessFlags(access_flags);
3700 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003701 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003702 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003703
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003704 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003705 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003706}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003707
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003708LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3709 LinearAlloc* allocator,
3710 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003711 if (length == 0) {
3712 return nullptr;
3713 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003714 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3715 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3716 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003717 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003718 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003719 CHECK(ret != nullptr);
3720 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3721 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003722}
3723
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003724LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3725 LinearAlloc* allocator,
3726 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003727 if (length == 0) {
3728 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003729 }
Vladimir Marko14632852015-08-17 12:07:23 +01003730 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3731 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003732 const size_t storage_size =
3733 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003734 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003735 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003736 CHECK(ret != nullptr);
3737 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003738 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003739 }
3740 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003741}
3742
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003743LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003744 if (class_loader == nullptr) {
3745 return Runtime::Current()->GetLinearAlloc();
3746 }
3747 LinearAlloc* allocator = class_loader->GetAllocator();
3748 DCHECK(allocator != nullptr);
3749 return allocator;
3750}
3751
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003752LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003753 if (class_loader == nullptr) {
3754 return Runtime::Current()->GetLinearAlloc();
3755 }
3756 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3757 LinearAlloc* allocator = class_loader->GetAllocator();
3758 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003759 RegisterClassLoader(class_loader);
3760 allocator = class_loader->GetAllocator();
3761 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003762 }
3763 return allocator;
3764}
3765
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003766void ClassLinker::LoadClass(Thread* self,
3767 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003768 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003769 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003770 ClassAccessor accessor(dex_file,
3771 dex_class_def,
3772 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003773 if (!accessor.HasClassData()) {
3774 return;
3775 }
3776 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003777 {
3778 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3779 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003780 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003781 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003782 // We allow duplicate definitions of the same field in a class_data_item
3783 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003784 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003785 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3786 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003787 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003788 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3789 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003790 accessor.NumInstanceFields());
3791 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003792 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003793 uint32_t last_static_field_idx = 0u;
3794 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003795
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003796 // Methods
3797 bool has_oat_class = false;
3798 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3799 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3800 : OatFile::OatClass::Invalid();
3801 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3802 klass->SetMethodsPtr(
3803 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3804 accessor.NumDirectMethods(),
3805 accessor.NumVirtualMethods());
3806 size_t class_def_method_index = 0;
3807 uint32_t last_dex_method_index = dex::kDexNoIndex;
3808 size_t last_class_def_method_index = 0;
3809
3810 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3811 // methods needs to decode all of the fields.
3812 accessor.VisitFieldsAndMethods([&](
3813 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3814 uint32_t field_idx = field.GetIndex();
3815 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3816 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3817 LoadField(field, klass, &sfields->At(num_sfields));
3818 ++num_sfields;
3819 last_static_field_idx = field_idx;
3820 }
3821 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3822 uint32_t field_idx = field.GetIndex();
3823 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3824 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3825 LoadField(field, klass, &ifields->At(num_ifields));
3826 ++num_ifields;
3827 last_instance_field_idx = field_idx;
3828 }
3829 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3830 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3831 image_pointer_size_);
3832 LoadMethod(dex_file, method, klass, art_method);
3833 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3834 uint32_t it_method_index = method.GetIndex();
3835 if (last_dex_method_index == it_method_index) {
3836 // duplicate case
3837 art_method->SetMethodIndex(last_class_def_method_index);
3838 } else {
3839 art_method->SetMethodIndex(class_def_method_index);
3840 last_dex_method_index = it_method_index;
3841 last_class_def_method_index = class_def_method_index;
3842 }
3843 ++class_def_method_index;
3844 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3845 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3846 class_def_method_index - accessor.NumDirectMethods(),
3847 image_pointer_size_);
3848 LoadMethod(dex_file, method, klass, art_method);
3849 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3850 ++class_def_method_index;
3851 });
3852
3853 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003854 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003855 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3856 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3857 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003858 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3859 if (sfields != nullptr) {
3860 sfields->SetSize(num_sfields);
3861 }
3862 if (ifields != nullptr) {
3863 ifields->SetSize(num_ifields);
3864 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003865 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003866 // Set the field arrays.
3867 klass->SetSFieldsPtr(sfields);
3868 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003869 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003870 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003871 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003872 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003873 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003874 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003875}
3876
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003877void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003878 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003879 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003880 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003881 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003882 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003883
David Brazdil85865692018-10-30 17:26:20 +00003884 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3885 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003886}
3887
Mathieu Chartier268764d2016-09-13 12:09:38 -07003888void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003889 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003890 Handle<mirror::Class> klass,
3891 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003892 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003893 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003894 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003895
Mathieu Chartier268764d2016-09-13 12:09:38 -07003896 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003897 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003898 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003899 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003900
David Brazdil85865692018-10-30 17:26:20 +00003901 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3902 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003903
Ian Rogersdfb325e2013-10-30 01:00:44 -07003904 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003905 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003906 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3907 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003908 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003909 klass->SetFinalizable();
3910 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003911 std::string temp;
3912 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003913 // The Enum class declares a "final" finalize() method to prevent subclasses from
3914 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3915 // subclasses, so we exclude it here.
3916 // We also want to avoid setting the flag on Object, where we know that finalize() is
3917 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003918 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3919 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003920 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003921 }
3922 }
3923 }
3924 } else if (method_name[0] == '<') {
3925 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003926 bool is_init = (strcmp("<init>", method_name) == 0);
3927 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003928 if (UNLIKELY(!is_init && !is_clinit)) {
3929 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3930 } else {
3931 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3932 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003933 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003934 access_flags |= kAccConstructor;
3935 }
3936 }
3937 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003938 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3939 // Check if the native method is annotated with @FastNative or @CriticalNative.
3940 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3941 dex_file, dst->GetClassDef(), dex_method_idx);
3942 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003943 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003944 // Must be done after SetAccessFlags since IsAbstract depends on it.
3945 if (klass->IsInterface() && dst->IsAbstract()) {
3946 dst->CalculateAndSetImtIndex();
3947 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003948}
3949
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003950void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003951 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003952 self,
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003953 *dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003954 Runtime::Current()->GetLinearAlloc());
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003955 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003956 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003957}
3958
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003959void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003960 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003961 CHECK(dex_file != nullptr);
3962 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3963 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003964 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003965 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003966}
3967
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003968void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003969 ObjPtr<mirror::DexCache> dex_cache,
3970 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003971 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003972 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003973 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003974 // For app images, the dex cache location may be a suffix of the dex file location since the
3975 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003976 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3977 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003978 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3979 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003980 // The following paths checks don't work on preopt when using boot dex files, where the dex
3981 // cache location is the one on device, and the dex_file's location is the one on host.
3982 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3983 CHECK_GE(dex_file_location.length(), dex_cache_length)
3984 << dex_cache_location << " " << dex_file.GetLocation();
3985 const std::string dex_file_suffix = dex_file_location.substr(
3986 dex_file_location.length() - dex_cache_length,
3987 dex_cache_length);
3988 // Example dex_cache location is SettingsProvider.apk and
3989 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3990 CHECK_EQ(dex_cache_location, dex_file_suffix);
3991 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003992 const OatFile* oat_file =
3993 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003994 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3995 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3996 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3997 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003998 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003999 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
4000 DexCacheData data = *it;
4001 if (self->IsJWeakCleared(data.weak_root)) {
4002 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004003 it = dex_caches_.erase(it);
4004 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00004005 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004006 it->dex_file->GetOatDexFile() != nullptr &&
4007 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00004008 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004009 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004010 ++it;
4011 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004012 }
Vladimir Markob066d432018-01-03 13:14:37 +00004013 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00004014 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004015 }
David Brazdila5c3a802019-03-08 14:59:41 +00004016 // Let hiddenapi assign a domain to the newly registered dex file.
4017 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
4018
Vladimir Markocd556b02017-02-03 11:47:34 +00004019 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004020 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004021 DexCacheData data;
4022 data.weak_root = dex_cache_jweak;
4023 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00004024 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00004025 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00004026 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004027 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
4028 // path dex caches without an image.
4029 data.class_table->InsertStrongRoot(dex_cache);
4030 if (class_loader != nullptr) {
4031 // Since we added a strong root to the class table, do the write barrier as required for
4032 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004033 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004034 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004035 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004036}
4037
Vladimir Markocd556b02017-02-03 11:47:34 +00004038ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
4039 return data.IsValid()
4040 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
4041 : nullptr;
4042}
4043
4044ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
4045 Thread* self,
4046 ObjPtr<mirror::DexCache> dex_cache,
4047 const DexCacheData& data,
4048 ObjPtr<mirror::ClassLoader> class_loader) {
4049 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
4050 if (data.class_table != ClassTableForClassLoader(class_loader)) {
4051 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
4052 "Attempt to register dex file %s with multiple class loaders",
4053 data.dex_file->GetLocation().c_str());
4054 return nullptr;
4055 }
4056 return dex_cache;
4057}
4058
Alex Light07f06212017-06-01 14:01:43 -07004059void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
4060 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004061 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07004062 Thread* self = Thread::Current();
4063 StackHandleScope<2> hs(self);
4064 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
4065 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
4066 const DexFile* dex_file = dex_cache->GetDexFile();
4067 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
4068 if (kIsDebugBuild) {
4069 DexCacheData old_data;
4070 {
4071 ReaderMutexLock mu(self, *Locks::dex_lock_);
4072 old_data = FindDexCacheDataLocked(*dex_file);
4073 }
4074 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
4075 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
4076 << "been registered on dex file " << dex_file->GetLocation();
4077 }
4078 ClassTable* table;
4079 {
4080 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4081 table = InsertClassTableForClassLoader(h_class_loader.Get());
4082 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004083 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4084 // a thread holding the dex lock and blocking on a condition variable regarding
4085 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004086 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07004087 WriterMutexLock mu(self, *Locks::dex_lock_);
4088 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
4089 table->InsertStrongRoot(h_dex_cache.Get());
4090 if (h_class_loader.Get() != nullptr) {
4091 // Since we added a strong root to the class table, do the write barrier as required for
4092 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004093 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004094 }
4095}
4096
Vladimir Markocd556b02017-02-03 11:47:34 +00004097ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4098 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004099 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00004100 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004101 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004102 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004103 old_data = FindDexCacheDataLocked(dex_file);
4104 }
4105 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
4106 if (old_dex_cache != nullptr) {
4107 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07004108 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004109 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004110 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4111 DCHECK(linear_alloc != nullptr);
4112 ClassTable* table;
4113 {
4114 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4115 table = InsertClassTableForClassLoader(class_loader);
4116 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004117 // Don't alloc while holding the lock, since allocation may need to
4118 // suspend all threads and another thread may need the dex_lock_ to
4119 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004120 StackHandleScope<3> hs(self);
4121 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004122 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07004123 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
4124 self,
4125 dex_file)));
4126 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004127 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004128 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4129 // a thread holding the dex lock and blocking on a condition variable regarding
4130 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004131 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004132 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004133 old_data = FindDexCacheDataLocked(dex_file);
4134 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004135 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004136 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
4137 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
4138 // that the arrays are null.
4139 mirror::DexCache::InitializeDexCache(self,
4140 h_dex_cache.Get(),
4141 h_location.Get(),
4142 &dex_file,
4143 linear_alloc,
4144 image_pointer_size_);
4145 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004146 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004147 }
4148 if (old_dex_cache != nullptr) {
4149 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4150 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004151 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00004152 self->ClearException();
4153 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
4154 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
4155 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004156 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004157 self->AssertPendingOOMException();
4158 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004159 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004160 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004161 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());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004165 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004166 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004167}
4168
Vladimir Markocd556b02017-02-03 11:47:34 +00004169bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004170 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004171 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004172}
4173
Vladimir Markocd556b02017-02-03 11:47:34 +00004174ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4175 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004176 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
4177 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004178 if (dex_cache != nullptr) {
4179 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004180 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004181 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004182 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004183 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004184 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004185 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004186 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004187 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
4188 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004189 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004190}
4191
Vladimir Markocd556b02017-02-03 11:47:34 +00004192ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4193 const DexFile* dex_file = dex_cache->GetDexFile();
4194 DCHECK(dex_file != nullptr);
4195 ReaderMutexLock mu(self, *Locks::dex_lock_);
4196 // Search assuming unique-ness of dex file.
4197 for (const DexCacheData& data : dex_caches_) {
4198 // Avoid decoding (and read barriers) other unrelated dex caches.
4199 if (data.dex_file == dex_file) {
4200 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
4201 if (registered_dex_cache != nullptr) {
4202 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4203 return data.class_table;
4204 }
4205 }
4206 }
4207 return nullptr;
4208}
4209
4210ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
4211 // Search assuming unique-ness of dex file.
4212 for (const DexCacheData& data : dex_caches_) {
4213 // Avoid decoding (and read barriers) other unrelated dex caches.
4214 if (data.dex_file == &dex_file) {
4215 return data;
4216 }
4217 }
4218 return DexCacheData();
4219}
4220
Vladimir Marko70e2a762019-07-12 16:49:00 +01004221void ClassLinker::CreatePrimitiveClass(Thread* self,
4222 Primitive::Type type,
4223 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004224 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004225 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004226 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4227 // Do not hold lock on the primitive class object, the initialization of
4228 // primitive classes is done while the process is still single threaded.
4229 primitive_class->SetAccessFlags(
4230 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4231 primitive_class->SetPrimitiveType(type);
4232 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4233 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4234 // the kAccVerificationAttempted flag was added above, and there are no
4235 // methods that need the kAccSkipAccessChecks flag.
4236 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004237 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4238 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004239 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004240 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004241 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004242 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004243 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004244 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004245}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004246
Vladimir Marko02610552018-06-04 14:38:00 +01004247inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4248 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4249}
4250
Brian Carlstrombe977852011-07-19 14:54:54 -07004251// Create an array class (i.e. the class object for the array, not the
4252// array itself). "descriptor" looks like "[C" or "[[[[B" or
4253// "[Ljava/lang/String;".
4254//
4255// If "descriptor" refers to an array of primitives, look up the
4256// primitive type's internally-generated class object.
4257//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004258// "class_loader" is the class loader of the class that's referring to
4259// us. It's used to ensure that we're looking for the element type in
4260// the right context. It does NOT become the class loader for the
4261// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004262//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004263// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004264ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4265 const char* descriptor,
4266 size_t hash,
4267 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004268 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004269 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004270 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004271
4272 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4273 // code to be executed. We put it up here so we can avoid all the allocations associated with
4274 // creating the class. This can happen with (eg) jit threads.
4275 if (!self->CanLoadClasses()) {
4276 // Make sure we don't try to load anything, potentially causing an infinite loop.
4277 ObjPtr<mirror::Throwable> pre_allocated =
4278 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4279 self->SetException(pre_allocated);
4280 return nullptr;
4281 }
4282
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004283 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4284 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004285 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004286 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004287 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004288 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4289 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004290 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004291 DCHECK(self->IsExceptionPending());
4292 return nullptr;
4293 } else {
4294 self->ClearException();
4295 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004296 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004297 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4298 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4299 return nullptr;
4300 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004301 // See if the component type is already loaded. Array classes are
4302 // always associated with the class loader of their underlying
4303 // element type -- an array of Strings goes with the loader for
4304 // java/lang/String -- so we need to look for it there. (The
4305 // caller should have checked for the existence of the class
4306 // before calling here, but they did so with *their* class loader,
4307 // not the component type's loader.)
4308 //
4309 // If we find it, the caller adds "loader" to the class' initiating
4310 // loader list, which should prevent us from going through this again.
4311 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004312 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004313 // are the same, because our caller (FindClass) just did the
4314 // lookup. (Even if we get this wrong we still have correct behavior,
4315 // because we effectively do this lookup again when we add the new
4316 // class to the hash table --- necessary because of possible races with
4317 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004318 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004319 ObjPtr<mirror::Class> new_class =
4320 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004321 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004322 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004323 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004324 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004325 // Core array classes, i.e. Object[], Class[], String[] and primitive
4326 // arrays, have special initialization and they should be found above.
4327 DCHECK(!component_type->IsObjectClass() ||
4328 // Guard from false positives for errors before setting superclass.
4329 component_type->IsErroneousUnresolved());
4330 DCHECK(!component_type->IsStringClass());
4331 DCHECK(!component_type->IsClassClass());
4332 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004333
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004334 // Fill out the fields in the Class.
4335 //
4336 // It is possible to execute some methods against arrays, because
4337 // all arrays are subclasses of java_lang_Object_, so we need to set
4338 // up a vtable. We can just point at the one in java_lang_Object_.
4339 //
4340 // Array classes are simple enough that we don't need to do a full
4341 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004342 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4343 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4344 size_t usable_size)
4345 REQUIRES_SHARED(Locks::mutator_lock_) {
4346 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4347 init_class(obj, usable_size);
4348 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4349 klass->SetComponentType(component_type.Get());
4350 // Do not hold lock for initialization, the fence issued after the visitor
4351 // returns ensures memory visibility together with the implicit consume
4352 // semantics (for all supported architectures) for any thread that loads
4353 // the array class reference from any memory locations afterwards.
4354 FinishArrayClassSetup(klass);
4355 };
4356 auto new_class = hs.NewHandle<mirror::Class>(
4357 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004358 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004359 self->AssertPendingOOMException();
4360 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004361 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004362
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004363 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004364 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004365 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4366 // duplicate events in case of races. Array classes don't really follow dedicated
4367 // load and prepare, anyways.
4368 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4369 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4370
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004371 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004372 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004373 }
4374 // Another thread must have loaded the class after we
4375 // started but before we finished. Abandon what we've
4376 // done.
4377 //
4378 // (Yes, this happens.)
4379
Vladimir Markobcf17522018-06-01 13:14:32 +01004380 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004381}
4382
Vladimir Marko9186b182018-11-06 14:55:54 +00004383ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4384 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004385 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004386 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4387 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4388 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4389 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4390 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4391 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4392 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4393 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4394 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004395 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004396 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004397 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004398 return GetClassRoot(class_root, this);
4399}
4400
4401ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4402 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4403 if (UNLIKELY(result == nullptr)) {
4404 std::string printable_type(PrintableChar(type));
4405 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4406 }
4407 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004408}
4409
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004410ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4411 ObjPtr<mirror::Class> klass,
4412 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004413 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004414 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004415 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004416 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004417 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004418 source += " from ";
4419 source += dex_cache->GetLocation()->ToModifiedUtf8();
4420 }
4421 LOG(INFO) << "Loaded class " << descriptor << source;
4422 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004423 {
4424 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004425 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004426 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004427 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004428 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004429 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004430 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004431 VerifyObject(klass);
4432 class_table->InsertWithHash(klass, hash);
4433 if (class_loader != nullptr) {
4434 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004435 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004436 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004437 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004438 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004439 }
4440 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004441 if (kIsDebugBuild) {
4442 // Test that copied methods correctly can find their holder.
4443 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4444 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4445 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004446 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004447 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004448}
4449
Vladimir Marko1998cd02017-01-13 13:02:58 +00004450void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004451 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4452 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4453 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4454 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004455 }
4456}
4457
Alex Lighte64300b2015-12-15 15:02:47 -08004458// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004459void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004460 LengthPrefixedArray<ArtMethod>* new_methods) {
4461 klass->SetMethodsPtrUnchecked(new_methods,
4462 klass->NumDirectMethods(),
4463 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004464 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004465 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004466}
4467
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004468ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4469 const char* descriptor,
4470 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004471 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4472}
4473
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004474ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4475 const char* descriptor,
4476 size_t hash,
4477 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004478 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4479 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4480 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004481 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004482 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004483 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004484 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004485 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004486 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004487}
4488
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004489class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4490 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004491 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004492
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004493 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004494 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004495 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004496 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004497 if (class_table != nullptr) {
4498 class_table->FreezeSnapshot();
4499 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004500 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004501};
4502
4503void ClassLinker::MoveClassTableToPreZygote() {
4504 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004505 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004506 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004507 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004508}
4509
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004510// Look up classes by hash and descriptor and put all matching ones in the result array.
4511class LookupClassesVisitor : public ClassLoaderVisitor {
4512 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004513 LookupClassesVisitor(const char* descriptor,
4514 size_t hash,
4515 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004516 : descriptor_(descriptor),
4517 hash_(hash),
4518 result_(result) {}
4519
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004520 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004521 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004522 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004523 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004524 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4525 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004526 result_->push_back(klass);
4527 }
4528 }
4529
4530 private:
4531 const char* const descriptor_;
4532 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004533 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004534};
4535
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004536void ClassLinker::LookupClasses(const char* descriptor,
4537 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004538 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004539 Thread* const self = Thread::Current();
4540 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004541 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004542 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004543 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004544 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004545 result.push_back(klass);
4546 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004547 LookupClassesVisitor visitor(descriptor, hash, &result);
4548 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004549}
4550
Alex Lightf1f10492015-10-07 16:08:36 -07004551bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4552 Handle<mirror::Class> klass,
4553 Handle<mirror::Class> supertype) {
4554 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004555 DCHECK(klass != nullptr);
4556 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004557
Alex Lightf1f10492015-10-07 16:08:36 -07004558 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4559 VerifyClass(self, supertype);
4560 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004561
4562 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4563 // The supertype is either verified, or we soft failed at AOT time.
4564 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004565 return true;
4566 }
4567 // If we got this far then we have a hard failure.
4568 std::string error_msg =
4569 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004570 klass->PrettyDescriptor().c_str(),
4571 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004572 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004573 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004574 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004575 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004576 // Set during VerifyClass call (if at all).
4577 self->ClearException();
4578 }
4579 // Change into a verify error.
4580 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004581 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004582 self->GetException()->SetCause(cause.Get());
4583 }
4584 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4585 if (Runtime::Current()->IsAotCompiler()) {
4586 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4587 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004588 // Need to grab the lock to change status.
4589 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004590 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004591 return false;
4592}
4593
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004594verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004595 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004596 {
4597 // TODO: assert that the monitor on the Class is held
4598 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004599
Andreas Gampe884f3b82016-03-30 19:52:58 -07004600 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004601 ClassStatus old_status = klass->GetStatus();
4602 while (old_status == ClassStatus::kVerifying ||
4603 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004604 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004605 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4606 // case we may see the same status again. b/62912904. This is why the check is
4607 // greater or equal.
4608 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004609 << "Class '" << klass->PrettyClass()
4610 << "' performed an illegal verification state transition from " << old_status
4611 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004612 old_status = klass->GetStatus();
4613 }
jeffhao98eacac2011-09-14 16:11:53 -07004614
Andreas Gampe884f3b82016-03-30 19:52:58 -07004615 // The class might already be erroneous, for example at compile time if we attempted to verify
4616 // this class as a parent to another.
4617 if (klass->IsErroneous()) {
4618 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004619 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004620 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004621
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004622 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004623 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004624 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004625 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004626 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004627
4628 // For AOT, don't attempt to re-verify if we have already found we should
4629 // verify at runtime.
4630 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004631 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004632 }
jeffhao98eacac2011-09-14 16:11:53 -07004633
Vladimir Marko2c64a832018-01-04 11:31:56 +00004634 if (klass->GetStatus() == ClassStatus::kResolved) {
4635 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004636 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004637 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004638 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004639 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004640 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004641 }
4642
4643 // Skip verification if disabled.
4644 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004645 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004646 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004647 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004648 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004649 }
4650
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004651 VLOG(class_linker) << "Beginning verification for class: "
4652 << klass->PrettyDescriptor()
4653 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4654
Ian Rogers9ffb0392012-09-10 11:56:50 -07004655 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004656 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004657 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4658 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004659 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004660 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004661 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004662 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004663
Alex Lightf1f10492015-10-07 16:08:36 -07004664 // Verify all default super-interfaces.
4665 //
4666 // (1) Don't bother if the superclass has already had a soft verification failure.
4667 //
4668 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4669 // recursive initialization by themselves. This is because when an interface is initialized
4670 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4671 // but choose not to for an optimization. If the interfaces is being verified due to a class
4672 // initialization (which would need all the default interfaces to be verified) the class code
4673 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004674 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004675 && !klass->IsInterface()) { // See (2)
4676 int32_t iftable_count = klass->GetIfTableCount();
4677 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4678 // Loop through all interfaces this class has defined. It doesn't matter the order.
4679 for (int32_t i = 0; i < iftable_count; i++) {
4680 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004681 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004682 // We only care if we have default interfaces and can skip if we are already verified...
4683 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4684 continue;
4685 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4686 // We had a hard failure while verifying this interface. Just return immediately.
4687 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004688 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004689 } else if (UNLIKELY(!iface->IsVerified())) {
4690 // We softly failed to verify the iface. Stop checking and clean up.
4691 // Put the iface into the supertype handle so we know what caused us to fail.
4692 supertype.Assign(iface.Get());
4693 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004694 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004695 }
4696 }
4697
Alex Lightf1f10492015-10-07 16:08:36 -07004698 // At this point if verification failed, then supertype is the "first" supertype that failed
4699 // verification (without a specific order). If verification succeeded, then supertype is either
4700 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004701 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004702 supertype.Get() == klass->GetSuperClass() ||
4703 !supertype->IsVerified());
4704
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004705 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004706 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004707 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004708 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004709
4710 VLOG(class_linker) << "Class preverified status for class "
4711 << klass->PrettyDescriptor()
4712 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4713 << ": "
4714 << preverified;
4715
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004716 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4717 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004718 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4719 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004720
Ian Rogers62d6c772013-02-27 08:32:07 -08004721 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004722 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004723 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004724 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004725 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004726
4727 // Verification is done, grab the lock again.
4728 ObjectLock<mirror::Class> lock(self, klass);
4729
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004730 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4731 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004732 VLOG(class_linker) << "Soft verification failure in class "
4733 << klass->PrettyDescriptor()
4734 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4735 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004736 }
Ian Rogers1f539342012-10-03 21:09:42 -07004737 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004738 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004739 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004740 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004741 // Even though there were no verifier failures we need to respect whether the super-class and
4742 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004743 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004744 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004745 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004746 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4747 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004748 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004749 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004750 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004751 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004752 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004753 // Soft failures at compile time should be retried at runtime. Soft
4754 // failures at runtime will be handled by slow paths in the generated
4755 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004756 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004757 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004758 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004759 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004760 // As this is a fake verified status, make sure the methods are _not_ marked
4761 // kAccSkipAccessChecks later.
4762 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004763 }
4764 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004765 } else {
David Sehr709b0702016-10-13 09:12:37 -07004766 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004767 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4768 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004769 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004770 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004771 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004772 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004773 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004774 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004775 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004776 // method.
4777 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004778 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004779 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004780
4781 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4782 // Never skip access checks if the verification soft fail is forced.
4783 // Mark the class as having a verification attempt to avoid re-running the verifier.
4784 klass->SetVerificationAttempted();
4785 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004786 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004787 }
Andreas Gampe48498592014-09-10 19:48:05 -07004788 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004789 // Done verifying. Notify the compiler about the verification status, in case the class
4790 // was verified implicitly (eg super class of a compiled class).
4791 if (Runtime::Current()->IsAotCompiler()) {
4792 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4793 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4794 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004795 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004796}
4797
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004798verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4799 Handle<mirror::Class> klass,
4800 verifier::HardFailLogMode log_level,
4801 std::string* error_msg) {
4802 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004803 return verifier::ClassVerifier::VerifyClass(self,
4804 klass.Get(),
4805 runtime->GetCompilerCallbacks(),
4806 runtime->IsAotCompiler(),
4807 log_level,
4808 Runtime::Current()->GetTargetSdkVersion(),
4809 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004810}
4811
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004812bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004813 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004814 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004815 // If we're compiling, we can only verify the class using the oat file if
4816 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004817 // the compilation unit (app - dependencies). We will let the compiler callback
4818 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004819 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004820 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004821 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004822 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004823 return false;
4824 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004825 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004826
Andreas Gampeb40d3612018-06-26 15:49:42 -07004827 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004828 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004829 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004830 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4831 // For boot classpath classes in the case we're not using a default boot image:
4832 // we don't have the infrastructure yet to query verification data on individual
4833 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4834 // verified. This should be taken into account when measuring boot time and app
4835 // startup compare to the (current) production system where both:
4836 // 1) updatable boot classpath classes, and
4837 // 2) classes in /system referencing updatable classes
4838 // will be verified at runtime.
David Srbecky3db3d372019-04-17 18:19:17 +01004839 if (Runtime::Current()->IsUsingApexBootImageLocation()) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004840 oat_file_class_status = ClassStatus::kVerified;
4841 return true;
4842 }
4843 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004844 return false;
4845 }
4846
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004847 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004848 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004849 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004850 return true;
4851 }
4852 // If we only verified a subset of the classes at compile time, we can end up with classes that
4853 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004854 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004855 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004856 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004857 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004858 // Compile time verification failed with a soft error. Compile time verification can fail
4859 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004860 // class ... {
4861 // Foo x;
4862 // .... () {
4863 // if (...) {
4864 // v1 gets assigned a type of resolved class Foo
4865 // } else {
4866 // v1 gets assigned a type of unresolved class Bar
4867 // }
4868 // iput x = v1
4869 // } }
4870 // when we merge v1 following the if-the-else it results in Conflict
4871 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4872 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4873 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4874 // at compile time).
4875 return false;
4876 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004877 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004878 // Compile time verification failed with a hard error. This is caused by invalid instructions
4879 // in the class. These errors are unrecoverable.
4880 return false;
4881 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004882 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004883 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4884 // not loading the class.
4885 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4886 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004887 return false;
4888 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004889 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004890 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004891 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004892 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004893 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004894}
4895
Alex Light5a559862016-01-29 12:24:48 -08004896void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004897 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004898 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004899 }
4900}
4901
Alex Light5a559862016-01-29 12:24:48 -08004902void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004903 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004904 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004905 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004906 return; // native or abstract method
4907 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004908 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004909 return; // nothing to process
4910 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004911 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004912 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004913 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4914 CatchHandlerIterator iterator(handlers_ptr);
4915 for (; iterator.HasNext(); iterator.Next()) {
4916 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4917 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004918 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004919 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004920 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004921 DCHECK(Thread::Current()->IsExceptionPending());
4922 Thread::Current()->ClearException();
4923 }
4924 }
4925 }
4926 handlers_ptr = iterator.EndDataPointer();
4927 }
4928}
4929
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004930ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4931 jstring name,
4932 jobjectArray interfaces,
4933 jobject loader,
4934 jobjectArray methods,
4935 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004936 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004937
4938 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4939 // code to be executed. We put it up here so we can avoid all the allocations associated with
4940 // creating the class. This can happen with (eg) jit-threads.
4941 if (!self->CanLoadClasses()) {
4942 // Make sure we don't try to load anything, potentially causing an infinite loop.
4943 ObjPtr<mirror::Throwable> pre_allocated =
4944 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4945 self->SetException(pre_allocated);
4946 return nullptr;
4947 }
4948
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004949 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004950 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004951 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004952 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004953 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004954 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004955 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004956 DCHECK(temp_klass->GetClass() != nullptr);
4957 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004958 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4959 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004960 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4961 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4962 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4963 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004964 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004965 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004966 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004967 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004968 std::string storage;
4969 const char* descriptor = temp_klass->GetDescriptor(&storage);
4970 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004971
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004972 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004973 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004974
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004975 // Insert the class before loading the fields as the field roots
4976 // (ArtField::declaring_class_) are only visited from the class
4977 // table. There can't be any suspend points between inserting the
4978 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004979 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004980 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004981
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004982 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004983 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004984 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004985 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004986
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004987 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4988 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004989 ArtField& interfaces_sfield = sfields->At(0);
4990 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004991 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004992 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004993
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004994 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004995 ArtField& throws_sfield = sfields->At(1);
4996 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004997 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004998 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004999
Ian Rogers466bb252011-10-14 03:29:56 -07005000 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08005001 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04005002
Alex Lighte64300b2015-12-15 15:02:47 -08005003 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07005004 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01005005 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07005006 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005007 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08005008
5009 // Create the methods array.
5010 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
5011 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005012 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
5013 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08005014 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005015 self->AssertPendingOOMException();
5016 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005017 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005018 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005019
5020 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005021 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005022
5023 // Create virtual method using specified prototypes.
5024 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005025 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005026 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005027 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005028 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005029 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5030 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005031 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005032
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005033 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005034 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005035 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005036 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005037 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005038
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005039 // At this point the class is loaded. Publish a ClassLoad event.
5040 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5041 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5042
5043 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005044 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005045 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005046 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005047 // Link the fields and virtual methods, creating vtable and iftables.
5048 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005049 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005050 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005051 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005052 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005053 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005054 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005055 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005056 CHECK(temp_klass->IsRetired());
5057 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005058
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005059 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005060 interfaces_sfield.SetObject<false>(
5061 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005062 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005063 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5064 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005065 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005066 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005067
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005068 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5069
Vladimir Marko305c38b2018-02-14 11:50:07 +00005070 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5071 // See also ClassLinker::EnsureInitialized().
5072 if (kBitstringSubtypeCheckEnabled) {
5073 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5074 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5075 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5076 }
5077
Vladimir Markobf121912019-06-04 13:49:05 +01005078 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005079 {
5080 // Lock on klass is released. Lock new class object.
5081 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005082 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005083 // Conservatively go through the ClassStatus::kInitialized state.
5084 callback = MarkClassInitialized(self, klass);
5085 }
5086 if (callback != nullptr) {
5087 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005088 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005089
5090 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07005091 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005092 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005093 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5094
Ian Rogersc2b44472011-12-14 21:17:17 -08005095 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005096 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
5097 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005098 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08005099 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005100
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005101 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005102 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005103 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005104 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005105 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005106
5107 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005108 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005109 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005110
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005111 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005112 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005113 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005114 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08005115 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005116 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005117}
5118
Mathieu Chartiere401d142015-04-22 13:56:20 -07005119void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5120 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005121 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5122 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005123
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005124 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5125 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005126 ArtMethod* proxy_constructor =
5127 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005128 DCHECK(proxy_constructor != nullptr)
5129 << "Could not find <init> method in java.lang.reflect.Proxy";
5130
Jeff Haodb8a6642014-08-14 17:18:52 -07005131 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5132 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005133 DCHECK(out != nullptr);
5134 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005135 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005136 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005137 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005138 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5139 kAccPublic |
5140 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005141 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005142
5143 // Set the original constructor method.
5144 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005145}
5146
Mathieu Chartiere401d142015-04-22 13:56:20 -07005147void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005148 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005149 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5150 CHECK_STREQ(np->GetName(), "<init>");
5151 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005152 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005153}
5154
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005155void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005156 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005157 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005158 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005159 DCHECK(out != nullptr);
5160 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005161
Alex Lighte9dd04f2016-03-16 16:09:45 -07005162 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005163 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005164 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5165 // preference to the invocation handler.
5166 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5167 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005168 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5169 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005170 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5171
5172 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5173 // method they copy might (if it's a default method).
5174 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005175
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005176 // Set the original interface method.
5177 out->SetDataPtrSize(prototype, image_pointer_size_);
5178
Ian Rogers466bb252011-10-14 03:29:56 -07005179 // At runtime the method looks like a reference and argument saving method, clone the code
5180 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005181 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005182}
Jesse Wilson95caa792011-10-12 18:14:17 -04005183
Mathieu Chartiere401d142015-04-22 13:56:20 -07005184void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005185 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005186 CHECK(!prototype->IsFinal());
5187 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005188 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005189
5190 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5191 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005192 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005193 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005194}
5195
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005196bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005197 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005198 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005199 return true;
5200 }
5201 if (!can_init_statics) {
5202 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005203 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005204 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005205 return false;
5206 }
5207 // Check if there are encoded static values needing initialization.
5208 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005209 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005210 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005211 if (dex_class_def->static_values_off_ != 0) {
5212 return false;
5213 }
5214 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005215 }
5216 // If we are a class we need to initialize all interfaces with default methods when we are
5217 // initialized. Check all of them.
5218 if (!klass->IsInterface()) {
5219 size_t num_interfaces = klass->GetIfTableCount();
5220 for (size_t i = 0; i < num_interfaces; i++) {
5221 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5222 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5223 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005224 return false;
5225 }
5226 }
5227 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005228 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005229 if (klass->IsInterface() || !klass->HasSuperClass()) {
5230 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005231 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005232 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005233 if (super_class->IsInitialized()) {
5234 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005235 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005236 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005237}
5238
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005239bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5240 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005241 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5242
5243 // Are we already initialized and therefore done?
5244 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5245 // an initialized class will never change its state.
5246 if (klass->IsInitialized()) {
5247 return true;
5248 }
5249
5250 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005251 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005252 return false;
5253 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005254
Ian Rogers7b078e82014-09-10 14:44:24 -07005255 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005256 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005257 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005258 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005259
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005260 // Re-check under the lock in case another thread initialized ahead of us.
5261 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005262 return true;
5263 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005264
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005265 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005266 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005267 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005268 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005269 return false;
5270 }
5271
Vladimir Marko72ab6842017-01-20 19:32:50 +00005272 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5273 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005274
5275 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005276 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005277 if (!klass->IsVerified()) {
5278 // We failed to verify, expect either the klass to be erroneous or verification failed at
5279 // compile time.
5280 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005281 // The class is erroneous. This may be a verifier error, or another thread attempted
5282 // verification and/or initialization and failed. We can distinguish those cases by
5283 // whether an exception is already pending.
5284 if (self->IsExceptionPending()) {
5285 // Check that it's a VerifyError.
5286 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005287 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005288 } else {
5289 // Check that another thread attempted initialization.
5290 DCHECK_NE(0, klass->GetClinitThreadId());
5291 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5292 // Need to rethrow the previous failure now.
5293 ThrowEarlierClassFailure(klass.Get(), true);
5294 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005295 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005296 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005297 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005298 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005299 self->AssertNoPendingException();
5300 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005301 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005302 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005303 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005304 } else {
5305 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005306 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005307
5308 // A separate thread could have moved us all the way to initialized. A "simple" example
5309 // involves a subclass of the current class being initialized at the same time (which
5310 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005311 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005312 if (klass->IsInitialized()) {
5313 return true;
5314 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005315 }
5316
Vladimir Marko2c64a832018-01-04 11:31:56 +00005317 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005318 // initializing higher up the stack or another thread has beat us
5319 // to initializing and we need to wait. Either way, this
5320 // invocation of InitializeClass will not be responsible for
5321 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005322 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005323 // Could have got an exception during verification.
5324 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005325 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005326 return false;
5327 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005328 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005329 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005330 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005331 return true;
5332 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005333 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005334 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005335 }
5336
Jeff Haoe2e40342017-07-19 10:45:18 -07005337 // Try to get the oat class's status for this class if the oat file is present. The compiler
5338 // tries to validate superclass descriptors, and writes the result into the oat file.
5339 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5340 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5341 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005342 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005343 const Runtime* runtime = Runtime::Current();
5344 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5345 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5346 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005347 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005348 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005349 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005350 return false;
5351 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005352 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005353
Vladimir Marko2c64a832018-01-04 11:31:56 +00005354 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005355 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005356
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005357 // From here out other threads may observe that we're initializing and so changes of state
5358 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005359 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005360 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005361
5362 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005363 }
5364
Andreas Gampeaf864702019-07-23 14:05:35 -07005365 uint64_t t_sub = 0;
5366
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005367 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005368 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005369 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005370 if (!super_class->IsInitialized()) {
5371 CHECK(!super_class->IsInterface());
5372 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005373 StackHandleScope<1> hs(self);
5374 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Andreas Gampeaf864702019-07-23 14:05:35 -07005375 uint64_t super_t0 = NanoTime();
Ian Rogers7b078e82014-09-10 14:44:24 -07005376 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Andreas Gampeaf864702019-07-23 14:05:35 -07005377 uint64_t super_t1 = NanoTime();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005378 if (!super_initialized) {
5379 // The super class was verified ahead of entering initializing, we should only be here if
5380 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005381 // For the case of aot compiler, the super class might also be initializing but we don't
5382 // want to process circular dependencies in pre-compile.
5383 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005384 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005385 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005386 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005387 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005388 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005389 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005390 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005391 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005392 return false;
5393 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005394 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005395 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005396 }
5397
Alex Lighteb7c1442015-08-31 13:17:42 -07005398 if (!klass->IsInterface()) {
5399 // Initialize interfaces with default methods for the JLS.
5400 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005401 // Only setup the (expensive) handle scope if we actually need to.
5402 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005403 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005404 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5405 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005406 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005407 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005408 CHECK(handle_scope_iface->IsInterface());
5409 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5410 // We have already done this for this interface. Skip it.
5411 continue;
5412 }
5413 // We cannot just call initialize class directly because we need to ensure that ALL
5414 // interfaces with default methods are initialized. Non-default interface initialization
5415 // will not affect other non-default super-interfaces.
Andreas Gampeaf864702019-07-23 14:05:35 -07005416 uint64_t inf_t0 = NanoTime(); // This is not very precise, misses all walking.
Alex Light56a40f52015-10-14 11:07:41 -07005417 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5418 handle_scope_iface,
5419 can_init_statics,
5420 can_init_parents);
Andreas Gampeaf864702019-07-23 14:05:35 -07005421 uint64_t inf_t1 = NanoTime();
Alex Light56a40f52015-10-14 11:07:41 -07005422 if (!iface_initialized) {
5423 ObjectLock<mirror::Class> lock(self, klass);
5424 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005425 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005426 return false;
5427 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005428 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005429 }
5430 }
5431 }
5432
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005433 const size_t num_static_fields = klass->NumStaticFields();
5434 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005435 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005436 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005437 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005438 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005439 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005440
5441 // Eagerly fill in static fields so that the we don't have to do as many expensive
5442 // Class::FindStaticField in ResolveField.
5443 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005444 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005445 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005446 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005447 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005448 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005449 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5450 field,
5451 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5452 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005453 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005454 } else {
5455 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005456 }
5457 }
5458
Vladimir Markoe11dd502017-12-08 14:09:45 +00005459 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5460 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005461 this,
5462 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005463 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005464
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005465 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005466 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005467 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005468 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5469 if (!value_it.HasNext()) {
5470 break;
5471 }
5472 ArtField* art_field = ResolveField(field.GetIndex(),
5473 dex_cache,
5474 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005475 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005476 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005477 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005478 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005479 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005480 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005481 if (self->IsExceptionPending()) {
5482 break;
5483 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005484 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005485 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005486 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005487 }
5488 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005489
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005490
Mathieu Chartierda595be2016-08-10 13:57:39 -07005491 if (!self->IsExceptionPending()) {
5492 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5493 if (clinit != nullptr) {
5494 CHECK(can_init_statics);
5495 JValue result;
5496 clinit->Invoke(self, nullptr, 0, &result, "V");
5497 }
5498 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005499 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005500 uint64_t t1 = NanoTime();
5501
Vladimir Markobf121912019-06-04 13:49:05 +01005502 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005503 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005504 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005505 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005506
5507 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005508 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005509 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005510 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005511 } else if (Runtime::Current()->IsTransactionAborted()) {
5512 // The exception thrown when the transaction aborted has been caught and cleared
5513 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005514 VLOG(compiler) << "Return from class initializer of "
5515 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005516 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005517 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005518 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005519 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005520 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005521 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5522 RuntimeStats* thread_stats = self->GetStats();
5523 ++global_stats->class_init_count;
5524 ++thread_stats->class_init_count;
Andreas Gampeaf864702019-07-23 14:05:35 -07005525 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5526 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005527 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005528 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005529 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005530 std::string temp;
5531 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005532 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005533 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005534 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005535 }
Vladimir Markobf121912019-06-04 13:49:05 +01005536 if (callback != nullptr) {
5537 callback->MakeVisible(self);
5538 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005539 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005540}
5541
Alex Lighteb7c1442015-08-31 13:17:42 -07005542// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5543// and perform the initialization only on those interfaces that contain default methods.
5544bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5545 Handle<mirror::Class> iface,
5546 bool can_init_statics,
5547 bool can_init_parents) {
5548 CHECK(iface->IsInterface());
5549 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005550 // Only create the (expensive) handle scope if we need it.
5551 if (UNLIKELY(num_direct_ifaces > 0)) {
5552 StackHandleScope<1> hs(self);
5553 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5554 // First we initialize all of iface's super-interfaces recursively.
5555 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005556 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005557 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005558 if (!super_iface->HasBeenRecursivelyInitialized()) {
5559 // Recursive step
5560 handle_super_iface.Assign(super_iface);
5561 if (!InitializeDefaultInterfaceRecursive(self,
5562 handle_super_iface,
5563 can_init_statics,
5564 can_init_parents)) {
5565 return false;
5566 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005567 }
5568 }
5569 }
5570
5571 bool result = true;
5572 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5573 // initialize if we don't have default methods.
5574 if (iface->HasDefaultMethods()) {
5575 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5576 }
5577
5578 // Mark that this interface has undergone recursive default interface initialization so we know we
5579 // can skip it on any later class initializations. We do this even if we are not a default
5580 // interface since we can still avoid the traversal. This is purely a performance optimization.
5581 if (result) {
5582 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005583 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5584 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5585 // initialization is a performance optimization (to avoid another idempotent visit
5586 // for other implementing classes/interfaces), and can be revisited later.
5587 ObjectTryLock<mirror::Class> lock(self, iface);
5588 if (lock.Acquired()) {
5589 iface->SetRecursivelyInitialized();
5590 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005591 }
5592 return result;
5593}
5594
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005595bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5596 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005597 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005598 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005599 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005600 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005601 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005602 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005603
5604 // When we wake up, repeat the test for init-in-progress. If
5605 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005606 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005607 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005608 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005609 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005610 return false;
5611 }
5612 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005613 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005614 continue;
5615 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005616 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005617 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005618 // Compile time initialization failed.
5619 return false;
5620 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005621 if (klass->IsErroneous()) {
5622 // The caller wants an exception, but it was thrown in a
5623 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005624 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005625 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005626 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005627 return false;
5628 }
5629 if (klass->IsInitialized()) {
5630 return true;
5631 }
David Sehr709b0702016-10-13 09:12:37 -07005632 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005633 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005634 }
Ian Rogers07140832014-09-30 15:43:59 -07005635 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005636}
5637
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005638static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5639 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005640 ArtMethod* method,
5641 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005642 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005643 DCHECK(Thread::Current()->IsExceptionPending());
5644 DCHECK(!m->IsProxyMethod());
5645 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005646 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5647 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005648 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005649 std::string return_type = dex_file->PrettyType(return_type_idx);
5650 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005651 ThrowWrappedLinkageError(klass.Get(),
5652 "While checking class %s method %s signature against %s %s: "
5653 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005654 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5655 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005656 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005657 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005658 return_type.c_str(), class_loader.c_str());
5659}
5660
5661static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5662 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005663 ArtMethod* method,
5664 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005665 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005666 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005667 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005668 DCHECK(Thread::Current()->IsExceptionPending());
5669 DCHECK(!m->IsProxyMethod());
5670 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005671 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5672 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005673 ThrowWrappedLinkageError(klass.Get(),
5674 "While checking class %s method %s signature against %s %s: "
5675 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005676 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5677 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005678 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005679 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005680 index, arg_type.c_str(), class_loader.c_str());
5681}
5682
5683static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5684 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005685 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005686 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005687 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005688 ThrowLinkageError(klass.Get(),
5689 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005690 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5691 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005692 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005693 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005694 error_msg.c_str());
5695}
5696
Ian Rogersb5fb2072014-12-02 17:22:02 -08005697static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005698 Handle<mirror::Class> klass,
5699 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005700 ArtMethod* method1,
5701 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005702 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005703 {
5704 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005705 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005706 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005707 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005708 return false;
5709 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005710 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005711 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005712 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005713 return false;
5714 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005715 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005716 ThrowSignatureMismatch(klass, super_klass, method1,
5717 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005718 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005719 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005720 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005721 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005722 return false;
5723 }
5724 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005725 const dex::TypeList* types1 = method1->GetParameterTypeList();
5726 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005727 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005728 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005729 ThrowSignatureMismatch(klass, super_klass, method1,
5730 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005731 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005732 return false;
5733 }
5734 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005735 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005736 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005737 ThrowSignatureMismatch(klass, super_klass, method1,
5738 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005739 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005740 return false;
5741 }
5742 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005743 }
5744 uint32_t num_types = types1->Size();
5745 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005746 ThrowSignatureMismatch(klass, super_klass, method1,
5747 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005748 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005749 return false;
5750 }
5751 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005752 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005753 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005754 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005755 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005756 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005757 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005758 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005759 return false;
5760 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005761 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005762 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005763 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005764 if (UNLIKELY(other_param_type == nullptr)) {
5765 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005766 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005767 return false;
5768 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005769 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005770 ThrowSignatureMismatch(klass, super_klass, method1,
5771 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5772 i,
David Sehr709b0702016-10-13 09:12:37 -07005773 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005774 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005775 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005776 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005777 return false;
5778 }
5779 }
5780 return true;
5781}
5782
5783
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005784bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005785 if (klass->IsInterface()) {
5786 return true;
5787 }
Ian Rogers151f2212014-05-06 11:27:27 -07005788 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005789 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005790 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005791 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005792 if (klass->HasSuperClass() &&
5793 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005794 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005795 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005796 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5797 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5798 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005799 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5800 klass,
5801 super_klass,
5802 m,
5803 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005804 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005805 return false;
5806 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005807 }
5808 }
5809 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005810 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005811 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5812 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5813 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005814 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005815 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5816 j, image_pointer_size_);
5817 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5818 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005819 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5820 klass,
5821 super_klass,
5822 m,
5823 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005824 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005825 return false;
5826 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005827 }
5828 }
5829 }
5830 }
5831 return true;
5832}
5833
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005834bool ClassLinker::EnsureInitialized(Thread* self,
5835 Handle<mirror::Class> c,
5836 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005837 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005838 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005839
Mathieu Chartier524507a2014-08-27 15:28:28 -07005840 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005841 // If we've seen an initialized but not visibly initialized class
5842 // many times, request visible initialization.
5843 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5844 // Thanks to the x86 memory model classes skip the initialized status.
5845 DCHECK(c->IsVisiblyInitialized());
5846 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5847 if (self->IncrementMakeVisiblyInitializedCounter()) {
5848 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5849 }
5850 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005851 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005852 return true;
5853 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005854 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5855 //
5856 // Ensure the bitstring is initialized before any of the class initialization
5857 // logic occurs. Once a class initializer starts running, objects can
5858 // escape into the heap and use the subtype checking code.
5859 //
5860 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5861 // can be used as a source for the IsSubClass check, and that all ancestors
5862 // of the class are Assigned (can be used as a target for IsSubClass check)
5863 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005864 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005865 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005866 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005867 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5868 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005869 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005870 if (!success) {
5871 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005872 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005873 }
5874 } else {
5875 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005876 }
5877 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005878}
5879
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005880void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5881 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005882 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005883 for (ArtField& field : new_class->GetIFields()) {
5884 if (field.GetDeclaringClass() == temp_class) {
5885 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005886 }
5887 }
5888
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005889 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005890 for (ArtField& field : new_class->GetSFields()) {
5891 if (field.GetDeclaringClass() == temp_class) {
5892 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005893 }
5894 }
5895
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005896 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005897 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005898 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005899 if (method.GetDeclaringClass() == temp_class) {
5900 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005901 }
5902 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005903
5904 // Make sure the remembered set and mod-union tables know that we updated some of the native
5905 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005906 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005907}
5908
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005909void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005910 CHECK(class_loader->GetAllocator() == nullptr);
5911 CHECK(class_loader->GetClassTable() == nullptr);
5912 Thread* const self = Thread::Current();
5913 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005914 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005915 // Create and set the class table.
5916 data.class_table = new ClassTable;
5917 class_loader->SetClassTable(data.class_table);
5918 // Create and set the linear allocator.
5919 data.allocator = Runtime::Current()->CreateLinearAlloc();
5920 class_loader->SetAllocator(data.allocator);
5921 // Add to the list so that we know to free the data later.
5922 class_loaders_.push_back(data);
5923}
5924
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005925ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005926 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005927 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005928 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005929 ClassTable* class_table = class_loader->GetClassTable();
5930 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005931 RegisterClassLoader(class_loader);
5932 class_table = class_loader->GetClassTable();
5933 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005934 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005935 return class_table;
5936}
5937
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005938ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005939 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005940}
5941
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005942static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005943 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005944 while (klass->HasSuperClass()) {
5945 klass = klass->GetSuperClass();
5946 if (klass->ShouldHaveImt()) {
5947 return klass->GetImt(pointer_size);
5948 }
5949 }
5950 return nullptr;
5951}
5952
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005953bool ClassLinker::LinkClass(Thread* self,
5954 const char* descriptor,
5955 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005956 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005957 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005958 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005959
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005960 if (!LinkSuperClass(klass)) {
5961 return false;
5962 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005963 ArtMethod* imt_data[ImTable::kSize];
5964 // If there are any new conflicts compared to super class.
5965 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005966 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005967 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005968 return false;
5969 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005970 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005971 return false;
5972 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005973 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005974 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005975 return false;
5976 }
5977 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005978 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005979
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005980 ImTable* imt = nullptr;
5981 if (klass->ShouldHaveImt()) {
5982 // If there are any new conflicts compared to the super class we can not make a copy. There
5983 // can be cases where both will have a conflict method at the same slot without having the same
5984 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5985 // will possibly create a table that is incorrect for either of the classes.
5986 // Same IMT with new_conflict does not happen very often.
5987 if (!new_conflict) {
5988 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5989 if (super_imt != nullptr) {
5990 bool imt_equals = true;
5991 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5992 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5993 }
5994 if (imt_equals) {
5995 imt = super_imt;
5996 }
5997 }
5998 }
5999 if (imt == nullptr) {
6000 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
6001 imt = reinterpret_cast<ImTable*>(
6002 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
6003 if (imt == nullptr) {
6004 return false;
6005 }
6006 imt->Populate(imt_data, image_pointer_size_);
6007 }
6008 }
6009
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006010 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
6011 // We don't need to retire this class as it has no embedded tables or it was created the
6012 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006013 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006014
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006015 if (klass->ShouldHaveEmbeddedVTable()) {
6016 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006017 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006018 if (klass->ShouldHaveImt()) {
6019 klass->SetImt(imt, image_pointer_size_);
6020 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006021
6022 // Update CHA info based on whether we override methods.
6023 // Have to do this before setting the class as resolved which allows
6024 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006025 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006026 cha_->UpdateAfterLoadingOf(klass);
6027 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006028
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006029 // This will notify waiters on klass that saw the not yet resolved
6030 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006031 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006032 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006033 } else {
6034 CHECK(!klass->IsResolved());
6035 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006036 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006037 Handle<mirror::Class> h_new_class =
6038 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006039 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6040 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6041 // may not see any references to the target space and clean the card for a class if another
6042 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006043 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006044 klass->SetSFieldsPtrUnchecked(nullptr);
6045 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006046 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006047 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006048 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006049 return false;
6050 }
6051
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006052 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6053 ObjectLock<mirror::Class> lock(self, h_new_class);
6054 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006055
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006056 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006057 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006058 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006059 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006060 const ObjPtr<mirror::Class> existing =
6061 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006062 if (class_loader != nullptr) {
6063 // We updated the class in the class table, perform the write barrier so that the GC knows
6064 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006065 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006066 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006067 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006068 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006069 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6070 }
6071 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006072
Mingyao Yang063fc772016-08-02 11:02:54 -07006073 // Update CHA info based on whether we override methods.
6074 // Have to do this before setting the class as resolved which allows
6075 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006076 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006077 cha_->UpdateAfterLoadingOf(h_new_class);
6078 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006079
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006080 // This will notify waiters on temp class that saw the not yet resolved class in the
6081 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006082 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006083
Vladimir Marko2c64a832018-01-04 11:31:56 +00006084 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006085 // This will notify waiters on new_class that saw the not yet resolved
6086 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006087 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006088 // Return the new class.
6089 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006090 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006091 return true;
6092}
6093
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006094bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006095 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006096 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006097 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6098 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006099 // Check that a class does not inherit from itself directly.
6100 //
6101 // TODO: This is a cheap check to detect the straightforward case
6102 // of a class extending itself (b/28685551), but we should do a
6103 // proper cycle detection on loaded classes, to detect all cases
6104 // of class circularity errors (b/28830038).
6105 if (super_class_idx == class_def.class_idx_) {
6106 ThrowClassCircularityError(klass.Get(),
6107 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006108 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006109 return false;
6110 }
6111
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006112 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006113 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006114 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006115 return false;
6116 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006117 // Verify
6118 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006119 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006120 super_class->PrettyDescriptor().c_str(),
6121 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006122 return false;
6123 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006124 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006125 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006126 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006127 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006128 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006129 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006130 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006131 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006132 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006133 DCHECK(Thread::Current()->IsExceptionPending());
6134 return false;
6135 }
6136 // Verify
6137 if (!klass->CanAccess(interface)) {
6138 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006139 ThrowIllegalAccessError(klass.Get(),
6140 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006141 interface->PrettyDescriptor().c_str(),
6142 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006143 return false;
6144 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006145 }
6146 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006147 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006148 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006149 return true;
6150}
6151
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006152bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006153 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006154 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006155 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6156 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006157 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006158 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006159 return false;
6160 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006161 return true;
6162 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006163 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006164 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006165 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006166 return false;
6167 }
6168 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006169 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006170 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6171 return false;
6172 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006173 if (super->IsFinal()) {
6174 ThrowVerifyError(klass.Get(),
6175 "Superclass %s of %s is declared final",
6176 super->PrettyDescriptor().c_str(),
6177 klass->PrettyDescriptor().c_str());
6178 return false;
6179 }
6180 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006181 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006182 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006183 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006184 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006185 return false;
6186 }
6187 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006188 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006189 super->PrettyDescriptor().c_str(),
6190 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006191 return false;
6192 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006193
Brian Carlstromf3632832014-05-20 15:36:53 -07006194 // Inherit kAccClassIsFinalizable from the superclass in case this
6195 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006196 if (super->IsFinalizable()) {
6197 klass->SetFinalizable();
6198 }
6199
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006200 // Inherit class loader flag form super class.
6201 if (super->IsClassLoaderClass()) {
6202 klass->SetClassLoaderClass();
6203 }
6204
Elliott Hughes2da50362011-10-10 16:57:08 -07006205 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006206 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006207 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006208 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006209 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006210 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006211 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006212 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006213 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006214 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006215 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006216 return false;
6217 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006218
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006219 if (kIsDebugBuild) {
6220 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006221 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006222 CHECK(super->IsResolved());
6223 super = super->GetSuperClass();
6224 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006225 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006226 return true;
6227}
6228
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006229// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006230bool ClassLinker::LinkMethods(Thread* self,
6231 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006232 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006233 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006234 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006235 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006236 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6237 // need to have default methods be in the virtuals array of each class but we don't set that up
6238 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006239 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006240 // Link virtual methods then interface methods.
6241 // We set up the interface lookup table first because we need it to determine if we need to update
6242 // any vtable entries with new default method implementations.
6243 return SetupInterfaceLookupTable(self, klass, interfaces)
6244 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006245 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006246}
6247
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006248// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6249// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6250// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006251class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006252 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006253 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006254 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006255 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6256 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006257 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006258 }
6259
6260 const char* GetName() {
6261 if (name_ == nullptr) {
6262 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6263 }
6264 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006265 }
6266
Mathieu Chartiere401d142015-04-22 13:56:20 -07006267 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006268 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006269 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006270 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006271 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006272 if (dex_file_ == other_dex_file) {
6273 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6274 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006275 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006276 uint32_t other_name_len;
6277 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6278 &other_name_len);
6279 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6280 return false;
6281 }
6282 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6283 }
6284
6285 private:
6286 // Dex file for the method to compare against.
6287 const DexFile* const dex_file_;
6288 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006289 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006290 // Lazily computed name from the dex file's strings.
6291 const char* name_;
6292 // Lazily computed name length.
6293 uint32_t name_len_;
6294};
6295
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006296class LinkVirtualHashTable {
6297 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006298 LinkVirtualHashTable(Handle<mirror::Class> klass,
6299 size_t hash_size,
6300 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006301 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006302 : klass_(klass),
6303 hash_size_(hash_size),
6304 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006305 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006306 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6307 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006308
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006309 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006310 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6311 virtual_method_index, image_pointer_size_);
6312 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006313 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006314 uint32_t index = hash % hash_size_;
6315 // Linear probe until we have an empty slot.
6316 while (hash_table_[index] != invalid_index_) {
6317 if (++index == hash_size_) {
6318 index = 0;
6319 }
6320 }
6321 hash_table_[index] = virtual_method_index;
6322 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006323
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006324 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006325 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006326 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006327 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006328 size_t index = hash % hash_size_;
6329 while (true) {
6330 const uint32_t value = hash_table_[index];
6331 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6332 // the block and can safely assume not found.
6333 if (value == invalid_index_) {
6334 break;
6335 }
6336 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006337 ArtMethod* virtual_method =
6338 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6339 if (comparator->HasSameNameAndSignature(
6340 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006341 hash_table_[index] = removed_index_;
6342 return value;
6343 }
6344 }
6345 if (++index == hash_size_) {
6346 index = 0;
6347 }
6348 }
6349 return GetNotFoundIndex();
6350 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006351
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006352 static uint32_t GetNotFoundIndex() {
6353 return invalid_index_;
6354 }
6355
6356 private:
6357 static const uint32_t invalid_index_;
6358 static const uint32_t removed_index_;
6359
6360 Handle<mirror::Class> klass_;
6361 const size_t hash_size_;
6362 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006363 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006364};
6365
6366const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6367const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6368
Stephen Hines1ddd9132017-02-08 01:51:18 -08006369bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006370 Thread* self,
6371 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006372 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006373 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006374 if (klass->IsInterface()) {
6375 // No vtable.
6376 if (!IsUint<16>(num_virtual_methods)) {
6377 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6378 return false;
6379 }
6380 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006381 // Assign each method an IMT index and set the default flag.
6382 for (size_t i = 0; i < num_virtual_methods; ++i) {
6383 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6384 m->SetMethodIndex(i);
6385 if (!m->IsAbstract()) {
6386 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6387 has_defaults = true;
6388 }
6389 }
6390 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6391 // during initialization. This is a performance optimization. We could simply traverse the
6392 // virtual_methods_ array again during initialization.
6393 if (has_defaults) {
6394 klass->SetHasDefaultMethods();
6395 }
6396 return true;
6397 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006398 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6399 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006400 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006401 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006402 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006403 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006404 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006405 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006406 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006407 return false;
6408 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006409 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006410 vtable->SetElementPtrSize(
6411 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006412 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006413 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6414 // might give us new default methods). If no new interfaces then we can skip the rest since
6415 // the class cannot override any of the super-class's methods. This is required for
6416 // correctness since without it we might not update overridden default method vtable entries
6417 // correctly.
6418 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006419 klass->SetVTable(vtable.Get());
6420 return true;
6421 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006422 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006423 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006424 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006425 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006426 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6427 // might give us new default methods). See comment above.
6428 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006429 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006430 return true;
6431 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006432 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6433 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006434 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006435 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006436 return false;
6437 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006438 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006439 // How the algorithm works:
6440 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6441 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6442 // method which has not been matched to a vtable method, and j if the virtual method at the
6443 // index overrode the super virtual method at index j.
6444 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6445 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6446 // the need for the initial vtable which we later shrink back down).
6447 // 3. Add non overridden methods to the end of the vtable.
6448 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006449 // + 1 so that even if we only have new default methods we will still be able to use this hash
6450 // table (i.e. it will never have 0 size).
6451 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006452 uint32_t* hash_table_ptr;
6453 std::unique_ptr<uint32_t[]> hash_heap_storage;
6454 if (hash_table_size <= kMaxStackHash) {
6455 hash_table_ptr = reinterpret_cast<uint32_t*>(
6456 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6457 } else {
6458 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6459 hash_table_ptr = hash_heap_storage.get();
6460 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006461 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006462 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006463 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006464 DCHECK(klass->GetVirtualMethodDuringLinking(
6465 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006466 hash_table.Add(i);
6467 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006468 // 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 -07006469 // the hash table.
6470 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006471 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006472 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006473 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6474 super_method->GetAccessFlags())) {
6475 // Continue on to the next method since this one is package private and canot be overridden.
6476 // Before Android 4.1, the package-private method super_method might have been incorrectly
6477 // overridden.
6478 continue;
6479 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006480 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006481 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006482 // We remove the method so that subsequent lookups will be faster by making the hash-map
6483 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006484 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6485 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006486 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6487 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006488 if (super_method->IsFinal()) {
6489 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6490 virtual_method->PrettyMethod().c_str(),
6491 super_method->GetDeclaringClassDescriptor());
6492 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006493 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006494 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6495 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006496 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006497 // We didn't directly override this method but we might through default methods...
6498 // Check for default method update.
6499 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006500 switch (FindDefaultMethodImplementation(self,
6501 super_method,
6502 klass,
6503 /*out*/&default_method)) {
6504 case DefaultMethodSearchResult::kDefaultConflict: {
6505 // A conflict was found looking for default methods. Note this (assuming it wasn't
6506 // pre-existing) in the translations map.
6507 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6508 // Don't generate another conflict method to reduce memory use as an optimization.
6509 default_translations->insert(
6510 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6511 }
6512 break;
6513 }
6514 case DefaultMethodSearchResult::kAbstractFound: {
6515 // No conflict but method is abstract.
6516 // We note that this vtable entry must be made abstract.
6517 if (UNLIKELY(!super_method->IsAbstract())) {
6518 default_translations->insert(
6519 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6520 }
6521 break;
6522 }
6523 case DefaultMethodSearchResult::kDefaultFound: {
6524 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6525 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6526 // Found a default method implementation that is new.
6527 // TODO Refactor this add default methods to virtuals here and not in
6528 // LinkInterfaceMethods maybe.
6529 // The problem is default methods might override previously present
6530 // default-method or miranda-method vtable entries from the superclass.
6531 // Unfortunately we need these to be entries in this class's virtuals. We do not
6532 // give these entries there until LinkInterfaceMethods so we pass this map around
6533 // to let it know which vtable entries need to be updated.
6534 // Make a note that vtable entry j must be updated, store what it needs to be updated
6535 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6536 // then.
6537 default_translations->insert(
6538 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006539 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6540 << " overridden by default "
6541 << default_method->PrettyMethod()
6542 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006543 }
6544 break;
6545 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006546 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006547 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006548 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006549 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006550 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006551 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006552 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006553 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6554 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006555 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006556 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006557 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006558 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006559 local_method->SetMethodIndex(actual_count);
6560 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006561 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006562 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006563 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006564 return false;
6565 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006566 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006567 CHECK_LE(actual_count, max_count);
6568 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006569 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6570 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006571 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006572 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006573 return false;
6574 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006575 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006576 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006577 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006578 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006579 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006580 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6581 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006582 return false;
6583 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006584 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006585 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006586 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006587 return false;
6588 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006589 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006590 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6591 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006592 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006593 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006594 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006595 }
6596 return true;
6597}
6598
Alex Light9139e002015-10-09 15:59:48 -07006599// Determine if the given iface has any subinterface in the given list that declares the method
6600// specified by 'target'.
6601//
6602// Arguments
6603// - self: The thread we are running on
6604// - target: A comparator that will match any method that overrides the method we are checking for
6605// - iftable: The iftable we are searching for an overriding method on.
6606// - ifstart: The index of the interface we are checking to see if anything overrides
6607// - iface: The interface we are checking to see if anything overrides.
6608// - image_pointer_size:
6609// The image pointer size.
6610//
6611// Returns
6612// - True: There is some method that matches the target comparator defined in an interface that
6613// is a subtype of iface.
6614// - False: There is no method that matches the target comparator in any interface that is a subtype
6615// of iface.
6616static bool ContainsOverridingMethodOf(Thread* self,
6617 MethodNameAndSignatureComparator& target,
6618 Handle<mirror::IfTable> iftable,
6619 size_t ifstart,
6620 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006621 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006622 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006623 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006624 DCHECK(iface != nullptr);
6625 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006626 DCHECK_GE(ifstart, 0u);
6627 DCHECK_LT(ifstart, iftable->Count());
6628 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6629 DCHECK(iface->IsInterface());
6630
6631 size_t iftable_count = iftable->Count();
6632 StackHandleScope<1> hs(self);
6633 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6634 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6635 // Skip ifstart since our current interface obviously cannot override itself.
6636 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006637 // Iterate through every method on this interface. The order does not matter.
6638 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006639 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006640 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006641 // Check if the i'th interface is a subtype of this one.
6642 if (iface->IsAssignableFrom(current_iface.Get())) {
6643 return true;
6644 }
6645 break;
6646 }
6647 }
6648 }
6649 return false;
6650}
6651
Alex Lighteb7c1442015-08-31 13:17:42 -07006652// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006653// out_default_method and returns kDefaultFound on success. If no default method was found return
6654// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6655// default_method conflict) it will return kDefaultConflict.
6656ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6657 Thread* self,
6658 ArtMethod* target_method,
6659 Handle<mirror::Class> klass,
6660 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006661 DCHECK(self != nullptr);
6662 DCHECK(target_method != nullptr);
6663 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006664
6665 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006666
6667 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6668 // table. This lets us walk the table backwards when searching for default methods. The first one
6669 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6670 // track of it and then continue checking all other interfaces, since we need to throw an error if
6671 // we encounter conflicting default method implementations (one is not a subtype of the other).
6672 //
6673 // The order of unrelated interfaces does not matter and is not defined.
6674 size_t iftable_count = klass->GetIfTableCount();
6675 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006676 // No interfaces. We have already reset out to null so just return kAbstractFound.
6677 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006678 }
6679
Alex Light9139e002015-10-09 15:59:48 -07006680 StackHandleScope<3> hs(self);
6681 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006682 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006683 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006684 MethodNameAndSignatureComparator target_name_comparator(
6685 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6686 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006687 for (size_t k = iftable_count; k != 0; ) {
6688 --k;
6689
Alex Lighteb7c1442015-08-31 13:17:42 -07006690 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006691
6692 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006693 // Iterate through every declared method on this interface. The order does not matter.
6694 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6695 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006696 // Skip abstract methods and methods with different names.
6697 if (current_method->IsAbstract() ||
6698 !target_name_comparator.HasSameNameAndSignature(
6699 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6700 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006701 } else if (!current_method->IsPublic()) {
6702 // The verifier should have caught the non-public method for dex version 37. Just warn and
6703 // skip it since this is from before default-methods so we don't really need to care that it
6704 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006705 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6706 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006707 << "This will be a fatal error in subsequent versions of android. "
6708 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006709 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006710 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006711 // We have multiple default impls of the same method. This is a potential default conflict.
6712 // We need to check if this possibly conflicting method is either a superclass of the chosen
6713 // default implementation or is overridden by a non-default interface method. In either case
6714 // there is no conflict.
6715 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6716 !ContainsOverridingMethodOf(self,
6717 target_name_comparator,
6718 iftable,
6719 k,
6720 iface,
6721 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006722 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006723 << current_method->PrettyMethod() << " and "
6724 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6725 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006726 *out_default_method = nullptr;
6727 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006728 } else {
6729 break; // Continue checking at the next interface.
6730 }
6731 } else {
Alex Light9139e002015-10-09 15:59:48 -07006732 // chosen_iface == null
6733 if (!ContainsOverridingMethodOf(self,
6734 target_name_comparator,
6735 iftable,
6736 k,
6737 iface,
6738 image_pointer_size_)) {
6739 // Don't set this as the chosen interface if something else is overriding it (because that
6740 // other interface would be potentially chosen instead if it was default). If the other
6741 // interface was abstract then we wouldn't select this interface as chosen anyway since
6742 // the abstract method masks it.
6743 *out_default_method = current_method;
6744 chosen_iface.Assign(iface.Get());
6745 // We should now finish traversing the graph to find if we have default methods that
6746 // conflict.
6747 } else {
David Sehr709b0702016-10-13 09:12:37 -07006748 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6749 << "' was "
6750 << "skipped because it was overridden by an abstract method in a "
6751 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006752 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006753 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006754 break;
6755 }
6756 }
Alex Light9139e002015-10-09 15:59:48 -07006757 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006758 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6759 << "' selected "
6760 << "as the implementation for '" << target_method->PrettyMethod()
6761 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006762 return DefaultMethodSearchResult::kDefaultFound;
6763 } else {
6764 return DefaultMethodSearchResult::kAbstractFound;
6765 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006766}
6767
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006768ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006769 ArtMethod* conflict_method,
6770 ArtMethod* interface_method,
6771 ArtMethod* method,
6772 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006773 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006774 Runtime* const runtime = Runtime::Current();
6775 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6776 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6777
6778 // Create a new entry if the existing one is the shared conflict method.
6779 ArtMethod* new_conflict_method = new_entry
6780 ? runtime->CreateImtConflictMethod(linear_alloc)
6781 : conflict_method;
6782
6783 // Allocate a new table. Note that we will leak this table at the next conflict,
6784 // but that's a tradeoff compared to making the table fixed size.
6785 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006786 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6787 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006788 if (data == nullptr) {
6789 LOG(ERROR) << "Failed to allocate conflict table";
6790 return conflict_method;
6791 }
6792 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6793 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006794 method,
6795 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006796
6797 // Do a fence to ensure threads see the data in the table before it is assigned
6798 // to the conflict method.
6799 // Note that there is a race in the presence of multiple threads and we may leak
6800 // memory from the LinearAlloc, but that's a tradeoff compared to using
6801 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006802 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006803 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006804 return new_conflict_method;
6805}
6806
Vladimir Marko921094a2017-01-12 18:37:06 +00006807bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6808 Handle<mirror::Class> klass,
6809 Handle<mirror::IfTable> iftable) {
6810 DCHECK(!klass->IsInterface());
6811 const bool has_superclass = klass->HasSuperClass();
6812 const bool extend_super_iftable = has_superclass;
6813 const size_t ifcount = klass->GetIfTableCount();
6814 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6815 for (size_t i = 0; i < ifcount; ++i) {
6816 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6817 if (num_methods > 0) {
6818 const bool is_super = i < super_ifcount;
6819 // This is an interface implemented by a super-class. Therefore we can just copy the method
6820 // array from the superclass.
6821 const bool super_interface = is_super && extend_super_iftable;
6822 ObjPtr<mirror::PointerArray> method_array;
6823 if (super_interface) {
6824 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6825 DCHECK(if_table != nullptr);
6826 DCHECK(if_table->GetMethodArray(i) != nullptr);
6827 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006828 StackHandleScope<1u> hs(self);
6829 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6830 method_array =
6831 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006832 } else {
6833 method_array = AllocPointerArray(self, num_methods);
6834 }
6835 if (UNLIKELY(method_array == nullptr)) {
6836 self->AssertPendingOOMException();
6837 return false;
6838 }
6839 iftable->SetMethodArray(i, method_array);
6840 }
6841 }
6842 return true;
6843}
6844
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006845void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6846 ArtMethod* imt_conflict_method,
6847 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006848 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006849 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006850 // Place method in imt if entry is empty, place conflict otherwise.
6851 if (*imt_ref == unimplemented_method) {
6852 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006853 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006854 // If we are not a conflict and we have the same signature and name as the imt
6855 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006856 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6857 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006858 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006859 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006860 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006861 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006862 *imt_ref = current_method;
6863 } else {
Alex Light9139e002015-10-09 15:59:48 -07006864 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006865 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006866 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006867 } else {
6868 // Place the default conflict method. Note that there may be an existing conflict
6869 // method in the IMT, but it could be one tailored to the super class, with a
6870 // specific ImtConflictTable.
6871 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006872 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006873 }
6874}
6875
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006876void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006877 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6878 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006879 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006880 Runtime* const runtime = Runtime::Current();
6881 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6882 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006883 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006884 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006885 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006886 FillIMTFromIfTable(klass->GetIfTable(),
6887 unimplemented_method,
6888 conflict_method,
6889 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006890 /*create_conflict_tables=*/true,
6891 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006892 &new_conflict,
6893 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006894 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006895 if (!klass->ShouldHaveImt()) {
6896 return;
6897 }
6898 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6899 // we can just use the same pointer.
6900 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006901 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006902 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6903 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6904 bool same = true;
6905 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6906 ArtMethod* method = imt_data[i];
6907 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6908 if (method != super_method) {
6909 bool is_conflict_table = method->IsRuntimeMethod() &&
6910 method != unimplemented_method &&
6911 method != conflict_method;
6912 // Verify conflict contents.
6913 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6914 super_method != unimplemented_method &&
6915 super_method != conflict_method;
6916 if (!is_conflict_table || !super_conflict_table) {
6917 same = false;
6918 } else {
6919 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6920 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6921 same = same && table1->Equals(table2, image_pointer_size_);
6922 }
6923 }
6924 }
6925 if (same) {
6926 imt = super_imt;
6927 }
6928 }
6929 if (imt == nullptr) {
6930 imt = klass->GetImt(image_pointer_size_);
6931 DCHECK(imt != nullptr);
6932 imt->Populate(imt_data, image_pointer_size_);
6933 } else {
6934 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006935 }
6936}
6937
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006938ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6939 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006940 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006941 void* data = linear_alloc->Alloc(Thread::Current(),
6942 ImtConflictTable::ComputeSize(count,
6943 image_pointer_size));
6944 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6945}
6946
6947ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6948 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6949}
6950
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006951void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006952 ArtMethod* unimplemented_method,
6953 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006954 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006955 bool create_conflict_tables,
6956 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006957 /*out*/bool* new_conflict,
6958 /*out*/ArtMethod** imt) {
6959 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006960 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006961 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006962 const size_t num_virtuals = interface->NumVirtualMethods();
6963 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6964 // Virtual methods can be larger than the if table methods if there are default methods.
6965 DCHECK_GE(num_virtuals, method_array_count);
6966 if (kIsDebugBuild) {
6967 if (klass->IsInterface()) {
6968 DCHECK_EQ(method_array_count, 0u);
6969 } else {
6970 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6971 }
6972 }
6973 if (method_array_count == 0) {
6974 continue;
6975 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006976 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006977 for (size_t j = 0; j < method_array_count; ++j) {
6978 ArtMethod* implementation_method =
6979 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6980 if (ignore_copied_methods && implementation_method->IsCopied()) {
6981 continue;
6982 }
6983 DCHECK(implementation_method != nullptr);
6984 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6985 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6986 // or interface methods in the IMT here they will not create extra conflicts since we compare
6987 // names and signatures in SetIMTRef.
6988 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006989 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006990
6991 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6992 // the same implementation method, keep track of this to avoid creating a conflict table in
6993 // this case.
6994
6995 // Conflict table size for each IMT slot.
6996 ++conflict_counts[imt_index];
6997
6998 SetIMTRef(unimplemented_method,
6999 imt_conflict_method,
7000 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007001 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007002 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007003 }
7004 }
7005
7006 if (create_conflict_tables) {
7007 // Create the conflict tables.
7008 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007009 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007010 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007011 if (imt[i] == imt_conflict_method) {
7012 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7013 if (new_table != nullptr) {
7014 ArtMethod* new_conflict_method =
7015 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7016 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7017 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007018 } else {
7019 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007020 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007021 }
7022 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007023 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007024 }
7025 }
7026
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007027 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007028 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007029 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7030 // Virtual methods can be larger than the if table methods if there are default methods.
7031 if (method_array_count == 0) {
7032 continue;
7033 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007034 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007035 for (size_t j = 0; j < method_array_count; ++j) {
7036 ArtMethod* implementation_method =
7037 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7038 if (ignore_copied_methods && implementation_method->IsCopied()) {
7039 continue;
7040 }
7041 DCHECK(implementation_method != nullptr);
7042 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007043 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007044 if (!imt[imt_index]->IsRuntimeMethod() ||
7045 imt[imt_index] == unimplemented_method ||
7046 imt[imt_index] == imt_conflict_method) {
7047 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007048 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007049 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7050 const size_t num_entries = table->NumEntries(image_pointer_size_);
7051 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7052 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007053 }
7054 }
7055 }
7056}
7057
Alex Lighteb7c1442015-08-31 13:17:42 -07007058// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7059// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007060static bool NotSubinterfaceOfAny(
7061 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
7062 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007063 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007064 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007065 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007066 for (ObjPtr<mirror::Class> c : classes) {
7067 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007068 return false;
7069 }
7070 }
7071 return true;
7072}
7073
7074// Fills in and flattens the interface inheritance hierarchy.
7075//
7076// By the end of this function all interfaces in the transitive closure of to_process are added to
7077// the iftable and every interface precedes all of its sub-interfaces in this list.
7078//
7079// all I, J: Interface | I <: J implies J precedes I
7080//
7081// (note A <: B means that A is a subtype of B)
7082//
7083// This returns the total number of items in the iftable. The iftable might be resized down after
7084// this call.
7085//
7086// We order this backwards so that we do not need to reorder superclass interfaces when new
7087// interfaces are added in subclass's interface tables.
7088//
7089// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7090// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7091// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7092// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007093static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007094 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07007095 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07007096 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007097 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007098 // This is the set of all class's already in the iftable. Used to make checking if a class has
7099 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007100 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07007101 // The first super_ifcount elements are from the superclass. We note that they are already added.
7102 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007103 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007104 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
7105 classes_in_iftable.insert(iface);
7106 }
7107 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007108 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007109 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7110 // At this point in the loop current-iface-list has the invariant that:
7111 // for every pair of interfaces I,J within it:
7112 // if index_of(I) < index_of(J) then I is not a subtype of J
7113
7114 // If we have already seen this element then all of its super-interfaces must already be in the
7115 // current-iface-list so we can skip adding it.
7116 if (!ContainsElement(classes_in_iftable, interface)) {
7117 // We haven't seen this interface so add all of its super-interfaces onto the
7118 // current-iface-list, skipping those already on it.
7119 int32_t ifcount = interface->GetIfTableCount();
7120 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007121 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007122 if (!ContainsElement(classes_in_iftable, super_interface)) {
7123 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
7124 classes_in_iftable.insert(super_interface);
7125 iftable->SetInterface(filled_ifcount, super_interface);
7126 filled_ifcount++;
7127 }
7128 }
7129 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7130 // Place this interface onto the current-iface-list after all of its super-interfaces.
7131 classes_in_iftable.insert(interface);
7132 iftable->SetInterface(filled_ifcount, interface);
7133 filled_ifcount++;
7134 } else if (kIsDebugBuild) {
7135 // Check all super-interfaces are already in the list.
7136 int32_t ifcount = interface->GetIfTableCount();
7137 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007138 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007139 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007140 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7141 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007142 }
7143 }
7144 }
7145 if (kIsDebugBuild) {
7146 // Check that the iftable is ordered correctly.
7147 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007148 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007149 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007150 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007151 // !(if_a <: if_b)
7152 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007153 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7154 << ") extends "
7155 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007156 << "interface list.";
7157 }
7158 }
7159 }
7160 return filled_ifcount;
7161}
7162
7163bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
7164 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7165 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007166 const bool has_superclass = klass->HasSuperClass();
7167 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007168 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007169 const size_t num_interfaces =
7170 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007171 if (num_interfaces == 0) {
7172 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007173 if (LIKELY(has_superclass)) {
7174 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7175 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007176 // Class implements no interfaces.
7177 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007178 return true;
7179 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007180 // Class implements same interfaces as parent, are any of these not marker interfaces?
7181 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007182 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007183 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007184 if (super_iftable->GetMethodArrayCount(i) > 0) {
7185 has_non_marker_interface = true;
7186 break;
7187 }
7188 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007189 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007190 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007191 klass->SetIfTable(super_iftable);
7192 return true;
7193 }
7194 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007195 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007196 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007197 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007198 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007199 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007200 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007201 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007202 if (UNLIKELY(!interface->IsInterface())) {
7203 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007204 ThrowIncompatibleClassChangeError(klass.Get(),
7205 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007206 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007207 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7208 return false;
7209 }
7210 ifcount += interface->GetIfTableCount();
7211 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007212 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007213 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007214 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007215 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007216 return false;
7217 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007218 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007219 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007220 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007221 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007222 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007223 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007224 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007225 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007226
7227 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7228 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7229 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007230 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007231
7232 size_t new_ifcount;
7233 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007234 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007235 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007236 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007237 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007238 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007239 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007240 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007241
7242 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007243 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007244
Ian Rogers7b078e82014-09-10 14:44:24 -07007245 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007246
Ian Rogersb52b01a2012-01-12 17:01:38 -08007247 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007248 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007249 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007250 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007251 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007252 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007253 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007254 return false;
7255 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007256 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007257 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007258 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007259 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007260 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007261 return true;
7262}
7263
Alex Light1f3925d2016-09-07 12:04:20 -07007264// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7265// of methods must be unique.
7266static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7267 return nullptr;
7268}
7269
7270template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007271static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007272 const ScopedArenaVector<ArtMethod*>& list,
7273 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007274 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007275 for (ArtMethod* method : list) {
7276 if (cmp.HasSameNameAndSignature(method)) {
7277 return method;
7278 }
7279 }
Alex Light1f3925d2016-09-07 12:04:20 -07007280 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007281}
7282
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007283namespace {
7284
Alex Light1f3925d2016-09-07 12:04:20 -07007285// Check that all vtable entries are present in this class's virtuals or are the same as a
7286// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007287void CheckClassOwnsVTableEntries(Thread* self,
7288 Handle<mirror::Class> klass,
7289 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007290 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007291 StackHandleScope<2> hs(self);
7292 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007293 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007294 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007295 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007296 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7297 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7298 CHECK(m != nullptr);
7299
Alex Lighta41a30782017-03-29 11:33:19 -07007300 if (m->GetMethodIndexDuringLinking() != i) {
7301 LOG(WARNING) << m->PrettyMethod()
7302 << " has an unexpected method index for its spot in the vtable for class"
7303 << klass->PrettyClass();
7304 }
Alex Lighte64300b2015-12-15 15:02:47 -08007305 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7306 auto is_same_method = [m] (const ArtMethod& meth) {
7307 return &meth == m;
7308 };
Alex Light3f980532017-03-17 15:10:32 -07007309 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7310 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7311 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7312 << klass->PrettyClass() << " or any of its superclasses!";
7313 }
Alex Lighte64300b2015-12-15 15:02:47 -08007314 }
7315}
7316
Alex Light1f3925d2016-09-07 12:04:20 -07007317// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7318// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007319template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007320void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007321 REQUIRES_SHARED(Locks::mutator_lock_) {
7322 StackHandleScope<1> hs(self);
7323 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7324 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007325
7326 // Observations:
7327 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7328 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7329 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7330 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7331 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7332 // * The single-pass algorithm will trade memory for speed, but that is OK.
7333
7334 CHECK_GT(num_entries, 0);
7335
7336 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7337 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7338 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7339 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7340 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7341 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7342 << m2->PrettyMethod() << " (0x" << std::hex
7343 << reinterpret_cast<uintptr_t>(m2) << ")";
7344 };
7345 struct BaseHashType {
7346 static size_t HashCombine(size_t seed, size_t val) {
7347 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7348 }
7349 };
7350
7351 // Check assuming all entries come from the same dex file.
7352 {
7353 // Find the first interesting method and its dex file.
7354 int32_t start = 0;
7355 for (; start < num_entries; ++start) {
7356 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7357 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7358 // maybe).
7359 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7360 vtable_entry->GetAccessFlags())) {
7361 continue;
7362 }
7363 break;
7364 }
7365 if (start == num_entries) {
7366 return;
7367 }
7368 const DexFile* dex_file =
7369 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7370 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7371
7372 // Helper function to avoid logging if we have to run the cross-file checks.
7373 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7374 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7375 using PairType = std::pair<uint32_t, uint16_t>;
7376 struct PairHash : BaseHashType {
7377 size_t operator()(const PairType& key) const {
7378 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7379 }
7380 };
7381 std::unordered_map<PairType, int32_t, PairHash> seen;
7382 seen.reserve(2 * num_entries);
7383 bool need_slow_path = false;
7384 bool found_dup = false;
7385 for (int i = start; i < num_entries; ++i) {
7386 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7387 // wrt/ kPointerSize.
7388 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7389 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7390 vtable_entry->GetAccessFlags())) {
7391 continue;
7392 }
7393 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7394 if (dex_file != m->GetDexFile()) {
7395 need_slow_path = true;
7396 break;
7397 }
7398 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7399 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7400 auto it = seen.find(pair);
7401 if (it != seen.end()) {
7402 found_dup = true;
7403 if (log_warn) {
7404 log_fn(it->second, i);
7405 }
7406 } else {
7407 seen.emplace(pair, i);
7408 }
7409 }
7410 return std::make_pair(need_slow_path, found_dup);
7411 };
7412 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7413 if (!result.first) {
7414 if (result.second) {
7415 check_fn(/* log_warn= */ true);
7416 }
7417 return;
7418 }
7419 }
7420
7421 // Need to check across dex files.
7422 struct Entry {
7423 size_t cached_hash = 0;
7424 const char* name = nullptr;
7425 Signature signature = Signature::NoSignature();
7426 uint32_t name_len = 0;
7427
7428 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7429 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7430 signature(dex_file->GetMethodSignature(mid)) {
7431 }
7432
7433 bool operator==(const Entry& other) const {
7434 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7435 return false;
7436 }
7437 return signature == other.signature;
7438 }
7439 };
7440 struct EntryHash {
7441 size_t operator()(const Entry& key) const {
7442 return key.cached_hash;
7443 }
7444 };
7445 std::unordered_map<Entry, int32_t, EntryHash> map;
7446 for (int32_t i = 0; i < num_entries; ++i) {
7447 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7448 // wrt/ kPointerSize.
7449 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7450 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7451 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007452 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7453 vtable_entry->GetAccessFlags())) {
7454 continue;
7455 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007456 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7457 const DexFile* dex_file = m->GetDexFile();
7458 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7459
7460 Entry e(dex_file, mid);
7461
7462 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7463 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7464 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7465 sig_hash);
7466
7467 auto it = map.find(e);
7468 if (it != map.end()) {
7469 log_fn(it->second, i);
7470 } else {
7471 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007472 }
7473 }
7474}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007475
7476void CheckVTableHasNoDuplicates(Thread* self,
7477 Handle<mirror::Class> klass,
7478 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007479 REQUIRES_SHARED(Locks::mutator_lock_) {
7480 switch (pointer_size) {
7481 case PointerSize::k64:
7482 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7483 break;
7484 case PointerSize::k32:
7485 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7486 break;
7487 }
7488}
Alex Light1f3925d2016-09-07 12:04:20 -07007489
7490static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7491 REQUIRES_SHARED(Locks::mutator_lock_) {
7492 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7493 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7494}
7495
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007496} // namespace
7497
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007498void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7499 ArtMethod* unimplemented_method,
7500 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007501 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007502 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007503 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007504 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007505 if (super_class->ShouldHaveImt()) {
7506 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7507 for (size_t i = 0; i < ImTable::kSize; ++i) {
7508 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007509 }
7510 } else {
7511 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007512 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007513 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007514 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007515 FillIMTFromIfTable(if_table,
7516 unimplemented_method,
7517 imt_conflict_method,
7518 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007519 /*create_conflict_tables=*/false,
7520 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007521 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007522 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007523 }
7524 }
7525}
7526
Vladimir Marko921094a2017-01-12 18:37:06 +00007527class ClassLinker::LinkInterfaceMethodsHelper {
7528 public:
7529 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7530 Handle<mirror::Class> klass,
7531 Thread* self,
7532 Runtime* runtime)
7533 : class_linker_(class_linker),
7534 klass_(klass),
7535 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7536 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7537 self_(self),
7538 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7539 allocator_(&stack_),
7540 default_conflict_methods_(allocator_.Adapter()),
7541 overriding_default_conflict_methods_(allocator_.Adapter()),
7542 miranda_methods_(allocator_.Adapter()),
7543 default_methods_(allocator_.Adapter()),
7544 overriding_default_methods_(allocator_.Adapter()),
7545 move_table_(allocator_.Adapter()) {
7546 }
7547
7548 ArtMethod* FindMethod(ArtMethod* interface_method,
7549 MethodNameAndSignatureComparator& interface_name_comparator,
7550 ArtMethod* vtable_impl)
7551 REQUIRES_SHARED(Locks::mutator_lock_);
7552
7553 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7554 MethodNameAndSignatureComparator& interface_name_comparator)
7555 REQUIRES_SHARED(Locks::mutator_lock_);
7556
7557 bool HasNewVirtuals() const {
7558 return !(miranda_methods_.empty() &&
7559 default_methods_.empty() &&
7560 overriding_default_methods_.empty() &&
7561 overriding_default_conflict_methods_.empty() &&
7562 default_conflict_methods_.empty());
7563 }
7564
7565 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7566
7567 ObjPtr<mirror::PointerArray> UpdateVtable(
7568 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007569 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007570
7571 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7572
7573 void UpdateIMT(ArtMethod** out_imt);
7574
7575 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7576 if (kIsDebugBuild) {
7577 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7578 // Check that there are no stale methods are in the dex cache array.
7579 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7580 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007581 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7582 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007583 CHECK(move_table_.find(m) == move_table_.end() ||
7584 // The original versions of copied methods will still be present so allow those too.
7585 // Note that if the first check passes this might fail to GetDeclaringClass().
7586 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7587 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7588 [m] (ArtMethod& meth) {
7589 return &meth == m;
7590 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7591 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7592 }
7593 }
7594 }
7595
7596 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7597 LengthPrefixedArray<ArtMethod>* methods) {
7598 if (kIsDebugBuild) {
7599 CHECK(methods != nullptr);
7600 // Put some random garbage in old methods to help find stale pointers.
7601 if (methods != old_methods && old_methods != nullptr) {
7602 // Need to make sure the GC is not running since it could be scanning the methods we are
7603 // about to overwrite.
7604 ScopedThreadStateChange tsc(self_, kSuspended);
7605 gc::ScopedGCCriticalSection gcs(self_,
7606 gc::kGcCauseClassLinker,
7607 gc::kCollectorTypeClassLinker);
7608 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7609 method_size_,
7610 method_alignment_);
7611 memset(old_methods, 0xFEu, old_size);
7612 }
7613 }
7614 }
7615
7616 private:
7617 size_t NumberOfNewVirtuals() const {
7618 return miranda_methods_.size() +
7619 default_methods_.size() +
7620 overriding_default_conflict_methods_.size() +
7621 overriding_default_methods_.size() +
7622 default_conflict_methods_.size();
7623 }
7624
7625 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7626 return !klass_->IsInterface();
7627 }
7628
7629 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7630 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7631 << "Interfaces should only have default-conflict methods appended to them.";
7632 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7633 << miranda_methods_.size()
7634 << " default_methods=" << default_methods_.size()
7635 << " overriding_default_methods=" << overriding_default_methods_.size()
7636 << " default_conflict_methods=" << default_conflict_methods_.size()
7637 << " overriding_default_conflict_methods="
7638 << overriding_default_conflict_methods_.size();
7639 }
7640
7641 ClassLinker* class_linker_;
7642 Handle<mirror::Class> klass_;
7643 size_t method_alignment_;
7644 size_t method_size_;
7645 Thread* const self_;
7646
7647 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7648 // the virtual methods array.
7649 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7650 // during cross compilation.
7651 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7652 ArenaStack stack_;
7653 ScopedArenaAllocator allocator_;
7654
7655 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7656 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7657 ScopedArenaVector<ArtMethod*> miranda_methods_;
7658 ScopedArenaVector<ArtMethod*> default_methods_;
7659 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7660
7661 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7662};
7663
7664ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7665 ArtMethod* interface_method,
7666 MethodNameAndSignatureComparator& interface_name_comparator,
7667 ArtMethod* vtable_impl) {
7668 ArtMethod* current_method = nullptr;
7669 switch (class_linker_->FindDefaultMethodImplementation(self_,
7670 interface_method,
7671 klass_,
7672 /*out*/&current_method)) {
7673 case DefaultMethodSearchResult::kDefaultConflict: {
7674 // Default method conflict.
7675 DCHECK(current_method == nullptr);
7676 ArtMethod* default_conflict_method = nullptr;
7677 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7678 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7679 default_conflict_method = vtable_impl;
7680 } else {
7681 // See if we already have a conflict method for this method.
7682 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7683 interface_name_comparator,
7684 default_conflict_methods_,
7685 overriding_default_conflict_methods_);
7686 if (LIKELY(preexisting_conflict != nullptr)) {
7687 // We already have another conflict we can reuse.
7688 default_conflict_method = preexisting_conflict;
7689 } else {
7690 // Note that we do this even if we are an interface since we need to create this and
7691 // cannot reuse another classes.
7692 // Create a new conflict method for this to use.
7693 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7694 new(default_conflict_method) ArtMethod(interface_method,
7695 class_linker_->GetImagePointerSize());
7696 if (vtable_impl == nullptr) {
7697 // Save the conflict method. We need to add it to the vtable.
7698 default_conflict_methods_.push_back(default_conflict_method);
7699 } else {
7700 // Save the conflict method but it is already in the vtable.
7701 overriding_default_conflict_methods_.push_back(default_conflict_method);
7702 }
7703 }
7704 }
7705 current_method = default_conflict_method;
7706 break;
7707 } // case kDefaultConflict
7708 case DefaultMethodSearchResult::kDefaultFound: {
7709 DCHECK(current_method != nullptr);
7710 // Found a default method.
7711 if (vtable_impl != nullptr &&
7712 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7713 // We found a default method but it was the same one we already have from our
7714 // superclass. Don't bother adding it to our vtable again.
7715 current_method = vtable_impl;
7716 } else if (LIKELY(FillTables())) {
7717 // Interfaces don't need to copy default methods since they don't have vtables.
7718 // Only record this default method if it is new to save space.
7719 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7720 // would make lookup for interface super much faster. (We would only need to scan
7721 // the iftable to find if there is a NSME or AME.)
7722 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7723 default_methods_,
7724 overriding_default_methods_);
7725 if (old == nullptr) {
7726 // We found a default method implementation and there were no conflicts.
7727 if (vtable_impl == nullptr) {
7728 // Save the default method. We need to add it to the vtable.
7729 default_methods_.push_back(current_method);
7730 } else {
7731 // Save the default method but it is already in the vtable.
7732 overriding_default_methods_.push_back(current_method);
7733 }
7734 } else {
7735 CHECK(old == current_method) << "Multiple default implementations selected!";
7736 }
7737 }
7738 break;
7739 } // case kDefaultFound
7740 case DefaultMethodSearchResult::kAbstractFound: {
7741 DCHECK(current_method == nullptr);
7742 // Abstract method masks all defaults.
7743 if (vtable_impl != nullptr &&
7744 vtable_impl->IsAbstract() &&
7745 !vtable_impl->IsDefaultConflicting()) {
7746 // We need to make this an abstract method but the version in the vtable already is so
7747 // don't do anything.
7748 current_method = vtable_impl;
7749 }
7750 break;
7751 } // case kAbstractFound
7752 }
7753 return current_method;
7754}
7755
7756ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7757 ArtMethod* interface_method,
7758 MethodNameAndSignatureComparator& interface_name_comparator) {
7759 // Find out if there is already a miranda method we can use.
7760 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7761 miranda_methods_);
7762 if (miranda_method == nullptr) {
7763 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7764 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7765 CHECK(miranda_method != nullptr);
7766 // Point the interface table at a phantom slot.
7767 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7768 miranda_methods_.push_back(miranda_method);
7769 }
7770 return miranda_method;
7771}
7772
7773void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7774 LogNewVirtuals();
7775
7776 const size_t old_method_count = klass_->NumMethods();
7777 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7778 DCHECK_NE(old_method_count, new_method_count);
7779
7780 // Attempt to realloc to save RAM if possible.
7781 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7782 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7783 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7784 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7785 // CopyFrom has internal read barriers.
7786 //
7787 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7788 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7789 method_size_,
7790 method_alignment_);
7791 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7792 method_size_,
7793 method_alignment_);
7794 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7795 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007796 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007797 self_, old_methods, old_methods_ptr_size, new_size));
7798 CHECK(methods != nullptr); // Native allocation failure aborts.
7799
7800 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7801 if (methods != old_methods) {
7802 // Maps from heap allocated miranda method to linear alloc miranda method.
7803 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7804 // Copy over the old methods.
7805 for (auto& m : klass_->GetMethods(pointer_size)) {
7806 move_table_.emplace(&m, &*out);
7807 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7808 // barriers when it copies.
7809 out->CopyFrom(&m, pointer_size);
7810 ++out;
7811 }
7812 }
7813 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7814 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7815 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007816 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7817 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007818 ArtMethod& new_method = *out;
7819 new_method.CopyFrom(mir_method, pointer_size);
7820 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7821 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7822 << "Miranda method should be abstract!";
7823 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007824 // Update the entry in the method array, as the array will be used for future lookups,
7825 // where thread suspension is allowed.
7826 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7827 // would not see them.
7828 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007829 ++out;
7830 }
7831 // We need to copy the default methods into our own method table since the runtime requires that
7832 // every method on a class's vtable be in that respective class's virtual method table.
7833 // NOTE This means that two classes might have the same implementation of a method from the same
7834 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7835 // default method found on a class with one found on the declaring interface directly and must
7836 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007837 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7838 &overriding_default_methods_}) {
7839 for (size_t i = 0; i < methods_vec->size(); ++i) {
7840 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007841 ArtMethod& new_method = *out;
7842 new_method.CopyFrom(def_method, pointer_size);
7843 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7844 // verified yet it shouldn't have methods that are skipping access checks.
7845 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7846 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007847 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007848 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7849 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7850 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7851 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007852 // Update the entry in the method array, as the array will be used for future lookups,
7853 // where thread suspension is allowed.
7854 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7855 // would not see them.
7856 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007857 ++out;
7858 }
7859 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007860 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7861 &overriding_default_conflict_methods_}) {
7862 for (size_t i = 0; i < methods_vec->size(); ++i) {
7863 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007864 ArtMethod& new_method = *out;
7865 new_method.CopyFrom(conf_method, pointer_size);
7866 // This is a type of default method (there are default method impls, just a conflict) so
7867 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7868 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7869 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007870 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7871 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007872 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007873 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007874 constexpr uint32_t kMaskFlags =
7875 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007876 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7877 DCHECK(new_method.IsDefaultConflicting());
7878 // The actual method might or might not be marked abstract since we just copied it from a
7879 // (possibly default) interface method. We need to set it entry point to be the bridge so
7880 // that the compiler will not invoke the implementation of whatever method we copied from.
7881 EnsureThrowsInvocationError(class_linker_, &new_method);
7882 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007883 // Update the entry in the method array, as the array will be used for future lookups,
7884 // where thread suspension is allowed.
7885 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7886 // would not see them.
7887 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007888 ++out;
7889 }
7890 }
7891 methods->SetSize(new_method_count);
7892 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7893}
7894
7895ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7896 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007897 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007898 // Update the vtable to the new method structures. We can skip this for interfaces since they
7899 // do not have vtables.
7900 const size_t old_vtable_count = old_vtable->GetLength();
7901 const size_t new_vtable_count = old_vtable_count +
7902 miranda_methods_.size() +
7903 default_methods_.size() +
7904 default_conflict_methods_.size();
7905
Vladimir Marko3068d582019-05-28 16:39:29 +01007906 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
7907 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007908 if (UNLIKELY(vtable == nullptr)) {
7909 self_->AssertPendingOOMException();
7910 return nullptr;
7911 }
7912
7913 size_t vtable_pos = old_vtable_count;
7914 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7915 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7916 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7917 default_conflict_methods_,
7918 miranda_methods_}) {
7919 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007920 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007921 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7922 // fields are references into the dex file the method was defined in. Since the ArtMethod
7923 // does not store that information it uses declaring_class_->dex_cache_.
7924 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7925 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7926 ++vtable_pos;
7927 }
7928 }
7929 DCHECK_EQ(vtable_pos, new_vtable_count);
7930
7931 // Update old vtable methods. We use the default_translations map to figure out what each
7932 // vtable entry should be updated to, if they need to be at all.
7933 for (size_t i = 0; i < old_vtable_count; ++i) {
7934 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7935 // Try and find what we need to change this method to.
7936 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007937 if (translation_it != default_translations.end()) {
7938 if (translation_it->second.IsInConflict()) {
7939 // Find which conflict method we are to use for this method.
7940 MethodNameAndSignatureComparator old_method_comparator(
7941 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7942 // We only need to look through overriding_default_conflict_methods since this is an
7943 // overridden method we are fixing up here.
7944 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7945 old_method_comparator, overriding_default_conflict_methods_);
7946 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7947 translated_method = new_conflict_method;
7948 } else if (translation_it->second.IsAbstract()) {
7949 // Find which miranda method we are to use for this method.
7950 MethodNameAndSignatureComparator old_method_comparator(
7951 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7952 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7953 miranda_methods_);
7954 DCHECK(miranda_method != nullptr);
7955 translated_method = miranda_method;
7956 } else {
7957 // Normal default method (changed from an older default or abstract interface method).
7958 DCHECK(translation_it->second.IsTranslation());
7959 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007960 auto it = move_table_.find(translated_method);
7961 DCHECK(it != move_table_.end());
7962 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007963 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007964 } else {
7965 auto it = move_table_.find(translated_method);
7966 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007967 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007968
7969 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007970 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007971 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007972 if (kIsDebugBuild) {
7973 auto* methods = klass_->GetMethodsPtr();
7974 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007975 reinterpret_cast<uintptr_t>(translated_method));
7976 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007977 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7978 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007979 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007980 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007981 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007982 }
7983 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007984 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007985 return vtable;
7986}
7987
7988void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7989 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7990 const size_t ifcount = klass_->GetIfTableCount();
7991 // Go fix up all the stale iftable pointers.
7992 for (size_t i = 0; i < ifcount; ++i) {
7993 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00007994 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
7995 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007996 DCHECK(m != nullptr) << klass_->PrettyClass();
7997 auto it = move_table_.find(m);
7998 if (it != move_table_.end()) {
7999 auto* new_m = it->second;
8000 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8001 method_array->SetElementPtrSize(j, new_m, pointer_size);
8002 }
8003 }
8004 }
8005}
8006
8007void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8008 // Fix up IMT next.
8009 for (size_t i = 0; i < ImTable::kSize; ++i) {
8010 auto it = move_table_.find(out_imt[i]);
8011 if (it != move_table_.end()) {
8012 out_imt[i] = it->second;
8013 }
8014 }
8015}
8016
Alex Light705ad492015-09-21 11:36:30 -07008017// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008018bool ClassLinker::LinkInterfaceMethods(
8019 Thread* self,
8020 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07008021 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008022 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008023 ArtMethod** out_imt) {
8024 StackHandleScope<3> hs(self);
8025 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008026
8027 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008028 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008029 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008030 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008031 const size_t ifcount = klass->GetIfTableCount();
8032
Vladimir Marko921094a2017-01-12 18:37:06 +00008033 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008034
8035 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8036 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008037 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008038 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008039 const bool extend_super_iftable = has_superclass;
8040 if (has_superclass && fill_tables) {
8041 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008042 unimplemented_method,
8043 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008044 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008045 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008046 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008047 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8048 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008049 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008050 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8051 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008052 }
8053 }
8054
Vladimir Marko921094a2017-01-12 18:37:06 +00008055 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8056
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008057 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008058 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008059 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8060 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8061 // they will already be null. This has the additional benefit that the declarer of a miranda
8062 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008063 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008064 --i;
Alex Light9139e002015-10-09 15:59:48 -07008065 DCHECK_LT(i, ifcount);
8066
Alex Light705ad492015-09-21 11:36:30 -07008067 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008068 if (num_methods > 0) {
8069 StackHandleScope<2> hs2(self);
8070 const bool is_super = i < super_ifcount;
8071 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008072 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8073 // conflict methods. Just set this as nullptr in those cases.
8074 Handle<mirror::PointerArray> method_array(fill_tables
8075 ? hs2.NewHandle(iftable->GetMethodArray(i))
8076 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008077
Alex Lighte64300b2015-12-15 15:02:47 -08008078 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008079 ScopedNullHandle<mirror::PointerArray> null_handle;
8080 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008081 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008082
Alex Light9139e002015-10-09 15:59:48 -07008083 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8084 // and confusing. Default methods should always look through all the superclasses
8085 // because they are the last choice of an implementation. We get around this by looking
8086 // at the super-classes iftable methods (copied into method_array previously) when we are
8087 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008088 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008089 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008090 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008091 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008092 using_virtuals = true;
8093 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
8094 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008095 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008096 // For a new interface, however, we need the whole vtable in case a new
8097 // interface method is implemented in the whole superclass.
8098 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008099 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008100 input_vtable_array = vtable;
8101 input_array_length = input_vtable_array->GetLength();
8102 }
Alex Lighte64300b2015-12-15 15:02:47 -08008103
Alex Lighteb7c1442015-08-31 13:17:42 -07008104 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008105 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008106 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008107 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008108 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008109 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008110 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008111 // For each method listed in the interface's method list, find the
8112 // matching method in our class's method list. We want to favor the
8113 // subclass over the superclass, which just requires walking
8114 // back from the end of the vtable. (This only matters if the
8115 // superclass defines a private method and this class redefines
8116 // it -- otherwise it would use the same vtable slot. In .dex files
8117 // those don't end up in the virtual method table, so it shouldn't
8118 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008119 //
8120 // To find defaults we need to do the same but also go over interfaces.
8121 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008122 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008123 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008124 ArtMethod* vtable_method = using_virtuals ?
8125 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008126 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8127 ArtMethod* vtable_method_for_name_comparison =
8128 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008129 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008130 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008131 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008132 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8133 // allocations.
8134 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008135 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008136 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008137 vtable_method->PrettyMethod().c_str(),
8138 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008139 return false;
Alex Light9139e002015-10-09 15:59:48 -07008140 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008141 // We might have a newer, better, default method for this, so we just skip it. If we
8142 // are still using this we will select it again when scanning for default methods. To
8143 // obviate the need to copy the method again we will make a note that we already found
8144 // a default here.
8145 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008146 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008147 break;
8148 } else {
8149 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008150 if (LIKELY(fill_tables)) {
8151 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8152 // Place method in imt if entry is empty, place conflict otherwise.
8153 SetIMTRef(unimplemented_method,
8154 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008155 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008156 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008157 /*out*/imt_ptr);
8158 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008159 break;
8160 }
8161 }
Alex Light9139e002015-10-09 15:59:48 -07008162 }
8163 // Continue on to the next method if we are done.
8164 if (LIKELY(found_impl)) {
8165 continue;
8166 } else if (LIKELY(super_interface)) {
8167 // Don't look for a default implementation when the super-method is implemented directly
8168 // by the class.
8169 //
8170 // See if we can use the superclasses method and skip searching everything else.
8171 // Note: !found_impl && super_interface
8172 CHECK(extend_super_iftable);
8173 // If this is a super_interface method it is possible we shouldn't override it because a
8174 // superclass could have implemented it directly. We get the method the superclass used
8175 // to implement this to know if we can override it with a default method. Doing this is
8176 // safe since we know that the super_iftable is filled in so we can simply pull it from
8177 // there. We don't bother if this is not a super-classes interface since in that case we
8178 // have scanned the entire vtable anyway and would have found it.
8179 // TODO This is rather dirty but it is faster than searching through the entire vtable
8180 // every time.
8181 ArtMethod* supers_method =
8182 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8183 DCHECK(supers_method != nullptr);
8184 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008185 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008186 // The method is not overridable by a default method (i.e. it is directly implemented
8187 // in some class). Therefore move onto the next interface method.
8188 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008189 } else {
8190 // If the super-classes method is override-able by a default method we need to keep
8191 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8192 // 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 -07008193 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8194 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8195 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008196 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008197 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8198 << " and not 'nullptr' or "
8199 << supers_method->PrettyMethod()
8200 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008201 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008202 }
8203 }
8204 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008205 ArtMethod* current_method = helper.FindMethod(interface_method,
8206 interface_name_comparator,
8207 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008208 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008209 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008210 // We could not find an implementation for this method and since it is a brand new
8211 // interface we searched the entire vtable (and all default methods) for an
8212 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008213 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8214 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008215 }
8216
8217 if (current_method != nullptr) {
8218 // We found a default method implementation. Record it in the iftable and IMT.
8219 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8220 SetIMTRef(unimplemented_method,
8221 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008222 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008223 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008224 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008225 }
8226 }
Alex Light705ad492015-09-21 11:36:30 -07008227 } // For each method in interface end.
8228 } // if (num_methods > 0)
8229 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008230 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008231 if (helper.HasNewVirtuals()) {
8232 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8233 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8234 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8235
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008236 // 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 -07008237 // suspension assert.
8238 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008239
Alex Light705ad492015-09-21 11:36:30 -07008240 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008241 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008242 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008243 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008244 return false;
8245 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008246 helper.UpdateIfTable(iftable);
8247 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008248 }
Alex Light705ad492015-09-21 11:36:30 -07008249
Vladimir Marko921094a2017-01-12 18:37:06 +00008250 helper.CheckNoStaleMethodsInDexCache();
8251 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008252 } else {
8253 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008254 }
Alex Light705ad492015-09-21 11:36:30 -07008255 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008256 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008257 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008258 return true;
8259}
8260
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008261bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008262 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008263 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008264}
8265
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008266bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008267 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008268 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008269}
8270
Brian Carlstromdbc05252011-09-09 01:59:59 -07008271struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008272 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008273 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008274 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008275 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008276 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008277 // 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 -07008278 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8279 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008280 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008281 if (type1 == Primitive::kPrimNot) {
8282 // Reference always goes first.
8283 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008284 }
Vladimir Markod5777482014-11-12 17:02:02 +00008285 if (type2 == Primitive::kPrimNot) {
8286 // Reference always goes first.
8287 return false;
8288 }
8289 size_t size1 = Primitive::ComponentSize(type1);
8290 size_t size2 = Primitive::ComponentSize(type2);
8291 if (size1 != size2) {
8292 // Larger primitive types go first.
8293 return size1 > size2;
8294 }
8295 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8296 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008297 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008298 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8299 // by name and for equal names by type id index.
8300 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8301 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008302 }
8303};
8304
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008305bool ClassLinker::LinkFields(Thread* self,
8306 Handle<mirror::Class> klass,
8307 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008308 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008309 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008310 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008311 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8312 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008313
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008314 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008315 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008316 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008317 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008318 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008319 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008320 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008321 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008322 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008323 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008324 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008325 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008326
David Sehr709b0702016-10-13 09:12:37 -07008327 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008328
Brian Carlstromdbc05252011-09-09 01:59:59 -07008329 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008330 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008331 //
8332 // The overall sort order order is:
8333 // 1) All object reference fields, sorted alphabetically.
8334 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8335 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8336 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8337 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8338 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8339 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8340 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8341 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8342 //
8343 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8344 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008345 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008346 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008347 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008348 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008349 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008350 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008351 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8352 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008353
Fred Shih381e4ca2014-08-25 17:24:27 -07008354 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008355 size_t current_field = 0;
8356 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008357 FieldGaps gaps;
8358
Brian Carlstromdbc05252011-09-09 01:59:59 -07008359 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008360 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008361 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008362 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008363 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008364 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008365 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008366 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8367 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008368 MemberOffset old_offset = field_offset;
8369 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8370 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8371 }
Roland Levillain14d90572015-07-16 10:52:26 +01008372 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008373 grouped_and_sorted_fields.pop_front();
8374 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008375 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008376 field_offset = MemberOffset(field_offset.Uint32Value() +
8377 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008378 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008379 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8380 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008381 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8382 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8383 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8384 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008385 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8386 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008387 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008388
Elliott Hughesadb460d2011-10-05 17:02:34 -07008389 // 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 -07008390 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008391 // We know there are no non-reference fields in the Reference classes, and we know
8392 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008393 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008394 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008395 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008396 --num_reference_fields;
8397 }
8398
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008399 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008400 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008401 if (is_static) {
8402 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008403 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008404 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008405 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008406 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008407 if (num_reference_fields == 0 || super_class == nullptr) {
8408 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008409 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008410 if (super_class == nullptr ||
8411 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8412 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008413 }
8414 }
8415 if (kIsDebugBuild) {
8416 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8417 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008418 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008419 while (cur_super != nullptr) {
8420 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8421 cur_super = cur_super->GetSuperClass();
8422 }
8423 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008424 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008425 } else {
8426 // Check that there is at least num_reference_fields other than Object.class.
8427 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008428 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008429 }
8430 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008431 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008432 std::string temp;
8433 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8434 size_t previous_size = klass->GetObjectSize();
8435 if (previous_size != 0) {
8436 // Make sure that we didn't originally have an incorrect size.
8437 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008438 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008439 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008440 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008441 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008442
8443 if (kIsDebugBuild) {
8444 // Make sure that the fields array is ordered by name but all reference
8445 // offsets are at the beginning as far as alignment allows.
8446 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008447 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008448 : klass->GetFirstReferenceInstanceFieldOffset();
8449 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8450 num_reference_fields *
8451 sizeof(mirror::HeapReference<mirror::Object>));
8452 MemberOffset current_ref_offset = start_ref_offset;
8453 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008454 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008455 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008456 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8457 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008458 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008459 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008460 // NOTE: The field names can be the same. This is not possible in the Java language
8461 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008462 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008463 }
8464 Primitive::Type type = field->GetTypeAsPrimitiveType();
8465 bool is_primitive = type != Primitive::kPrimNot;
8466 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8467 strcmp("referent", field->GetName()) == 0) {
8468 is_primitive = true; // We lied above, so we have to expect a lie here.
8469 }
8470 MemberOffset offset = field->GetOffsetDuringLinking();
8471 if (is_primitive) {
8472 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8473 // Shuffled before references.
8474 size_t type_size = Primitive::ComponentSize(type);
8475 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8476 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8477 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8478 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8479 }
8480 } else {
8481 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8482 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8483 sizeof(mirror::HeapReference<mirror::Object>));
8484 }
8485 }
8486 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8487 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008488 return true;
8489}
8490
Vladimir Marko76649e82014-11-10 18:32:59 +00008491// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008492void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008493 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008494 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008495 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008496 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008497 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008498 // Compute reference offsets unless our superclass overflowed.
8499 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8500 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008501 if (num_reference_fields != 0u) {
8502 // All of the fields that contain object references are guaranteed be grouped in memory
8503 // starting at an appropriately aligned address after super class object data.
8504 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8505 sizeof(mirror::HeapReference<mirror::Object>));
8506 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008507 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008508 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008509 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008510 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008511 reference_offsets |= (0xffffffffu << start_bit) &
8512 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008513 }
8514 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008515 }
8516 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008517 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008518}
8519
Vladimir Marko18090d12018-06-01 16:53:12 +01008520ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8521 ObjPtr<mirror::DexCache> dex_cache) {
8522 StackHandleScope<1> hs(Thread::Current());
8523 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8524 return DoResolveString(string_idx, h_dex_cache);
8525}
8526
8527ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8528 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008529 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008530 uint32_t utf16_length;
8531 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008532 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008533 if (string != nullptr) {
8534 dex_cache->SetResolvedString(string_idx, string);
8535 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008536 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008537}
8538
Vladimir Marko18090d12018-06-01 16:53:12 +01008539ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8540 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008541 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008542 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008543 uint32_t utf16_length;
8544 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008545 ObjPtr<mirror::String> string =
8546 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008547 if (string != nullptr) {
8548 dex_cache->SetResolvedString(string_idx, string);
8549 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008550 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008551}
8552
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008553ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008554 ObjPtr<mirror::Class> referrer) {
8555 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8556}
8557
8558ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008559 ObjPtr<mirror::DexCache> dex_cache,
8560 ObjPtr<mirror::ClassLoader> class_loader) {
8561 const DexFile& dex_file = *dex_cache->GetDexFile();
8562 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8563 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8564 ObjPtr<mirror::Class> type = nullptr;
8565 if (descriptor[1] == '\0') {
8566 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8567 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008568 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008569 } else {
8570 Thread* const self = Thread::Current();
8571 DCHECK(self != nullptr);
8572 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8573 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008574 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008575 }
8576 if (type != nullptr) {
8577 if (type->IsResolved()) {
8578 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008579 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008580 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008581 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008582 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008583 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008584}
8585
Andreas Gampeb0625e02019-05-01 12:43:31 -07008586template <typename RefType>
8587ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008588 StackHandleScope<2> hs(Thread::Current());
8589 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8590 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8591 return DoResolveType(type_idx, dex_cache, class_loader);
8592}
8593
Andreas Gampe4835d212018-11-21 14:55:10 -08008594// Instantiate the above.
8595template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8596 ArtField* referrer);
8597template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8598 ArtMethod* referrer);
8599template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8600 ObjPtr<mirror::Class> referrer);
8601
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008602ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008603 Handle<mirror::DexCache> dex_cache,
8604 Handle<mirror::ClassLoader> class_loader) {
8605 Thread* self = Thread::Current();
8606 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8607 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8608 if (resolved != nullptr) {
8609 // TODO: we used to throw here if resolved's class loader was not the
8610 // boot class loader. This was to permit different classes with the
8611 // same name to be loaded simultaneously by different loaders
8612 dex_cache->SetResolvedType(type_idx, resolved);
8613 } else {
8614 CHECK(self->IsExceptionPending())
8615 << "Expected pending exception for failed resolution of: " << descriptor;
8616 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8617 StackHandleScope<1> hs(self);
8618 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008619 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008620 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8621 self->ClearException();
8622 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8623 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008624 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008625 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008626 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008627 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008628 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008629}
8630
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008631ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8632 ObjPtr<mirror::DexCache> dex_cache,
8633 ObjPtr<mirror::ClassLoader> class_loader,
8634 uint32_t method_idx) {
8635 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8636 // functions can optimize the search if the dex_cache is the same as the DexCache
8637 // of the class, with fall-back to name and signature search otherwise.
8638 ArtMethod* resolved = nullptr;
8639 if (klass->IsInterface()) {
8640 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8641 } else {
8642 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8643 }
8644 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008645 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008646 hiddenapi::ShouldDenyAccessToMember(resolved,
8647 hiddenapi::AccessContext(class_loader, dex_cache),
8648 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008649 resolved = nullptr;
8650 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008651 if (resolved != nullptr) {
8652 // In case of jmvti, the dex file gets verified before being registered, so first
8653 // check if it's registered before checking class tables.
8654 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008655 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8656 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008657 << "DexFile referrer: " << dex_file.GetLocation()
8658 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8659 // Be a good citizen and update the dex cache to speed subsequent calls.
8660 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008661 // Disable the following invariant check as the verifier breaks it. b/73760543
8662 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8663 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8664 // << "Method: " << resolved->PrettyMethod() << ", "
8665 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8666 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008667 }
8668 return resolved;
8669}
8670
David Brazdil4525e0b2018-04-05 16:57:32 +01008671// Returns true if `method` is either null or hidden.
8672// Does not print any warnings if it is hidden.
8673static bool CheckNoSuchMethod(ArtMethod* method,
8674 ObjPtr<mirror::DexCache> dex_cache,
8675 ObjPtr<mirror::ClassLoader> class_loader)
8676 REQUIRES_SHARED(Locks::mutator_lock_) {
8677 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008678 hiddenapi::ShouldDenyAccessToMember(method,
8679 hiddenapi::AccessContext(class_loader, dex_cache),
8680 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008681}
8682
8683ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8684 ObjPtr<mirror::DexCache> dex_cache,
8685 ObjPtr<mirror::ClassLoader> class_loader,
8686 uint32_t method_idx) {
8687 if (klass->IsInterface()) {
8688 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8689 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8690 } else {
8691 // If there was an interface method with the same signature, we would have
8692 // found it in the "copied" methods. Only DCHECK that the interface method
8693 // really does not exist.
8694 if (kIsDebugBuild) {
8695 ArtMethod* method =
8696 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8697 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8698 }
8699 return nullptr;
8700 }
8701}
8702
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008703template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008704ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008705 Handle<mirror::DexCache> dex_cache,
8706 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008707 ArtMethod* referrer,
8708 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008709 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008710 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008711 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008712 PointerSize pointer_size = image_pointer_size_;
8713 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008714 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008715 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8716 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008717 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8718 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008719 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008720 return resolved;
8721 }
Vladimir Marko89011192017-12-11 13:45:05 +00008722 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008723 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008724 ObjPtr<mirror::Class> klass = nullptr;
8725 if (valid_dex_cache_method) {
8726 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8727 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008728 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008729 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008730 // We normaly should not end up here. However the verifier currently doesn't guarantee
8731 // the invariant of having the klass in the class table. b/73760543
8732 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008733 }
Vladimir Markoba118822017-06-12 15:41:56 +01008734 } else {
8735 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008736 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008737 if (klass == nullptr) {
8738 DCHECK(Thread::Current()->IsExceptionPending());
8739 return nullptr;
8740 }
8741 }
8742
8743 // Check if the invoke type matches the class type.
8744 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008745 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008746 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008747 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008748 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008749 }
Vladimir Markoba118822017-06-12 15:41:56 +01008750
8751 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008752 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008753 }
Vladimir Markoba118822017-06-12 15:41:56 +01008754
8755 // Note: We can check for IllegalAccessError only if we have a referrer.
8756 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8757 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8758 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8759 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8760 resolved,
8761 dex_cache.Get(),
8762 method_idx,
8763 type)) {
8764 DCHECK(Thread::Current()->IsExceptionPending());
8765 return nullptr;
8766 }
8767 }
8768
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008769 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008770 if (LIKELY(resolved != nullptr) &&
8771 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8772 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008773 return resolved;
8774 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008775 // If we had a method, or if we can find one with another lookup type,
8776 // it's an incompatible-class-change error.
8777 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008778 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008779 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008780 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008781 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008782 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008783 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008784 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8785 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008786 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008787 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008788 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008789 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008790 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008791}
8792
Vladimir Marko89011192017-12-11 13:45:05 +00008793ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008794 Handle<mirror::DexCache> dex_cache,
8795 Handle<mirror::ClassLoader> class_loader) {
8796 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008797 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008798 if (resolved != nullptr) {
8799 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008800 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8801 return resolved;
8802 }
8803 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008804 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008805 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008806 if (klass == nullptr) {
8807 Thread::Current()->AssertPendingException();
8808 return nullptr;
8809 }
8810 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008811 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8812 } else {
8813 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008814 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008815 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008816 hiddenapi::ShouldDenyAccessToMember(
8817 resolved,
8818 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8819 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008820 resolved = nullptr;
8821 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008822 return resolved;
8823}
8824
Vladimir Markof44d36c2017-03-14 14:18:46 +00008825ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8826 ObjPtr<mirror::DexCache> dex_cache,
8827 ObjPtr<mirror::ClassLoader> class_loader,
8828 bool is_static) {
8829 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008830 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008831 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8832 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008833 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008834 }
8835 if (klass == nullptr) {
8836 // The class has not been resolved yet, so the field is also unresolved.
8837 return nullptr;
8838 }
8839 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008840
David Brazdil1ab0fa82018-05-04 11:28:03 +01008841 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008842}
8843
Vladimir Markoe11dd502017-12-08 14:09:45 +00008844ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008845 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008846 Handle<mirror::ClassLoader> class_loader,
8847 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008848 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008849 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008850 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008851 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008852 return resolved;
8853 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008854 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008855 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008856 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008857 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008858 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008859 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008860 }
8861
David Brazdil1ab0fa82018-05-04 11:28:03 +01008862 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008863 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008864 const char* name = dex_file.GetFieldName(field_id);
8865 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008866 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008867 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008868 return resolved;
8869}
8870
Vladimir Markoe11dd502017-12-08 14:09:45 +00008871ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008872 Handle<mirror::DexCache> dex_cache,
8873 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008874 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008875 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008876 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008877 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008878 return resolved;
8879 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008880 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008881 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008882 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008883 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008884 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008885 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008886 }
8887
David Brazdil1ab0fa82018-05-04 11:28:03 +01008888 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8889 if (resolved == nullptr) {
8890 const char* name = dex_file.GetFieldName(field_id);
8891 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008892 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008893 }
8894 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008895}
8896
David Brazdil1ab0fa82018-05-04 11:28:03 +01008897ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8898 ObjPtr<mirror::DexCache> dex_cache,
8899 ObjPtr<mirror::ClassLoader> class_loader,
8900 uint32_t field_idx,
8901 bool is_static) {
8902 ArtField* resolved = nullptr;
8903 Thread* self = is_static ? Thread::Current() : nullptr;
8904 const DexFile& dex_file = *dex_cache->GetDexFile();
8905
8906 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8907 : klass->FindInstanceField(dex_cache, field_idx);
8908
8909 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008910 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008911 const char* name = dex_file.GetFieldName(field_id);
8912 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8913 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8914 : klass->FindInstanceField(name, type);
8915 }
8916
8917 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008918 hiddenapi::ShouldDenyAccessToMember(resolved,
8919 hiddenapi::AccessContext(class_loader, dex_cache),
8920 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008921 resolved = nullptr;
8922 }
8923
8924 if (resolved != nullptr) {
8925 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8926 }
8927
8928 return resolved;
8929}
8930
8931ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8932 ObjPtr<mirror::DexCache> dex_cache,
8933 ObjPtr<mirror::ClassLoader> class_loader,
8934 uint32_t field_idx) {
8935 ArtField* resolved = nullptr;
8936 Thread* self = Thread::Current();
8937 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008938 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008939
8940 const char* name = dex_file.GetFieldName(field_id);
8941 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8942 resolved = mirror::Class::FindField(self, klass, name, type);
8943
8944 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008945 hiddenapi::ShouldDenyAccessToMember(resolved,
8946 hiddenapi::AccessContext(class_loader, dex_cache),
8947 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008948 resolved = nullptr;
8949 }
8950
8951 if (resolved != nullptr) {
8952 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8953 }
8954
8955 return resolved;
8956}
8957
Vladimir Markoaf940202017-12-08 15:01:18 +00008958ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8959 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008960 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008961 Handle<mirror::DexCache> dex_cache,
8962 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008963 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008964 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008965
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008966 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008967 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008968 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008969 }
8970
Narayan Kamath25352fc2016-08-03 12:46:58 +01008971 StackHandleScope<4> hs(self);
8972
8973 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008974 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008975 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008976 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008977 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008978 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008979 DCHECK(self->IsExceptionPending());
8980 return nullptr;
8981 }
8982
8983 // Then resolve the argument types.
8984 //
8985 // TODO: Is there a better way to figure out the number of method arguments
8986 // other than by looking at the shorty ?
8987 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8988
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008989 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008990 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8991 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008992 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008993 DCHECK(self->IsExceptionPending());
8994 return nullptr;
8995 }
8996
8997 DexFileParameterIterator it(dex_file, proto_id);
8998 int32_t i = 0;
8999 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9000 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009001 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009002 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009003 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009004 DCHECK(self->IsExceptionPending());
9005 return nullptr;
9006 }
9007
9008 method_params->Set(i++, param_class.Get());
9009 }
9010
9011 DCHECK(!it.HasNext());
9012
9013 Handle<mirror::MethodType> type = hs.NewHandle(
9014 mirror::MethodType::Create(self, return_type, method_params));
9015 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9016
9017 return type.Get();
9018}
9019
Vladimir Markoaf940202017-12-08 15:01:18 +00009020ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009021 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009022 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009023 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009024 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9025 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009026 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009027}
9028
Vladimir Marko5aead702019-03-27 11:00:36 +00009029ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009030 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009031 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009032 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009033 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009034 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9035 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009036 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009037 bool is_static;
9038 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009039 switch (handle_type) {
9040 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009041 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009042 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009043 is_static = true;
9044 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009045 break;
9046 }
9047 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009048 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009049 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009050 is_static = true;
9051 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009052 break;
9053 }
9054 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009055 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009056 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009057 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009058 num_params = 2;
9059 break;
9060 }
9061 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009062 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009063 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009064 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009065 num_params = 1;
9066 break;
9067 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009068 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009069 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009070 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009071 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009072 case DexFile::MethodHandleType::kInvokeInterface:
9073 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009074 }
9075
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009076 ArtField* target_field =
9077 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9078 if (LIKELY(target_field != nullptr)) {
9079 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9080 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9081 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9082 ThrowIllegalAccessErrorField(referring_class, target_field);
9083 return nullptr;
9084 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009085 if (UNLIKELY(is_put && target_field->IsFinal())) {
9086 ThrowIllegalAccessErrorField(referring_class, target_field);
9087 return nullptr;
9088 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009089 } else {
9090 DCHECK(Thread::Current()->IsExceptionPending());
9091 return nullptr;
9092 }
9093
9094 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009095 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009096 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9097 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009098 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009099 DCHECK(self->IsExceptionPending());
9100 return nullptr;
9101 }
9102
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009103 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009104 Handle<mirror::Class> return_type;
9105 switch (handle_type) {
9106 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009107 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009108 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009109 break;
9110 }
9111 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009112 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009113 break;
9114 }
9115 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009116 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009117 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009118 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009119 break;
9120 }
9121 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009122 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009123 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009124 break;
9125 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009126 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009127 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009128 case DexFile::MethodHandleType::kInvokeConstructor:
9129 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009130 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009131 UNREACHABLE();
9132 }
9133
9134 for (int32_t i = 0; i < num_params; ++i) {
9135 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9136 DCHECK(self->IsExceptionPending());
9137 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009138 }
9139 }
9140
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009141 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009142 DCHECK(self->IsExceptionPending());
9143 return nullptr;
9144 }
9145
9146 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009147 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9148 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009149 DCHECK(self->IsExceptionPending());
9150 return nullptr;
9151 }
Orion Hodson631827d2017-04-10 14:53:47 +01009152
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009153 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9154 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9155}
9156
Vladimir Marko5aead702019-03-27 11:00:36 +00009157ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009158 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009159 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009160 ArtMethod* referrer) {
9161 DexFile::MethodHandleType handle_type =
9162 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9163 mirror::MethodHandle::Kind kind;
9164 uint32_t receiver_count = 0;
9165 ArtMethod* target_method = nullptr;
9166 switch (handle_type) {
9167 case DexFile::MethodHandleType::kStaticPut:
9168 case DexFile::MethodHandleType::kStaticGet:
9169 case DexFile::MethodHandleType::kInstancePut:
9170 case DexFile::MethodHandleType::kInstanceGet:
9171 UNREACHABLE();
9172 case DexFile::MethodHandleType::kInvokeStatic: {
9173 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9174 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009175 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9176 method_handle.field_or_method_idx_,
9177 referrer,
9178 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009179 break;
9180 }
9181 case DexFile::MethodHandleType::kInvokeInstance: {
9182 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9183 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009184 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9185 method_handle.field_or_method_idx_,
9186 referrer,
9187 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009188 break;
9189 }
9190 case DexFile::MethodHandleType::kInvokeConstructor: {
9191 // Constructors are currently implemented as a transform. They
9192 // are special cased later in this method.
9193 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9194 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009195 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9196 method_handle.field_or_method_idx_,
9197 referrer,
9198 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009199 break;
9200 }
9201 case DexFile::MethodHandleType::kInvokeDirect: {
9202 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9203 receiver_count = 1;
9204 StackHandleScope<2> hs(self);
9205 // A constant method handle with type kInvokeDirect can refer to
9206 // a method that is private or to a method in a super class. To
9207 // disambiguate the two options, we resolve the method ignoring
9208 // the invocation type to determine if the method is private. We
9209 // then resolve again specifying the intended invocation type to
9210 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009211 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009212 hs.NewHandle(referrer->GetDexCache()),
9213 hs.NewHandle(referrer->GetClassLoader()));
9214 if (UNLIKELY(target_method == nullptr)) {
9215 break;
9216 }
9217
9218 if (target_method->IsPrivate()) {
9219 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009220 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9221 method_handle.field_or_method_idx_,
9222 referrer,
9223 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009224 } else {
9225 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009226 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9227 method_handle.field_or_method_idx_,
9228 referrer,
9229 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009230 if (UNLIKELY(target_method == nullptr)) {
9231 break;
9232 }
9233 // Find the method specified in the parent in referring class
9234 // so invoke-super invokes the method in the parent of the
9235 // referrer.
9236 target_method =
9237 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9238 kRuntimePointerSize);
9239 }
9240 break;
9241 }
9242 case DexFile::MethodHandleType::kInvokeInterface: {
9243 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9244 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009245 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9246 method_handle.field_or_method_idx_,
9247 referrer,
9248 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009249 break;
9250 }
Orion Hodson631827d2017-04-10 14:53:47 +01009251 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009252
9253 if (UNLIKELY(target_method == nullptr)) {
9254 DCHECK(Thread::Current()->IsExceptionPending());
9255 return nullptr;
9256 }
9257
9258 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9259 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9260 uint32_t access_flags = target_method->GetAccessFlags();
9261 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9262 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9263 return nullptr;
9264 }
9265
9266 // Calculate the number of parameters from the method shorty. We add the
9267 // receiver count (0 or 1) and deduct one for the return value.
9268 uint32_t shorty_length;
9269 target_method->GetShorty(&shorty_length);
9270 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9271
Orion Hodsonecd58562018-09-24 11:27:33 +01009272 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009273 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009274 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9275 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9276 if (method_params.Get() == nullptr) {
9277 DCHECK(self->IsExceptionPending());
9278 return nullptr;
9279 }
9280
Orion Hodsonecd58562018-09-24 11:27:33 +01009281 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009282 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009283 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009284 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009285 // Insert receiver. Use the class identified in the method handle rather than the declaring
9286 // class of the resolved method which may be super class or default interface method
9287 // (b/115964401).
9288 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9289 // receiver_class should have been resolved when resolving the target method.
9290 DCHECK(receiver_class != nullptr);
9291 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009292 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009293
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009294 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009295 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009296 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009297 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009298 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009299 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009300 if (nullptr == klass) {
9301 DCHECK(self->IsExceptionPending());
9302 return nullptr;
9303 }
9304 method_params->Set(index++, klass);
9305 it.Next();
9306 }
9307
Orion Hodsonecd58562018-09-24 11:27:33 +01009308 Handle<mirror::Class> return_type =
9309 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009310 if (UNLIKELY(return_type.IsNull())) {
9311 DCHECK(self->IsExceptionPending());
9312 return nullptr;
9313 }
9314
9315 Handle<mirror::MethodType>
9316 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9317 if (UNLIKELY(method_type.IsNull())) {
9318 DCHECK(self->IsExceptionPending());
9319 return nullptr;
9320 }
9321
9322 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9323 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9324 Handle<mirror::MethodHandlesLookup> lookup =
9325 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9326 return lookup->FindConstructor(self, constructor_class, method_type);
9327 }
9328
9329 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9330 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9331}
9332
Vladimir Markoaf940202017-12-08 15:01:18 +00009333ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9334 uint32_t method_handle_idx,
9335 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009336 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009337 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009338 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009339 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9340 case DexFile::MethodHandleType::kStaticPut:
9341 case DexFile::MethodHandleType::kStaticGet:
9342 case DexFile::MethodHandleType::kInstancePut:
9343 case DexFile::MethodHandleType::kInstanceGet:
9344 return ResolveMethodHandleForField(self, method_handle, referrer);
9345 case DexFile::MethodHandleType::kInvokeStatic:
9346 case DexFile::MethodHandleType::kInvokeInstance:
9347 case DexFile::MethodHandleType::kInvokeConstructor:
9348 case DexFile::MethodHandleType::kInvokeDirect:
9349 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009350 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009351 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009352}
9353
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009354bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9355 return (entry_point == GetQuickResolutionStub()) ||
9356 (quick_resolution_trampoline_ == entry_point);
9357}
9358
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009359bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9360 return (entry_point == GetQuickToInterpreterBridge()) ||
9361 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9362}
9363
9364bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9365 return (entry_point == GetQuickGenericJniStub()) ||
9366 (quick_generic_jni_trampoline_ == entry_point);
9367}
9368
David Sehra49e0532017-08-25 08:05:29 -07009369bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009370 return entry_point == GetJniDlsymLookupStub() ||
9371 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009372}
9373
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009374const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9375 return GetQuickGenericJniStub();
9376}
9377
Mathieu Chartiere401d142015-04-22 13:56:20 -07009378void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009379 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009380 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9381 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009382 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009383 }
9384}
9385
Alex Lightdb01a092017-04-03 15:39:55 -07009386void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9387 DCHECK(method->IsObsolete());
9388 // We cannot mess with the entrypoints of native methods because they are used to determine how
9389 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9390 if (!method->IsNative()) {
9391 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9392 }
9393}
9394
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009395void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009396 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009397 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009398 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9399 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009400 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9401 os << "Dumping registered class loaders\n";
9402 size_t class_loader_index = 0;
9403 for (const ClassLoaderData& class_loader : class_loaders_) {
9404 ObjPtr<mirror::ClassLoader> loader =
9405 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9406 if (loader != nullptr) {
9407 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9408 bool saw_one_dex_file = false;
9409 for (const DexCacheData& dex_cache : dex_caches_) {
9410 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9411 if (saw_one_dex_file) {
9412 os << ":";
9413 }
9414 saw_one_dex_file = true;
9415 os << dex_cache.dex_file->GetLocation();
9416 }
9417 }
9418 os << "]";
9419 bool found_parent = false;
9420 if (loader->GetParent() != nullptr) {
9421 size_t parent_index = 0;
9422 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9423 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9424 soa.Self()->DecodeJObject(class_loader2.weak_root));
9425 if (loader2 == loader->GetParent()) {
9426 os << ", parent #" << parent_index;
9427 found_parent = true;
9428 break;
9429 }
9430 parent_index++;
9431 }
9432 if (!found_parent) {
9433 os << ", unregistered parent of type "
9434 << loader->GetParent()->GetClass()->PrettyDescriptor();
9435 }
9436 } else {
9437 os << ", no parent";
9438 }
9439 os << "\n";
9440 }
9441 }
9442 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009443 Runtime* runtime = Runtime::Current();
9444 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9445 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009446}
9447
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009448class CountClassesVisitor : public ClassLoaderVisitor {
9449 public:
9450 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9451
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009452 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009453 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009454 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009455 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009456 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9457 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009458 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009459 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009460
9461 size_t num_zygote_classes;
9462 size_t num_non_zygote_classes;
9463};
9464
9465size_t ClassLinker::NumZygoteClasses() const {
9466 CountClassesVisitor visitor;
9467 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009468 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009469}
9470
9471size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009472 CountClassesVisitor visitor;
9473 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009474 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009475}
9476
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009477size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009478 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009479 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009480 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009481}
9482
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009483pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009484 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009485}
9486
9487pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009488 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009489}
9490
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009491void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009492 DCHECK(!init_done_);
9493
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009494 DCHECK(klass != nullptr);
9495 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009496
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009497 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009498 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009499 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9500 int32_t index = static_cast<int32_t>(class_root);
9501 DCHECK(class_roots->Get(index) == nullptr);
9502 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009503}
9504
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009505ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9506 Thread* self,
9507 const std::vector<const DexFile*>& dex_files,
9508 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009509 Handle<mirror::ClassLoader> parent_loader,
9510 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009511
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009512 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009513
Mathieu Chartierc7853442015-03-27 14:35:38 -07009514 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009515 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009516
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009517 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009518 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009519 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009520 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009521 mirror::ObjectArray<mirror::Object>::Alloc(self,
9522 dex_elements_class.Get(),
9523 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009524 Handle<mirror::Class> h_dex_element_class =
9525 hs.NewHandle(dex_elements_class->GetComponentType());
9526
Mathieu Chartierc7853442015-03-27 14:35:38 -07009527 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009528 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009529 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009530
Andreas Gampe08883de2016-11-08 13:20:52 -08009531 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009532 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009533
Andreas Gampe08883de2016-11-08 13:20:52 -08009534 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009535 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009536
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009537 // Fill the elements array.
9538 int32_t index = 0;
9539 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009540 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009541
Calin Juravle7865ac72017-06-28 11:03:12 -07009542 // CreateWellKnownClassLoader is only used by gtests and compiler.
9543 // 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 -07009544 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9545 self,
9546 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009547 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009548 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009549
Mathieu Chartier3738e982017-05-12 16:07:28 -07009550 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9551 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009552 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009553 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009554 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009555 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009556
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009557 Handle<mirror::String> h_file_name = hs2.NewHandle(
9558 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009559 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009560 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9561
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009562 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009563 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009564 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009565
9566 h_dex_elements->Set(index, h_element.Get());
9567 index++;
9568 }
9569 DCHECK_EQ(index, h_dex_elements->GetLength());
9570
9571 // Create DexPathList.
9572 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009573 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009574 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009575 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009576 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009577 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9578 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9579 // elements.
9580 {
9581 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9582 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9583 DCHECK(native_lib_dirs != nullptr);
9584 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9585 DCHECK(list_class != nullptr);
9586 {
9587 StackHandleScope<1> h_list_scope(self);
9588 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9589 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9590 DCHECK(list_init);
9591 list_class = h_list_class.Get();
9592 }
9593 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9594 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9595 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9596 // normally never null), as long as one does not try to add elements, this will still
9597 // work.
9598 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9599 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009600
Calin Juravle7865ac72017-06-28 11:03:12 -07009601 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009602 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9603 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009604 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009605 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009606 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009607 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009608 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009609 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009610
9611 // Make a pretend boot-classpath.
9612 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009613 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009614 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009615 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009616 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009617 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009618 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009619 if (parent_loader.Get() == nullptr) {
9620 ScopedObjectAccessUnchecked soa(self);
9621 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9622 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9623 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9624 } else {
9625 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9626 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009627
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009628 ArtField* shared_libraries_field =
9629 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9630 DCHECK(shared_libraries_field != nullptr);
9631 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9632
9633 return h_class_loader.Get();
9634}
9635
9636jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9637 const std::vector<const DexFile*>& dex_files,
9638 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009639 jobject parent_loader,
9640 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009641 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9642 WellKnownClasses::dalvik_system_PathClassLoader) ||
9643 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009644 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9645 self->GetJniEnv()->IsSameObject(loader_class,
9646 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009647
9648 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9649 // We could move the jobject to the callers, but all call-sites do this...
9650 ScopedObjectAccessUnchecked soa(self);
9651
9652 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009653 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009654
9655 Handle<mirror::Class> h_loader_class =
9656 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009657 Handle<mirror::ClassLoader> h_parent =
9658 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9659 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9660 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009661
9662 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9663 self,
9664 dex_files,
9665 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009666 h_parent,
9667 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009668
9669 // Make it a global ref and return.
9670 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009671 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009672 return soa.Env()->NewGlobalRef(local_ref.get());
9673}
9674
Calin Juravle7865ac72017-06-28 11:03:12 -07009675jobject ClassLinker::CreatePathClassLoader(Thread* self,
9676 const std::vector<const DexFile*>& dex_files) {
9677 return CreateWellKnownClassLoader(self,
9678 dex_files,
9679 WellKnownClasses::dalvik_system_PathClassLoader,
9680 nullptr);
9681}
9682
Andreas Gampe8ac75952015-06-02 21:01:45 -07009683void ClassLinker::DropFindArrayClassCache() {
9684 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9685 find_array_class_cache_next_victim_ = 0;
9686}
9687
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009688void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009689 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009690 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009691 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009692 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9693 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009694 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009695 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009696 }
9697 }
9698}
9699
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009700void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9701 for (const ClassLoaderData& data : class_loaders_) {
9702 LinearAlloc* alloc = data.allocator;
9703 if (alloc != nullptr && !visitor->Visit(alloc)) {
9704 break;
9705 }
9706 }
9707}
9708
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009709void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9710 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009711 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009712 Thread* const self = Thread::Current();
9713 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009714 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009715 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009716 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009717 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9718 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009719 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009720 }
9721}
9722
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009723void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009724 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009725 std::vector<ClassLoaderData> to_delete;
9726 // Do the delete outside the lock to avoid lock violation in jit code cache.
9727 {
9728 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9729 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9730 const ClassLoaderData& data = *it;
9731 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009732 ObjPtr<mirror::ClassLoader> class_loader =
9733 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009734 if (class_loader != nullptr) {
9735 ++it;
9736 } else {
9737 VLOG(class_linker) << "Freeing class loader";
9738 to_delete.push_back(data);
9739 it = class_loaders_.erase(it);
9740 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009741 }
9742 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009743 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009744 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009745 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009746 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009747}
9748
Mathieu Chartier65975772016-08-05 10:46:36 -07009749class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9750 public:
9751 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9752 : method_(method),
9753 pointer_size_(pointer_size) {}
9754
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009755 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009756 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9757 holder_ = klass;
9758 }
9759 // Return false to stop searching if holder_ is not null.
9760 return holder_ == nullptr;
9761 }
9762
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009763 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009764 const ArtMethod* const method_;
9765 const PointerSize pointer_size_;
9766};
9767
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009768ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009769 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9770 CHECK(method->IsCopied());
9771 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9772 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009773 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009774}
9775
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009776ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9777 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009778 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009779 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009780 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009781}
9782
Roland Levillain0e840272018-08-23 19:55:30 +01009783// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009784template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009785 uint32_t method_idx,
9786 Handle<mirror::DexCache> dex_cache,
9787 Handle<mirror::ClassLoader> class_loader,
9788 ArtMethod* referrer,
9789 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009790template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009791 uint32_t method_idx,
9792 Handle<mirror::DexCache> dex_cache,
9793 Handle<mirror::ClassLoader> class_loader,
9794 ArtMethod* referrer,
9795 InvokeType type);
9796
Roland Levillain0e840272018-08-23 19:55:30 +01009797// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009798template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009799 Thread* self,
9800 ObjPtr<mirror::Class> java_lang_Class,
9801 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009802template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009803 Thread* self,
9804 ObjPtr<mirror::Class> java_lang_Class,
9805 uint32_t class_size);
9806
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009807} // namespace art