blob: de4db6733719f132064d769fbdb39dc6a07164f4 [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"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070072#include "entrypoints/entrypoint_utils.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"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700116#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700117#include "mirror/object_array-inl.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700118#include "mirror/object_reference.h"
119#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800120#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700121#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800122#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700123#include "mirror/string-inl.h"
Andreas Gampe501c3b02019-04-17 21:54:27 +0000124#include "mirror/throwable.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100125#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700126#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700127#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700128#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700129#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700130#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700131#include "oat_file_assistant.h"
132#include "oat_file_manager.h"
133#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700134#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700135#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800136#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700137#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700138#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700139#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700140#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100141#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700142#include "verifier/class_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700143#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700144
145namespace art {
146
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800147using android::base::StringPrintf;
148
Mathieu Chartierc7853442015-03-27 14:35:38 -0700149static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700150static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700151
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700152static void ThrowNoClassDefFoundError(const char* fmt, ...)
153 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700154 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700155static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700156 va_list args;
157 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800158 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000159 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800160 va_end(args);
161}
162
Andreas Gampe99babb62015-11-02 16:20:00 -0800163static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700164 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700165 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700166 StackHandleScope<1> hs(self);
167 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700168 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700169 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700170
171 if (exception_class == nullptr) {
172 // No exc class ~ no <init>-with-string.
173 CHECK(self->IsExceptionPending());
174 self->ClearException();
175 return false;
176 }
177
Vladimir Markoba118822017-06-12 15:41:56 +0100178 ArtMethod* exception_init_method = exception_class->FindConstructor(
179 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700180 return exception_init_method != nullptr;
181}
182
Vladimir Markobb206de2019-03-28 10:30:32 +0000183static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700184 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700185 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
186 if (ext == nullptr) {
187 return nullptr;
188 } else {
189 return ext->GetVerifyError();
190 }
191}
192
193// Helper for ThrowEarlierClassFailure. Throws the stored error.
194static void HandleEarlierVerifyError(Thread* self,
195 ClassLinker* class_linker,
196 ObjPtr<mirror::Class> c)
197 REQUIRES_SHARED(Locks::mutator_lock_) {
198 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800199 DCHECK(obj != nullptr);
200 self->AssertNoPendingException();
201 if (obj->IsClass()) {
202 // Previous error has been stored as class. Create a new exception of that type.
203
204 // It's possible the exception doesn't have a <init>(String).
205 std::string temp;
206 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
207
208 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700209 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800210 } else {
211 self->ThrowNewException(descriptor, nullptr);
212 }
213 } else {
214 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100215 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700216 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800217 CHECK(throwable_class->IsAssignableFrom(error_class));
218 self->SetException(obj->AsThrowable());
219 }
220 self->AssertPendingException();
221}
222
Andreas Gampe5b20b352018-10-11 19:03:20 -0700223// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
224// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
225// before.
226template <bool kNeedsVerified = false>
227static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
228 REQUIRES_SHARED(Locks::mutator_lock_) {
229 if (kNeedsVerified) {
230 // To not fail access-flags access checks, push a minimal state.
231 mirror::Class::SetStatus(klass, ClassStatus::kVerified, Thread::Current());
232 }
233 if (!klass->WasVerificationAttempted()) {
234 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
235 klass->SetVerificationAttempted();
236 }
237}
238
Vladimir Markobf121912019-06-04 13:49:05 +0100239// Callback responsible for making a batch of classes visibly initialized
240// after all threads have called it from a checkpoint, ensuring visibility.
241class ClassLinker::VisiblyInitializedCallback final
242 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
243 public:
244 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
245 : class_linker_(class_linker),
246 num_classes_(0u),
247 thread_visibility_counter_(0),
248 barriers_() {
249 std::fill_n(classes_, kMaxClasses, nullptr);
250 }
251
252 bool IsEmpty() const {
253 DCHECK_LE(num_classes_, kMaxClasses);
254 return num_classes_ == 0u;
255 }
256
257 bool IsFull() const {
258 DCHECK_LE(num_classes_, kMaxClasses);
259 return num_classes_ == kMaxClasses;
260 }
261
262 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
263 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
264 DCHECK(!IsFull());
265 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
266 ++num_classes_;
267 }
268
269 void AddBarrier(Barrier* barrier) {
270 barriers_.push_front(barrier);
271 }
272
273 std::forward_list<Barrier*> GetAndClearBarriers() {
274 std::forward_list<Barrier*> result;
275 result.swap(barriers_);
276 result.reverse(); // Return barriers in insertion order.
277 return result;
278 }
279
280 void MakeVisible(Thread* self) {
281 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
282 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
283 AdjustThreadVisibilityCounter(self, count);
284 }
285
286 void Run(Thread* self) override {
287 self->ClearMakeVisiblyInitializedCounter();
288 AdjustThreadVisibilityCounter(self, -1);
289 }
290
291 private:
292 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
293 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
294 if (old + adjustment == 0) {
295 // All threads passed the checkpoint. Mark classes as visibly initialized.
296 {
297 ScopedObjectAccess soa(self);
298 StackHandleScope<1u> hs(self);
299 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
300 JavaVMExt* vm = self->GetJniEnv()->GetVm();
301 for (size_t i = 0, num = num_classes_; i != num; ++i) {
302 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
303 vm->DeleteWeakGlobalRef(self, classes_[i]);
304 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100305 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
306 }
307 }
308 num_classes_ = 0u;
309 }
310 class_linker_->VisiblyInitializedCallbackDone(self, this);
311 }
312 }
313
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100314 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100315
316 ClassLinker* const class_linker_;
317 size_t num_classes_;
318 jweak classes_[kMaxClasses];
319
320 // The thread visibility counter starts at 0 and it is incremented by the number of
321 // threads that need to run this callback (by the thread that request the callback
322 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
323 // whether after the increment or after a decrement, we know that `Run()` was executed
324 // for all threads and therefore we can mark the classes as visibly initialized.
325 std::atomic<ssize_t> thread_visibility_counter_;
326
327 // List of barries to `Pass()` for threads that wait for the callback to complete.
328 std::forward_list<Barrier*> barriers_;
329};
330
331void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
332 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
333 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
334 }
335 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
336 if (wait) {
337 maybe_barrier.emplace(0);
338 }
339 int wait_count = 0;
340 VisiblyInitializedCallback* callback = nullptr;
341 {
342 MutexLock lock(self, visibly_initialized_callback_lock_);
343 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
344 callback = visibly_initialized_callback_.release();
345 running_visibly_initialized_callbacks_.push_front(*callback);
346 }
347 if (wait) {
348 DCHECK(maybe_barrier.has_value());
349 Barrier* barrier = std::addressof(*maybe_barrier);
350 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
351 cb.AddBarrier(barrier);
352 ++wait_count;
353 }
354 }
355 }
356 if (callback != nullptr) {
357 callback->MakeVisible(self);
358 }
359 if (wait_count != 0) {
360 DCHECK(maybe_barrier.has_value());
361 maybe_barrier->Increment(self, wait_count);
362 }
363}
364
365void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
366 VisiblyInitializedCallback* callback) {
367 MutexLock lock(self, visibly_initialized_callback_lock_);
368 // Pass the barriers if requested.
369 for (Barrier* barrier : callback->GetAndClearBarriers()) {
370 barrier->Pass(self);
371 }
372 // Remove the callback from the list of running callbacks.
373 auto before = running_visibly_initialized_callbacks_.before_begin();
374 auto it = running_visibly_initialized_callbacks_.begin();
375 DCHECK(it != running_visibly_initialized_callbacks_.end());
376 while (std::addressof(*it) != callback) {
377 before = it;
378 ++it;
379 DCHECK(it != running_visibly_initialized_callbacks_.end());
380 }
381 running_visibly_initialized_callbacks_.erase_after(before);
382 // Reuse or destroy the callback object.
383 if (visibly_initialized_callback_ == nullptr) {
384 visibly_initialized_callback_.reset(callback);
385 } else {
386 delete callback;
387 }
388}
389
Alex Lightfb119572019-09-18 15:04:53 -0700390void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
391 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
392 if (cb != nullptr) {
393 cb->MakeVisible(self);
394 }
395 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
396 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
397}
398
Vladimir Markobf121912019-06-04 13:49:05 +0100399ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
400 Thread* self, Handle<mirror::Class> klass) {
401 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
402 // Thanks to the x86 memory model, we do not need any memory fences and
403 // we can immediately mark the class as visibly initialized.
404 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
405 return nullptr;
406 }
407 if (Runtime::Current()->IsActiveTransaction()) {
408 // Transactions are single-threaded, so we can mark the class as visibly intialized.
409 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
410 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
411 return nullptr;
412 }
413 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
414 MutexLock lock(self, visibly_initialized_callback_lock_);
415 if (visibly_initialized_callback_ == nullptr) {
416 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
417 }
418 DCHECK(!visibly_initialized_callback_->IsFull());
419 visibly_initialized_callback_->AddClass(self, klass.Get());
420
421 if (visibly_initialized_callback_->IsFull()) {
422 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
423 running_visibly_initialized_callbacks_.push_front(*callback);
424 return callback;
425 } else {
426 return nullptr;
427 }
428}
429
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800430void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
431 bool wrap_in_no_class_def,
432 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700433 // The class failed to initialize on a previous attempt, so we want to throw
434 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
435 // failed in verification, in which case v2 5.4.1 says we need to re-throw
436 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800437 Runtime* const runtime = Runtime::Current();
438 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700439 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000440 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
441 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800442 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700443 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800444 } else {
445 extra = verify_error->AsThrowable()->Dump();
446 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700447 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800448 if (log) {
449 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
450 << ": " << extra;
451 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700452 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700453
David Sehr709b0702016-10-13 09:12:37 -0700454 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800455 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800456 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700457 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700458 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000459 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700460 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000461 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
462 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800463 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800464 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800465 }
Alex Lightd6251582016-10-31 11:12:30 -0700466 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
467 // might have meant to go down the earlier if statement with the original error but it got
468 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000469 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800470 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
471 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
472 // exception will be a cause.
473 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700474 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700475 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700476 }
477}
478
Brian Carlstromb23eab12014-10-08 17:55:21 -0700479static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700480 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700481 if (VLOG_IS_ON(class_linker)) {
482 std::string temp;
483 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000484 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700485 }
486}
487
488static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700489 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700490 Thread* self = Thread::Current();
491 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700492
493 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700494 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700495
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800496 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
497 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
498 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800499 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800500 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
501 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
502 // could have caused the error.
503 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
504 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
505 << " failed initialization: "
506 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800507 }
508
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700509 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700510 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
511 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700512
Elliott Hughesa4f94742012-05-29 16:28:38 -0700513 // We only wrap non-Error exceptions; an Error can just be used as-is.
514 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000515 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700516 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700517 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700518}
519
Fred Shih381e4ca2014-08-25 17:24:27 -0700520// Gap between two fields in object layout.
521struct FieldGap {
522 uint32_t start_offset; // The offset from the start of the object.
523 uint32_t size; // The gap size of 1, 2, or 4 bytes.
524};
525struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800526 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700527 }
528 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
529 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800530 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700531 // Note that the priority queue returns the largest element, so operator()
532 // should return true if lhs is less than rhs.
533 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700534 }
535};
Andreas Gampec55bb392018-09-21 00:02:02 +0000536using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700537
538// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800539static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700540 DCHECK(gaps != nullptr);
541
542 uint32_t current_offset = gap_start;
543 while (current_offset != gap_end) {
544 size_t remaining = gap_end - current_offset;
545 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
546 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
547 current_offset += sizeof(uint32_t);
548 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
549 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
550 current_offset += sizeof(uint16_t);
551 } else {
552 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
553 current_offset += sizeof(uint8_t);
554 }
555 DCHECK_LE(current_offset, gap_end) << "Overran gap";
556 }
557}
558// Shuffle fields forward, making use of gaps whenever possible.
559template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000560static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700561 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700562 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700563 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700564 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700565 DCHECK(current_field_idx != nullptr);
566 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700567 DCHECK(gaps != nullptr);
568 DCHECK(field_offset != nullptr);
569
570 DCHECK(IsPowerOfTwo(n));
571 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700572 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700573 Primitive::Type type = field->GetTypeAsPrimitiveType();
574 if (Primitive::ComponentSize(type) < n) {
575 break;
576 }
577 if (!IsAligned<n>(field_offset->Uint32Value())) {
578 MemberOffset old_offset = *field_offset;
579 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
580 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
581 }
David Sehr709b0702016-10-13 09:12:37 -0700582 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700583 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700584 if (!gaps->empty() && gaps->top().size >= n) {
585 FieldGap gap = gaps->top();
586 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100587 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700588 field->SetOffset(MemberOffset(gap.start_offset));
589 if (gap.size > n) {
590 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
591 }
592 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100593 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700594 field->SetOffset(*field_offset);
595 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
596 }
597 ++(*current_field_idx);
598 }
599}
600
Andreas Gampe87658f32019-04-18 18:39:02 +0000601ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700602 : boot_class_table_(new ClassTable()),
603 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800604 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800605 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700606 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000607 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700608 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000609 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Ian Rogers98379392014-02-24 16:53:16 -0800610 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800611 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100612 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800613 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700614 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100615 visibly_initialized_callback_lock_("visibly initialized callback lock"),
616 visibly_initialized_callback_(nullptr),
Andreas Gampe7dface32017-07-25 21:32:59 -0700617 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
618 // For CHA disabled during Aot, see b/34193647.
619
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700620 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700621 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
622 "Array cache size wrong.");
623 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700624}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700625
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800626void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700627 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800628 if (c2 == nullptr) {
629 LOG(FATAL) << "Could not find class " << descriptor;
630 UNREACHABLE();
631 }
632 if (c1.Get() != c2) {
633 std::ostringstream os1, os2;
634 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
635 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
636 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
637 << ". This is most likely the result of a broken build. Make sure that "
638 << "libcore and art projects match.\n\n"
639 << os1.str() << "\n\n" << os2.str();
640 UNREACHABLE();
641 }
642}
643
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800644bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
645 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800646 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700647
Mathieu Chartiere401d142015-04-22 13:56:20 -0700648 Thread* const self = Thread::Current();
649 Runtime* const runtime = Runtime::Current();
650 gc::Heap* const heap = runtime->GetHeap();
651
Jeff Haodcdc85b2015-12-04 14:06:18 -0800652 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700653 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700654
Mathieu Chartiere401d142015-04-22 13:56:20 -0700655 // Use the pointer size from the runtime since we are probably creating the image.
656 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
657
Elliott Hughes30646832011-10-13 16:59:46 -0700658 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700659 // 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 -0800660 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700661 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700662 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700663 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
664 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000665 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100666 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800667 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100668 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700669 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700670 if (kUseBakerReadBarrier) {
671 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800672 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700673 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700674 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800675 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700676 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700677
Elliott Hughes418d20f2011-09-22 14:00:39 -0700678 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700679 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700680 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700681 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700682 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700683
Ian Rogers23435d02012-09-24 11:23:12 -0700684 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700685 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700686 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800687 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700688 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700689 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000690 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700691
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700692 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800693 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
694 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100695 runtime->SetSentinel(heap->AllocNonMovableObject(self,
696 java_lang_Object.Get(),
697 java_lang_Object->GetObjectSize(),
698 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700699
Igor Murashkin86083f72017-10-27 10:59:04 -0700700 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000701 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700702 // It might seem the lock here is unnecessary, however all the SubtypeCheck
703 // functions are annotated to require locks all the way down.
704 //
705 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
706 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000707 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
708 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700709 }
710
Ian Rogers23435d02012-09-24 11:23:12 -0700711 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700712 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700713 AllocClass(self, java_lang_Class.Get(),
714 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700715 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700716
Roland Levillain0e840272018-08-23 19:55:30 +0100717 // Setup java.lang.String.
718 //
719 // We make this class non-movable for the unlikely case where it were to be
720 // moved by a sticky-bit (minor) collection when using the Generational
721 // Concurrent Copying (CC) collector, potentially creating a stale reference
722 // in the `klass_` field of one of its instances allocated in the Large-Object
723 // Space (LOS) -- see the comment about the dirty card scanning logic in
724 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700725 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700726 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100727 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700728 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000729 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400730
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700731 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700732 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700733 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700734 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000735 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700736
Ian Rogers23435d02012-09-24 11:23:12 -0700737 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700738 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100739 mirror::ObjectArray<mirror::Class>::Alloc(self,
740 object_array_class.Get(),
741 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700742 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100743 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
744 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
745 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
746 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100747 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
748 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700749
Mathieu Chartier6beced42016-11-15 15:51:31 -0800750 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
751 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
752
Vladimir Marko02610552018-06-04 14:38:00 +0100753 // Create array interface entries to populate once we can load system classes.
754 object_array_class->SetIfTable(AllocIfTable(self, 2));
755 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
756
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700757 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100758 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
759 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
760 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
761 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
762 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
763 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
764 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
765 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
766 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700767
Vladimir Marko70e2a762019-07-12 16:49:00 +0100768 // Allocate the primitive array classes. We need only the native pointer
769 // array at this point (int[] or long[], depending on architecture) but
770 // we shall perform the same setup steps for all primitive array classes.
771 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
772 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
773 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
774 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
775 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
776 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
777 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
778 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700779
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700780 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700781
Ian Rogers52813c92012-10-11 11:50:38 -0700782 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700783 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700784 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100785 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100786 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700787 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000788 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700789
Alex Lightd6251582016-10-31 11:12:30 -0700790
791 // Setup dalvik.system.ClassExt
792 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
793 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100794 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000795 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700796
Mathieu Chartier66f19252012-09-18 08:57:04 -0700797 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700798 Handle<mirror::Class> object_array_string(hs.NewHandle(
799 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700800 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700801 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100802 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700803
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000804 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700805 // Create runtime resolution and imt conflict methods.
806 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000807 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
808 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700809
Ian Rogers23435d02012-09-24 11:23:12 -0700810 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
811 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
812 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800813 if (boot_class_path.empty()) {
814 *error_msg = "Boot classpath is empty.";
815 return false;
816 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800817 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800818 if (dex_file.get() == nullptr) {
819 *error_msg = "Null dex file.";
820 return false;
821 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700822 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800823 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700824 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700825
826 // now we can use FindSystemClass
827
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700828 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
829 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700830 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800831 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700832 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700833 quick_resolution_trampoline_ = GetQuickResolutionStub();
834 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
835 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700836 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700837
Alex Lightd6251582016-10-31 11:12:30 -0700838 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000839 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800840 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700841 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000842 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800843 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000844 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800845 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700846 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000847 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700848 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
849 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700850
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800851 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
852 // in class_table_.
853 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700854
Vladimir Marko70e2a762019-07-12 16:49:00 +0100855 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
856 // arrays - can't be done until Object has a vtable and component classes are loaded.
857 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
858 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
859 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
860 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
861 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
862 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
863 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
864 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
865 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
866 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
867 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700868
Ian Rogers23435d02012-09-24 11:23:12 -0700869 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700870 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800871 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700872 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800873 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700874 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
875 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100876 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
877 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700878
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700879 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
880 // suspension.
881 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000882 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700883 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000884 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700885 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000886 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700887 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000888 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700889
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700890 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100891 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700892
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800893 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700894
Ian Rogers23435d02012-09-24 11:23:12 -0700895 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100896 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
897 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700898
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700899 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100900 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700901 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100902 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700903
904 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700905 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
906 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100907 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700908
909 // Create java.lang.reflect.Constructor.class root and array root.
910 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
911 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100912 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700913 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
914 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100915 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700916
917 // Create java.lang.reflect.Method.class root and array root.
918 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
919 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100920 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700921 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
922 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100923 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700924
Orion Hodson005ac512017-10-24 15:43:43 +0100925 // Create java.lang.invoke.CallSite.class root
926 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
927 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100928 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100929
Narayan Kamathafa48272016-08-03 12:46:58 +0100930 // Create java.lang.invoke.MethodType.class root
931 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
932 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100933 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100934
935 // Create java.lang.invoke.MethodHandleImpl.class root
936 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
937 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100938 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100939 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100940
Orion Hodsonc069a302017-01-18 09:23:12 +0000941 // Create java.lang.invoke.MethodHandles.Lookup.class root
942 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
943 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100944 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000945
Orion Hodson005ac512017-10-24 15:43:43 +0100946 // Create java.lang.invoke.VarHandle.class root
947 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000948 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100949 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100950
951 // Create java.lang.invoke.FieldVarHandle.class root
952 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
953 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100954 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100955
956 // Create java.lang.invoke.ArrayElementVarHandle.class root
957 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
958 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100959 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100960
961 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
962 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
963 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100964 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100965
966 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
967 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
968 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100969 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000970
Narayan Kamath000e1882016-10-24 17:14:25 +0100971 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
972 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100973 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100974
Brian Carlstrom1f870082011-08-23 16:02:11 -0700975 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700976 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000977 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800978 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700979 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700980 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
981 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700982 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700983 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700984 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700985 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700986 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700987 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700988 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700989 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700990 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700991 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700992 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700993 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700994
Ian Rogers23435d02012-09-24 11:23:12 -0700995 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700996 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700997 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700998 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100999 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001000
jeffhao8cd6dda2012-02-22 10:15:34 -08001001 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -07001002 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001003 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001004 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -07001005 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001006 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
1007 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
1008 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001009 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001010 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1011 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001012
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001013 // Create conflict tables that depend on the class linker.
1014 runtime->FixupConflictTables();
1015
Ian Rogers98379392014-02-24 16:53:16 -08001016 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001017
Brian Carlstroma004aa92012-02-08 18:05:09 -08001018 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001019
1020 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001021}
1022
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001023static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1024 REQUIRES_SHARED(Locks::mutator_lock_) {
1025 // Find String.<init> -> StringFactory bindings.
1026 ObjPtr<mirror::Class> string_factory_class =
1027 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1028 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001029 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001030 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1031 // Update the primordial thread.
1032 self->InitStringEntryPoints();
1033}
1034
Ian Rogers98379392014-02-24 16:53:16 -08001035void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001036 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001037
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001038 CreateStringInitBindings(self, this);
1039
Brian Carlstrom16192862011-09-12 17:50:06 -07001040 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001041 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001042 // as the types of the field can't be resolved prior to the runtime being
1043 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001044 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001045 Handle<mirror::Class> java_lang_ref_Reference =
1046 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001047 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1048 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001049
Mathieu Chartierc7853442015-03-27 14:35:38 -07001050 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001051 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1052 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001053
Mathieu Chartierc7853442015-03-27 14:35:38 -07001054 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001055 CHECK_STREQ(queue->GetName(), "queue");
1056 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001057
Mathieu Chartierc7853442015-03-27 14:35:38 -07001058 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001059 CHECK_STREQ(queueNext->GetName(), "queueNext");
1060 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001061
Mathieu Chartierc7853442015-03-27 14:35:38 -07001062 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001063 CHECK_STREQ(referent->GetName(), "referent");
1064 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001065
Mathieu Chartierc7853442015-03-27 14:35:38 -07001066 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001067 CHECK_STREQ(zombie->GetName(), "zombie");
1068 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001069
Brian Carlstroma663ea52011-08-19 23:33:41 -07001070 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001071 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001072 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001073 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001074 CHECK(klass != nullptr);
1075 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001076 // note SetClassRoot does additional validation.
1077 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001078 }
1079
Vladimir Marko02610552018-06-04 14:38:00 +01001080 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001081
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001082 // disable the slow paths in FindClass and CreatePrimitiveClass now
1083 // that Object, Class, and Object[] are setup
1084 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001085
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001086 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1087 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1088 // ensure that the class will be initialized.
1089 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001090 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001091
1092 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1093 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1094 // Strange, but don't crash.
1095 LOG(WARNING) << "Could not prepare StackOverflowError.";
1096 self->ClearException();
1097 }
1098 }
1099
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001100 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001101}
1102
Vladimir Markodcfcce42018-06-27 10:00:28 +00001103void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001104 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1105 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001106 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001107 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001108 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -07001109 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001110 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +00001111 } else {
1112 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001113 }
1114 }
1115}
1116
Jeff Haodcdc85b2015-12-04 14:06:18 -08001117struct TrampolineCheckData {
1118 const void* quick_resolution_trampoline;
1119 const void* quick_imt_conflict_trampoline;
1120 const void* quick_generic_jni_trampoline;
1121 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001122 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001123 ArtMethod* m;
1124 bool error;
1125};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001126
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001127bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1128 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001129 CHECK(!init_done_);
1130
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001131 Runtime* const runtime = Runtime::Current();
1132 Thread* const self = Thread::Current();
1133 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001134 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1135 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001136 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1137 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001138 if (!ValidPointerSize(pointer_size_unchecked)) {
1139 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001140 return false;
1141 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001142 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001143 if (!runtime->IsAotCompiler()) {
1144 // Only the Aot compiler supports having an image with a different pointer size than the
1145 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1146 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001147 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001148 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001149 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001150 sizeof(void*));
1151 return false;
1152 }
1153 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001154 DCHECK(!runtime->HasResolutionMethod());
1155 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1156 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1157 runtime->SetImtUnimplementedMethod(
1158 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1159 runtime->SetCalleeSaveMethod(
1160 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1161 CalleeSaveType::kSaveAllCalleeSaves);
1162 runtime->SetCalleeSaveMethod(
1163 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1164 CalleeSaveType::kSaveRefsOnly);
1165 runtime->SetCalleeSaveMethod(
1166 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1167 CalleeSaveType::kSaveRefsAndArgs);
1168 runtime->SetCalleeSaveMethod(
1169 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1170 CalleeSaveType::kSaveEverything);
1171 runtime->SetCalleeSaveMethod(
1172 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1173 CalleeSaveType::kSaveEverythingForClinit);
1174 runtime->SetCalleeSaveMethod(
1175 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1176 CalleeSaveType::kSaveEverythingForSuspendCheck);
1177
Jeff Haodcdc85b2015-12-04 14:06:18 -08001178 std::vector<const OatFile*> oat_files =
1179 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1180 DCHECK(!oat_files.empty());
1181 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001182 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1183 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1184 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1185 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1186 if (kIsDebugBuild) {
1187 // Check that the other images use the same trampoline.
1188 for (size_t i = 1; i < oat_files.size(); ++i) {
1189 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1190 const void* ith_quick_resolution_trampoline =
1191 ith_oat_header.GetQuickResolutionTrampoline();
1192 const void* ith_quick_imt_conflict_trampoline =
1193 ith_oat_header.GetQuickImtConflictTrampoline();
1194 const void* ith_quick_generic_jni_trampoline =
1195 ith_oat_header.GetQuickGenericJniTrampoline();
1196 const void* ith_quick_to_interpreter_bridge_trampoline =
1197 ith_oat_header.GetQuickToInterpreterBridge();
1198 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1199 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1200 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1201 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1202 // Make sure that all methods in this image do not contain those trampolines as
1203 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1204 TrampolineCheckData data;
1205 data.error = false;
1206 data.pointer_size = GetImagePointerSize();
1207 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1208 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1209 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1210 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1211 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001212 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1213 if (obj->IsClass()) {
1214 ObjPtr<mirror::Class> klass = obj->AsClass();
1215 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1216 const void* entrypoint =
1217 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1218 if (entrypoint == data.quick_resolution_trampoline ||
1219 entrypoint == data.quick_imt_conflict_trampoline ||
1220 entrypoint == data.quick_generic_jni_trampoline ||
1221 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1222 data.m = &m;
1223 data.error = true;
1224 return;
1225 }
1226 }
1227 }
1228 };
1229 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001230 if (data.error) {
1231 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001232 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001233 *error_msg = "Found an ArtMethod with a bad entrypoint";
1234 return false;
1235 }
1236 }
1237 }
1238 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001239
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001240 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001241 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001242 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001243 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001244
Vladimir Marko024d69f2019-06-13 10:52:32 +01001245 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1246 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1247 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1248 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1249 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1250 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001251
Vladimir Marko4433c432018-12-04 14:57:47 +00001252 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1253 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001254 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001255 // Boot class loader, use a null handle.
1256 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001257 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001258 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001259 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001260 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001261 /*out*/&dex_files,
1262 error_msg)) {
1263 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001264 }
David Brazdil3e8aae02019-03-26 18:48:02 +00001265 // Assert that if absolute boot classpath locations were provided, they were
1266 // assigned to the loaded dex files.
1267 if (kIsDebugBuild && IsAbsoluteLocation(boot_class_path_locations[i])) {
1268 for (const auto& dex_file : dex_files) {
1269 DCHECK_EQ(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1270 boot_class_path_locations[i]);
1271 }
1272 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001273 // Append opened dex files at the end.
1274 boot_dex_files_.insert(boot_dex_files_.end(),
1275 std::make_move_iterator(dex_files.begin()),
1276 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001277 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001278 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1279 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1280 }
Ian Rogers98379392014-02-24 16:53:16 -08001281 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001282
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001283 VLOG(startup) << __FUNCTION__ << " exiting";
1284 return true;
1285}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001286
Vladimir Marko4433c432018-12-04 14:57:47 +00001287void ClassLinker::AddExtraBootDexFiles(
1288 Thread* self,
1289 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1290 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1291 AppendToBootClassPath(self, *dex_file);
1292 boot_dex_files_.push_back(std::move(dex_file));
1293 }
1294}
1295
Jeff Hao5872d7c2016-04-27 11:07:41 -07001296bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001297 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001298 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001299 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1300 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001301}
1302
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001303static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1304 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001305 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001306 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001307 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001308 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001309 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001310 DCHECK(dex_file_field != nullptr);
1311 DCHECK(dex_file_name_field != nullptr);
1312 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001313 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001314 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001315 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001316 // Null dex file means it was probably a jar with no dex files, return a null string.
1317 *out_name = nullptr;
1318 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001319 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001320 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001321 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001322 *out_name = name_object->AsString();
1323 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001324 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001325 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001326}
1327
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001328static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1329 ObjPtr<mirror::ClassLoader> class_loader,
1330 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1331 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001332 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001333 StackHandleScope<1> hs(soa.Self());
1334 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001335 // Get element names. Sets error to true on failure.
1336 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1337 REQUIRES_SHARED(Locks::mutator_lock_) {
1338 if (element == nullptr) {
1339 *error_msg = "Null dex element";
1340 *error = true; // Null element is a critical error.
1341 return false; // Had an error, stop the visit.
1342 }
1343 ObjPtr<mirror::String> name;
1344 if (!GetDexPathListElementName(element, &name)) {
1345 *error_msg = "Invalid dex path list element";
1346 *error = true; // Invalid element, make it a critical error.
1347 return false; // Stop the visit.
1348 }
1349 if (name != nullptr) {
1350 dex_files->push_front(name);
1351 }
1352 return true; // Continue with the next Element.
1353 };
1354 bool error = VisitClassLoaderDexElements(soa,
1355 handle,
1356 add_element_names,
1357 /*defaultReturn=*/ false);
1358 return !error;
1359}
1360
1361static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1362 ObjPtr<mirror::ClassLoader> image_class_loader,
1363 ObjPtr<mirror::ClassLoader> class_loader,
1364 std::string* error_msg)
1365 REQUIRES_SHARED(Locks::mutator_lock_) {
1366 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1367 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1368 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001369 return false;
1370 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001371 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1372 *error_msg = "Hierarchies don't match";
1373 return false;
1374 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1375 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1376 image_class_loader->PrettyTypeOf().c_str(),
1377 class_loader->PrettyTypeOf().c_str());
1378 return false;
1379 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1380 class_loader->GetClass()) {
1381 *error_msg = StringPrintf("Unknown class loader type %s",
1382 class_loader->PrettyTypeOf().c_str());
1383 // Unsupported class loader.
1384 return false;
1385 }
1386 return true;
1387}
1388
1389static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1390 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1391 std::string* error_msg)
1392 REQUIRES_SHARED(Locks::mutator_lock_) {
1393 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1394 std::equal(image_dex_files.begin(),
1395 image_dex_files.end(),
1396 loader_dex_files.begin(),
1397 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1398 REQUIRES_SHARED(Locks::mutator_lock_) {
1399 return lhs->Equals(rhs);
1400 });
1401 if (!equal) {
1402 VLOG(image) << "Image dex files " << image_dex_files.size();
1403 for (ObjPtr<mirror::String> name : image_dex_files) {
1404 VLOG(image) << name->ToModifiedUtf8();
1405 }
1406 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1407 for (ObjPtr<mirror::String> name : loader_dex_files) {
1408 VLOG(image) << name->ToModifiedUtf8();
1409 }
1410 *error_msg = "Mismatch in dex files";
1411 }
1412 return equal;
1413}
1414
1415static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1416 ObjPtr<mirror::ClassLoader> image_class_loader,
1417 ObjPtr<mirror::ClassLoader> class_loader,
1418 bool check_dex_file_names,
1419 std::string* error_msg)
1420 REQUIRES_SHARED(Locks::mutator_lock_) {
1421 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1422 return false;
1423 }
1424
1425 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1426 // No need to check further.
1427 return true;
1428 }
1429
1430 if (check_dex_file_names) {
1431 std::list<ObjPtr<mirror::String>> image_dex_files;
1432 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001433 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001434 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001435
1436 std::list<ObjPtr<mirror::String>> loader_dex_files;
1437 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1438 return false;
1439 }
1440
1441 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1442 return false;
1443 }
1444 }
1445
1446 ArtField* field =
1447 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1448 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1449 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1450 if (shared_libraries_image_loader == nullptr) {
1451 if (shared_libraries_loader != nullptr) {
1452 *error_msg = "Mismatch in shared libraries";
1453 return false;
1454 }
1455 } else if (shared_libraries_loader == nullptr) {
1456 *error_msg = "Mismatch in shared libraries";
1457 return false;
1458 } else {
1459 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1460 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1461 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1462 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1463 if (array1->GetLength() != array2->GetLength()) {
1464 *error_msg = "Mismatch in number of shared libraries";
1465 return false;
1466 }
1467
1468 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1469 // Do a full comparison of the class loaders, including comparing their dex files.
1470 if (!CompareClassLoaders(soa,
1471 array1->Get(i),
1472 array2->Get(i),
1473 /*check_dex_file_names=*/ true,
1474 error_msg)) {
1475 return false;
1476 }
1477 }
1478 }
1479
1480 // Do a full comparison of the class loaders, including comparing their dex files.
1481 if (!CompareClassLoaders(soa,
1482 image_class_loader->GetParent(),
1483 class_loader->GetParent(),
1484 /*check_dex_file_names=*/ true,
1485 error_msg)) {
1486 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001487 }
1488 return true;
1489}
1490
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001491class CHAOnDeleteUpdateClassVisitor {
1492 public:
1493 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1494 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1495 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1496 self_(Thread::Current()) {}
1497
1498 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1499 // This class is going to be unloaded. Tell CHA about it.
1500 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1501 return true;
1502 }
1503 private:
1504 const LinearAlloc* allocator_;
1505 const ClassHierarchyAnalysis* cha_;
1506 const PointerSize pointer_size_;
1507 const Thread* self_;
1508};
1509
Chris Wailes0c61be42018-09-26 17:27:34 -07001510/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001511 * A class used to ensure that all references to strings interned in an AppImage have been
1512 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001513 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001514class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001515 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001516 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1517 const InternTable::UnorderedSet& image_interns)
1518 : space_(space),
1519 image_interns_(image_interns),
1520 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001521
Chris Wailes0c61be42018-09-26 17:27:34 -07001522 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001523 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001524 if (referred_obj != nullptr &&
1525 space_.HasAddress(referred_obj.Ptr()) &&
1526 referred_obj->IsString()) {
1527 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001528 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1529 if (it != image_interns_.end() && it->Read() == referred_str) {
1530 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001531 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001532 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001533 }
1534
Chris Wailes0c61be42018-09-26 17:27:34 -07001535 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001536 mirror::CompressedReference<mirror::Object>* root) const
1537 REQUIRES_SHARED(Locks::mutator_lock_) {
1538 if (!root->IsNull()) {
1539 VisitRoot(root);
1540 }
1541 }
1542
Chris Wailes0c61be42018-09-26 17:27:34 -07001543 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001544 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001545 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001546 }
1547
1548 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001549 void operator()(ObjPtr<mirror::Object> obj,
1550 MemberOffset offset,
1551 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001552 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001553 // References within image or across images don't need a read barrier.
1554 ObjPtr<mirror::Object> referred_obj =
1555 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1556 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001557 }
1558
1559 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1560 ObjPtr<mirror::Reference> ref) const
1561 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001562 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001563 }
1564
Vladimir Marko8e05f092019-06-10 11:10:38 +01001565 size_t GetCount() const {
1566 return count_;
1567 }
1568
1569 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001570 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001571 const InternTable::UnorderedSet& image_interns_;
1572 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001573};
1574
Chris Wailes0c61be42018-09-26 17:27:34 -07001575/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001576 * This function counts references to strings interned in the AppImage.
1577 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001578 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001579size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1580 const InternTable::UnorderedSet& image_interns)
1581 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001582 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1583 const ImageHeader& image_header = space.GetImageHeader();
1584 const uint8_t* target_base = space.GetMemMap()->Begin();
1585 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001586
1587 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1588 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001589
Vladimir Marko8e05f092019-06-10 11:10:38 +01001590 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001591 bitmap->VisitMarkedRange(objects_begin,
1592 objects_end,
1593 [&space, &visitor](mirror::Object* obj)
1594 REQUIRES_SHARED(Locks::mutator_lock_) {
1595 if (space.HasAddress(obj)) {
1596 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001597 obj->VisitReferences</* kVisitNativeRoots= */ true,
1598 kVerifyNone,
1599 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001600 } else {
1601 // Don't visit native roots for non-dex-cache as they can't contain
1602 // native references to strings. This is verified during compilation
1603 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001604 obj->VisitReferences</* kVisitNativeRoots= */ false,
1605 kVerifyNone,
1606 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001607 }
1608 }
1609 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001610 return visitor.GetCount();
1611}
1612
1613template <typename Visitor>
1614static void VisitInternedStringReferences(
1615 gc::space::ImageSpace* space,
1616 bool use_preresolved_strings,
1617 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1618 const uint8_t* target_base = space->Begin();
1619 const ImageSection& sro_section =
1620 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1621 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1622
1623 VLOG(image)
1624 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1625 << num_string_offsets;
1626
1627 const auto* sro_base =
1628 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1629
1630 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1631 uint32_t base_offset = sro_base[offset_index].first;
1632
1633 if (HasDexCacheStringNativeRefTag(base_offset)) {
1634 base_offset = ClearDexCacheNativeRefTags(base_offset);
1635 DCHECK_ALIGNED(base_offset, 2);
1636
1637 ObjPtr<mirror::DexCache> dex_cache =
1638 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1639 uint32_t string_slot_index = sro_base[offset_index].second;
1640
1641 mirror::StringDexCachePair source =
1642 dex_cache->GetStrings()[string_slot_index].load(std::memory_order_relaxed);
1643 ObjPtr<mirror::String> referred_string = source.object.Read();
1644 DCHECK(referred_string != nullptr);
1645
1646 ObjPtr<mirror::String> visited = visitor(referred_string);
1647 if (visited != referred_string) {
1648 // Because we are not using a helper function we need to mark the GC card manually.
1649 WriteBarrier::ForEveryFieldWrite(dex_cache);
1650 dex_cache->GetStrings()[string_slot_index].store(
1651 mirror::StringDexCachePair(visited, source.index), std::memory_order_relaxed);
1652 }
1653 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1654 if (use_preresolved_strings) {
1655 base_offset = ClearDexCacheNativeRefTags(base_offset);
1656 DCHECK_ALIGNED(base_offset, 2);
1657
1658 ObjPtr<mirror::DexCache> dex_cache =
1659 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1660 uint32_t string_index = sro_base[offset_index].second;
1661
Mathieu Chartier77f84fc2019-06-14 12:49:54 -07001662 GcRoot<mirror::String>* preresolved_strings =
1663 dex_cache->GetPreResolvedStrings();
1664 // Handle calls to ClearPreResolvedStrings that might occur concurrently by the profile
1665 // saver that runs shortly after startup. In case the strings are cleared, there is nothing
1666 // to fix up.
1667 if (preresolved_strings != nullptr) {
1668 ObjPtr<mirror::String> referred_string =
1669 preresolved_strings[string_index].Read();
1670 if (referred_string != nullptr) {
1671 ObjPtr<mirror::String> visited = visitor(referred_string);
1672 if (visited != referred_string) {
1673 // Because we are not using a helper function we need to mark the GC card manually.
1674 WriteBarrier::ForEveryFieldWrite(dex_cache);
1675 preresolved_strings[string_index] = GcRoot<mirror::String>(visited);
1676 }
1677 }
Vladimir Marko8e05f092019-06-10 11:10:38 +01001678 }
1679 }
1680 } else {
1681 uint32_t raw_member_offset = sro_base[offset_index].second;
1682 DCHECK_ALIGNED(base_offset, 2);
1683 DCHECK_ALIGNED(raw_member_offset, 2);
1684
1685 ObjPtr<mirror::Object> obj_ptr =
1686 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1687 MemberOffset member_offset(raw_member_offset);
1688 ObjPtr<mirror::String> referred_string =
1689 obj_ptr->GetFieldObject<mirror::String,
1690 kVerifyNone,
1691 kWithoutReadBarrier,
1692 /* kIsVolatile= */ false>(member_offset);
1693 DCHECK(referred_string != nullptr);
1694
1695 ObjPtr<mirror::String> visited = visitor(referred_string);
1696 if (visited != referred_string) {
1697 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1698 /* kCheckTransaction= */ false,
1699 kVerifyNone,
1700 /* kIsVolatile= */ false>(member_offset, visited);
1701 }
1702 }
1703 }
1704}
1705
1706static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1707 REQUIRES_SHARED(Locks::mutator_lock_) {
1708 InternTable::UnorderedSet image_interns;
1709 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1710 if (section.Size() > 0) {
1711 size_t read_count;
1712 const uint8_t* data = space->Begin() + section.Offset();
1713 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1714 image_set.swap(image_interns);
1715 }
1716 size_t num_recorded_refs = 0u;
1717 VisitInternedStringReferences(
1718 space,
1719 /*use_preresolved_strings=*/ true,
1720 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1721 REQUIRES_SHARED(Locks::mutator_lock_) {
1722 auto it = image_interns.find(GcRoot<mirror::String>(str));
1723 CHECK(it != image_interns.end());
1724 CHECK(it->Read() == str);
1725 ++num_recorded_refs;
1726 return str;
1727 });
1728 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1729 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001730}
1731
Andreas Gampe2af99022017-04-25 08:32:59 -07001732// new_class_set is the set of classes that were read from the class table section in the image.
1733// If there was no class table section, it is null.
1734// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001735class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001736 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001737 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001738 ClassLinker* class_linker,
1739 gc::space::ImageSpace* space,
1740 Handle<mirror::ClassLoader> class_loader,
1741 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001742 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001743 REQUIRES(!Locks::dex_lock_)
1744 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001745
Chris Wailesfbeef462018-10-19 14:16:35 -07001746 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001747 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001748};
1749
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001750void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001751 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001752 gc::space::ImageSpace* space,
1753 Handle<mirror::ClassLoader> class_loader,
1754 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001755 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001756 REQUIRES(!Locks::dex_lock_)
1757 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001758 ScopedTrace app_image_timing("AppImage:Updating");
1759
Vladimir Marko8e05f092019-06-10 11:10:38 +01001760 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1761 // In debug build, verify the string references before applying
1762 // the Runtime::LoadAppImageStartupCache() option.
1763 VerifyInternedStringReferences(space);
1764 }
1765
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001766 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001767 Runtime* const runtime = Runtime::Current();
1768 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001769 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001770 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001771 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001772 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001773 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001774 const size_t num_dex_caches = dex_caches->GetLength();
1775 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001776 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001777 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001778 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001779 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001780 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1781 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001782 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001783
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001784 if (!load_app_image_startup_cache) {
1785 dex_cache->ClearPreResolvedStrings();
1786 }
1787
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001788 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001789 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001790 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001791 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001792 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001793 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001794 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001795
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001796 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001797 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001798 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001799 DCHECK(it != new_class_set->end());
1800 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001801 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001802
Vladimir Marko1a1de672016-10-13 12:53:15 +01001803 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001804 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001805 DCHECK(it2 != new_class_set->end());
1806 DCHECK_EQ(it2->Read(), super_class);
1807 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001808
Vladimir Marko1a1de672016-10-13 12:53:15 +01001809 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1810 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001811 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1812 if (!class_linker->IsQuickResolutionStub(code) &&
1813 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001814 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001815 !m.IsNative()) {
1816 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001817 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001818 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001819
Vladimir Marko1a1de672016-10-13 12:53:15 +01001820 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1821 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001822 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1823 if (!class_linker->IsQuickResolutionStub(code) &&
1824 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001825 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001826 !m.IsNative()) {
1827 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001828 }
1829 }
1830 }
1831 }
1832 }
1833 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001834 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001835
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001836 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001837 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001838 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001839
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001840 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001841 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001842 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001843 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1844 header.VisitPackedArtMethods([&](ArtMethod& method)
1845 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1846 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1847 if (klass != nullptr) {
1848 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1849 }
1850 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001851 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001852}
1853
Chris Wailesfbeef462018-10-19 14:16:35 -07001854void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001855 // Iterate over the string reference offsets stored in the image and intern
1856 // the strings they point to.
1857 ScopedTrace timing("AppImage:InternString");
1858
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001859 Runtime* const runtime = Runtime::Current();
1860 InternTable* const intern_table = runtime->GetInternTable();
1861
1862 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001863
1864 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1865 // for faster lookup.
1866 // TODO: Optimize with a bitmap or bloom filter
1867 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001868 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001869 REQUIRES_SHARED(Locks::mutator_lock_)
1870 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001871 const size_t non_boot_image_strings = intern_table->CountInterns(
1872 /*visit_boot_images=*/false,
1873 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001874 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001875 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1876 // Visit the smaller of the two sets to compute the intersection.
1877 if (interns.size() < non_boot_image_strings) {
1878 for (auto it = interns.begin(); it != interns.end(); ) {
1879 ObjPtr<mirror::String> string = it->Read();
1880 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1881 if (existing == nullptr) {
1882 existing = intern_table->LookupStrongLocked(string);
1883 }
1884 if (existing != nullptr) {
1885 intern_remap.Put(string.Ptr(), existing.Ptr());
1886 it = interns.erase(it);
1887 } else {
1888 ++it;
1889 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001890 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001891 } else {
1892 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1893 REQUIRES_SHARED(Locks::mutator_lock_)
1894 REQUIRES(Locks::intern_table_lock_) {
1895 auto it = interns.find(root);
1896 if (it != interns.end()) {
1897 ObjPtr<mirror::String> existing = root.Read();
1898 intern_remap.Put(it->Read(), existing.Ptr());
1899 it = interns.erase(it);
1900 }
1901 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1902 }
1903 // Sanity check to ensure correctness.
1904 if (kIsDebugBuild) {
1905 for (GcRoot<mirror::String>& root : interns) {
1906 ObjPtr<mirror::String> string = root.Read();
1907 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1908 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001909 }
1910 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001911 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001912 intern_table->AddImageStringsToTable(space, func);
1913 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001914 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001915 VisitInternedStringReferences(
1916 space,
1917 load_startup_cache,
1918 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1919 auto it = intern_remap.find(str.Ptr());
1920 if (it != intern_remap.end()) {
1921 return ObjPtr<mirror::String>(it->second);
1922 }
1923 return str;
1924 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001925 }
1926}
1927
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001928static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1929 const char* location,
1930 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001931 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001932 DCHECK(error_msg != nullptr);
1933 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001934 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001935 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001936 return std::unique_ptr<const DexFile>();
1937 }
1938 std::string inner_error_msg;
1939 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1940 if (dex_file == nullptr) {
1941 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1942 location,
1943 oat_file->GetLocation().c_str(),
1944 inner_error_msg.c_str());
1945 return std::unique_ptr<const DexFile>();
1946 }
1947
1948 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1949 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1950 location,
1951 dex_file->GetLocationChecksum(),
1952 oat_dex_file->GetDexFileLocationChecksum());
1953 return std::unique_ptr<const DexFile>();
1954 }
1955 return dex_file;
1956}
1957
1958bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1959 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1960 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001961 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001962 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001963 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001964 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001965 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001966 dex_caches_object->AsObjectArray<mirror::DexCache>();
1967 const OatFile* oat_file = space->GetOatFile();
Vladimir Marko4617d582019-03-28 13:48:31 +00001968 for (int32_t i = 0, length = dex_caches->GetLength(); i != length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001969 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001970 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1971 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1972 dex_file_location.c_str(),
1973 error_msg);
1974 if (dex_file == nullptr) {
1975 return false;
1976 }
1977 dex_cache->SetDexFile(dex_file.get());
1978 out_dex_files->push_back(std::move(dex_file));
1979 }
1980 return true;
1981}
1982
Andreas Gampe0793bec2016-12-01 11:37:33 -08001983// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1984// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001985class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001986 public:
1987 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1988 REQUIRES_SHARED(Locks::mutator_lock_) {
1989 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001990 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1991 DCHECK(obj != nullptr);
1992 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1993 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1994 if (obj->IsClass()) {
1995 auto klass = obj->AsClass();
1996 for (ArtField& field : klass->GetIFields()) {
1997 CHECK_EQ(field.GetDeclaringClass(), klass);
1998 }
1999 for (ArtField& field : klass->GetSFields()) {
2000 CHECK_EQ(field.GetDeclaringClass(), klass);
2001 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002002 const PointerSize pointer_size = isc.pointer_size_;
2003 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07002004 isc.SanityCheckArtMethod(&m, klass);
2005 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002006 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07002007 if (vtable != nullptr) {
2008 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
2009 }
2010 if (klass->ShouldHaveImt()) {
2011 ImTable* imt = klass->GetImt(pointer_size);
2012 for (size_t i = 0; i < ImTable::kSize; ++i) {
2013 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
2014 }
2015 }
2016 if (klass->ShouldHaveEmbeddedVTable()) {
2017 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
2018 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
2019 }
2020 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002021 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07002022 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2023 if (iftable->GetMethodArrayCount(i) > 0) {
2024 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
2025 }
2026 }
2027 }
2028 };
2029 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08002030 }
2031
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002032 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
2033 ClassLinker* class_linker,
2034 mirror::MethodDexCacheType* arr,
2035 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08002036 REQUIRES_SHARED(Locks::mutator_lock_) {
2037 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002038 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08002039 }
2040
Andreas Gampe0793bec2016-12-01 11:37:33 -08002041 private:
2042 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
2043 : spaces_(heap->GetBootImageSpaces()),
2044 pointer_size_(class_linker->GetImagePointerSize()) {
2045 space_begin_.reserve(spaces_.size());
2046 method_sections_.reserve(spaces_.size());
2047 runtime_method_sections_.reserve(spaces_.size());
2048 for (gc::space::ImageSpace* space : spaces_) {
2049 space_begin_.push_back(space->Begin());
2050 auto& header = space->GetImageHeader();
2051 method_sections_.push_back(&header.GetMethodsSection());
2052 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
2053 }
2054 }
2055
2056 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
2057 REQUIRES_SHARED(Locks::mutator_lock_) {
2058 if (m->IsRuntimeMethod()) {
2059 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
2060 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
2061 } else if (m->IsCopied()) {
2062 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
2063 } else if (expected_class != nullptr) {
2064 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
2065 }
2066 if (!spaces_.empty()) {
2067 bool contains = false;
2068 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
2069 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
2070 contains = method_sections_[i]->Contains(offset) ||
2071 runtime_method_sections_[i]->Contains(offset);
2072 }
2073 CHECK(contains) << m << " not found";
2074 }
2075 }
2076
2077 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
2078 ObjPtr<mirror::Class> expected_class)
2079 REQUIRES_SHARED(Locks::mutator_lock_) {
2080 CHECK(arr != nullptr);
2081 for (int32_t j = 0; j < arr->GetLength(); ++j) {
2082 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
2083 // expected_class == null means we are a dex cache.
2084 if (expected_class != nullptr) {
2085 CHECK(method != nullptr);
2086 }
2087 if (method != nullptr) {
2088 SanityCheckArtMethod(method, expected_class);
2089 }
2090 }
2091 }
2092
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002093 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08002094 REQUIRES_SHARED(Locks::mutator_lock_) {
2095 CHECK_EQ(arr != nullptr, size != 0u);
2096 if (arr != nullptr) {
2097 bool contains = false;
2098 for (auto space : spaces_) {
2099 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002100 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002101 contains = true;
2102 break;
2103 }
2104 }
2105 CHECK(contains);
2106 }
2107 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002108 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
2109 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08002110 // expected_class == null means we are a dex cache.
2111 if (method != nullptr) {
2112 SanityCheckArtMethod(method, nullptr);
2113 }
2114 }
2115 }
2116
2117 const std::vector<gc::space::ImageSpace*>& spaces_;
2118 const PointerSize pointer_size_;
2119
2120 // Cached sections from the spaces.
2121 std::vector<const uint8_t*> space_begin_;
2122 std::vector<const ImageSection*> method_sections_;
2123 std::vector<const ImageSection*> runtime_method_sections_;
2124};
2125
Andreas Gampebe7af222017-07-25 09:57:28 -07002126static void VerifyAppImage(const ImageHeader& header,
2127 const Handle<mirror::ClassLoader>& class_loader,
2128 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
2129 ClassTable* class_table, gc::space::ImageSpace* space)
2130 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002131 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2132 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
2133 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2134 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
2135 << mirror::Class::PrettyClass(klass);
2136 }
2137 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07002138 {
2139 // Verify that all direct interfaces of classes in the class table are also resolved.
2140 std::vector<ObjPtr<mirror::Class>> classes;
2141 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
2142 REQUIRES_SHARED(Locks::mutator_lock_) {
2143 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
2144 classes.push_back(klass);
2145 }
2146 return true;
2147 };
2148 class_table->Visit(verify_direct_interfaces_in_table);
2149 Thread* self = Thread::Current();
2150 for (ObjPtr<mirror::Class> klass : classes) {
2151 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
2152 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
2153 << klass->PrettyDescriptor() << " iface #" << i;
2154 }
2155 }
2156 }
2157 // Check that all non-primitive classes in dex caches are also in the class table.
2158 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2159 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2160 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
2161 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
2162 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
2163 if (klass != nullptr && !klass->IsPrimitive()) {
2164 CHECK(class_table->Contains(klass))
2165 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
2166 }
2167 }
2168 }
2169}
2170
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002171bool ClassLinker::AddImageSpace(
2172 gc::space::ImageSpace* space,
2173 Handle<mirror::ClassLoader> class_loader,
2174 jobjectArray dex_elements,
2175 const char* dex_location,
2176 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
2177 std::string* error_msg) {
2178 DCHECK(out_dex_files != nullptr);
2179 DCHECK(error_msg != nullptr);
2180 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002181 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002182 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002183 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002184 DCHECK(dex_caches_object != nullptr);
2185 Runtime* const runtime = Runtime::Current();
2186 gc::Heap* const heap = runtime->GetHeap();
2187 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002188 // Check that the image is what we are expecting.
2189 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
2190 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
2191 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
2192 image_pointer_size_);
2193 return false;
2194 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002195 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
2196 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
2197 *error_msg = StringPrintf("Expected %zu image roots but got %d",
2198 expected_image_roots,
2199 header.GetImageRoots()->GetLength());
2200 return false;
2201 }
2202 StackHandleScope<3> hs(self);
2203 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
2204 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2205 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2206 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002207 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002208 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2209 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002210 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002211 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002212 *error_msg = StringPrintf("Expected %d class roots but got %d",
2213 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002214 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002215 return false;
2216 }
2217 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002218 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2219 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2220 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002221 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2222 return false;
2223 }
2224 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002225 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002226 if (oat_file->GetOatHeader().GetDexFileCount() !=
2227 static_cast<uint32_t>(dex_caches->GetLength())) {
2228 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2229 "image";
2230 return false;
2231 }
2232
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002233 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002234 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
David Brazdil3e8aae02019-03-26 18:48:02 +00002235 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Andreas Gamped5d807b2019-04-18 14:46:51 -07002236 if (class_loader == nullptr) {
2237 // For app images, we'll see the relative location. b/130666977.
2238 DCHECK_EQ(dex_location, DexFileLoader::GetBaseLocation(dex_file_location));
2239 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002240 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2241 dex_file_location.c_str(),
2242 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002243 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002244 return false;
2245 }
2246
2247 if (app_image) {
2248 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2249 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002250 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002251 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002252 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002253 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002254 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002255 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002256 }
2257 }
2258 } else {
2259 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002260 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2261 this,
2262 dex_cache->GetResolvedMethods(),
2263 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002264 }
2265 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002266 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002267 }
2268 out_dex_files->push_back(std::move(dex_file));
2269 }
2270
2271 if (app_image) {
2272 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002273 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002274 // Check that the class loader resolves the same way as the ones in the image.
2275 // Image class loader [A][B][C][image dex files]
2276 // Class loader = [???][dex_elements][image dex files]
2277 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002278 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002279 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2280 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2281 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002282 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2283 *error_msg = "Unexpected BootClassLoader in app image";
2284 return false;
2285 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002286 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2287 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2288 // special case the comparison of dex files of the two class loaders, but then do full
2289 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002290 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002291 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002292 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2293 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2294 if (element != nullptr) {
2295 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002296 ObjPtr<mirror::String> name;
2297 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2298 loader_dex_file_names.push_back(name);
2299 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002300 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002301 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002302 std::string temp_error_msg;
2303 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2304 bool success = GetDexFileNames(
2305 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2306 if (success) {
2307 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2308 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2309 static_cast<size_t>(dex_caches->GetLength()));
2310 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2311 image_dex_file_names.resize(image_count);
2312 success = success && CompareDexFiles(image_dex_file_names,
2313 loader_dex_file_names,
2314 &temp_error_msg);
2315 success = success && CompareClassLoaders(soa,
2316 image_class_loader.Get(),
2317 class_loader.Get(),
2318 /*check_dex_file_names=*/ false,
2319 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002320 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002321 if (!success) {
2322 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2323 temp_error_msg.c_str());
2324 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002325 }
2326 }
2327
2328 if (kSanityCheckObjects) {
2329 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002330 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002331 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2332 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2333 if (field != nullptr) {
2334 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2335 }
2336 }
2337 }
2338 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002339 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002340 }
2341 }
2342
2343 // Set entry point to interpreter if in InterpretOnly mode.
2344 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002345 // Set image methods' entry point to interpreter.
2346 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2347 if (!method.IsRuntimeMethod()) {
2348 DCHECK(method.GetDeclaringClass() != nullptr);
2349 if (!method.IsNative() && !method.IsResolutionMethod()) {
2350 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2351 image_pointer_size_);
2352 }
2353 }
2354 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002355 }
2356
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002357 ClassTable* class_table = nullptr;
2358 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002359 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002360 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002361 }
2362 // If we have a class table section, read it and use it for verification in
2363 // UpdateAppImageClassLoadersAndDexCaches.
2364 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002365 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002366 const bool added_class_table = class_table_section.Size() > 0u;
2367 if (added_class_table) {
2368 const uint64_t start_time2 = NanoTime();
2369 size_t read_count = 0;
2370 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2371 /*make copy*/false,
2372 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002373 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002374 }
2375 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002376 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002377
2378 {
2379 ScopedTrace trace("AppImage:UpdateClassLoaders");
2380 // Update class loader and resolved strings. If added_class_table is false, the resolved
2381 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002382 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002383 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002384 // Note: We probably don't need the read barrier unless we copy the app image objects into
2385 // the region space.
2386 ObjPtr<mirror::Class> klass(root.Read());
2387 // Do not update class loader for boot image classes where the app image
2388 // class loader is only the initiating loader but not the defining loader.
2389 // Avoid read barrier since we are comparing against null.
2390 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2391 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2392 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002393 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002394 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002395
Vladimir Marko305c38b2018-02-14 11:50:07 +00002396 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002397 // Every class in the app image has initially SubtypeCheckInfo in the
2398 // Uninitialized state.
2399 //
2400 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2401 // after class initialization is complete. The app image ClassStatus as-is
2402 // are almost all ClassStatus::Initialized, and being in the
2403 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2404 //
2405 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2406 //
2407 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002408 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002409 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2410 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002411 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002412 }
2413 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002414 }
2415 if (!oat_file->GetBssGcRoots().empty()) {
2416 // Insert oat file to class table for visiting .bss GC roots.
2417 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002418 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002419
Mathieu Chartier69731002016-03-02 16:08:31 -08002420 if (added_class_table) {
2421 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2422 class_table->AddClassSet(std::move(temp_set));
2423 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002424
Mathieu Chartier69731002016-03-02 16:08:31 -08002425 if (kIsDebugBuild && app_image) {
2426 // This verification needs to happen after the classes have been added to the class loader.
2427 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002428 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002429 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002430 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002431
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002432 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002433 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002434}
2435
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002436bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002437 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2438 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002439}
2440
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002441void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002442 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2443 // enabling tracing requires the mutator lock, there are no race conditions here.
2444 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002445 Thread* const self = Thread::Current();
2446 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002447 if (kUseReadBarrier) {
2448 // We do not track new roots for CC.
2449 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2450 kVisitRootFlagClearRootLog |
2451 kVisitRootFlagStartLoggingNewRoots |
2452 kVisitRootFlagStopLoggingNewRoots));
2453 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002454 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002455 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2456 // There is 3 GC cases to handle:
2457 // Non moving concurrent:
2458 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002459 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002460 //
2461 // Moving non-concurrent:
2462 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2463 // To prevent missing roots, this case needs to ensure that there is no
2464 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2465 // class which is in the class table.
2466 //
2467 // Moving concurrent:
2468 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2469 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002470 //
2471 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2472 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2473 // these objects.
2474 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002475 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002476 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002477 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002478 for (const ClassLoaderData& data : class_loaders_) {
2479 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2480 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2481 }
2482 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002483 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002484 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002485 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002486 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002487 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002488 // Concurrent moving GC marked new roots through the to-space invariant.
2489 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002490 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002491 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2492 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2493 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2494 if (old_ref != nullptr) {
2495 DCHECK(old_ref->IsClass());
2496 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2497 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2498 // Concurrent moving GC marked new roots through the to-space invariant.
2499 CHECK_EQ(new_ref, old_ref);
2500 }
2501 }
2502 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002503 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002504 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002505 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002506 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002507 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002508 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002509 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002510 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002511 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002512 }
2513 // We deliberately ignore the class roots in the image since we
2514 // handle image roots by using the MS/CMS rescanning of dirty cards.
2515}
2516
Brian Carlstroma663ea52011-08-19 23:33:41 -07002517// Keep in sync with InitCallback. Anything we visit, we need to
2518// reinit references to when reinitializing a ClassLinker from a
2519// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002520void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002521 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002522 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002523 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2524 // unloading if we are marking roots.
2525 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002526}
2527
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002528class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2529 public:
2530 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2531 : visitor_(visitor),
2532 done_(false) {}
2533
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002534 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002535 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002536 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002537 if (!done_ && class_table != nullptr) {
2538 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2539 if (!class_table->Visit(visitor)) {
2540 // If the visitor ClassTable returns false it means that we don't need to continue.
2541 done_ = true;
2542 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002543 }
2544 }
2545
2546 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002547 // Class visitor that limits the class visits from a ClassTable to the classes with
2548 // the provided defining class loader. This filter is used to avoid multiple visits
2549 // of the same class which can be recorded for multiple initiating class loaders.
2550 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2551 public:
2552 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2553 ClassVisitor* visitor)
2554 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2555
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002556 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002557 if (klass->GetClassLoader() != defining_class_loader_) {
2558 return true;
2559 }
2560 return (*visitor_)(klass);
2561 }
2562
Vladimir Marko0984e482019-03-27 16:41:41 +00002563 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002564 ClassVisitor* const visitor_;
2565 };
2566
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002567 ClassVisitor* const visitor_;
2568 // If done is true then we don't need to do any more visiting.
2569 bool done_;
2570};
2571
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002572void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002573 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002574 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2575 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002576 }
2577}
2578
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002579void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002580 Thread* const self = Thread::Current();
2581 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2582 // Not safe to have thread suspension when we are holding a lock.
2583 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002584 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002585 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002586 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002587 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002588 }
2589}
2590
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002591class GetClassesInToVector : public ClassVisitor {
2592 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002593 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002594 classes_.push_back(klass);
2595 return true;
2596 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002597 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002598};
2599
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002600class GetClassInToObjectArray : public ClassVisitor {
2601 public:
2602 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2603 : arr_(arr), index_(0) {}
2604
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002605 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002606 ++index_;
2607 if (index_ <= arr_->GetLength()) {
2608 arr_->Set(index_ - 1, klass);
2609 return true;
2610 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002611 return false;
2612 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002613
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002614 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002615 return index_ <= arr_->GetLength();
2616 }
2617
2618 private:
2619 mirror::ObjectArray<mirror::Class>* const arr_;
2620 int32_t index_;
2621};
2622
2623void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002624 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2625 // is avoiding duplicates.
2626 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002627 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002628 GetClassesInToVector accumulator;
2629 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002630 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002631 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002632 return;
2633 }
2634 }
2635 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002636 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002637 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002638 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002639 // We size the array assuming classes won't be added to the class table during the visit.
2640 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002641 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002642 size_t class_table_size;
2643 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002644 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002645 // Add 100 in case new classes get loaded when we are filling in the object array.
2646 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002647 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002648 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002649 classes.Assign(
2650 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002651 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002652 GetClassInToObjectArray accumulator(classes.Get());
2653 VisitClasses(&accumulator);
2654 if (accumulator.Succeeded()) {
2655 break;
2656 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002657 }
2658 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2659 // If the class table shrank during creation of the clases array we expect null elements. If
2660 // the class table grew then the loop repeats. If classes are created after the loop has
2661 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002662 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002663 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002664 return;
2665 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002666 }
2667 }
2668}
2669
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002670ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002671 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002672 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002673 // CHA unloading analysis is not needed. No negative consequences are expected because
2674 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002675 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002676 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002677 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002678 while (!running_visibly_initialized_callbacks_.empty()) {
2679 std::unique_ptr<VisiblyInitializedCallback> callback(
2680 std::addressof(running_visibly_initialized_callbacks_.front()));
2681 running_visibly_initialized_callbacks_.pop_front();
2682 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002683}
2684
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002685void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002686 Runtime* const runtime = Runtime::Current();
2687 JavaVMExt* const vm = runtime->GetJavaVM();
2688 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002689 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002690 if (runtime->GetJit() != nullptr) {
2691 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2692 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002693 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002694 code_cache->RemoveMethodsIn(self, *data.allocator);
2695 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002696 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002697 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002698 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002699 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002700 // Cleanup references to single implementation ArtMethods that will be deleted.
2701 if (cleanup_cha) {
2702 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2703 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2704 }
2705
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002706 delete data.allocator;
2707 delete data.class_table;
2708}
2709
Vladimir Markobcf17522018-06-01 13:14:32 +01002710ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2711 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002712 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002713 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2714 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002715}
2716
Vladimir Markobcf17522018-06-01 13:14:32 +01002717ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2718 Thread* self,
2719 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002720 StackHandleScope<1> hs(self);
2721 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002722 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002723 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002724 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002725 self->AssertPendingOOMException();
2726 return nullptr;
2727 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002728 // Use InternWeak() so that the location String can be collected when the ClassLoader
2729 // with this DexCache is collected.
2730 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002731 if (location == nullptr) {
2732 self->AssertPendingOOMException();
2733 return nullptr;
2734 }
2735 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002736 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002737}
2738
Vladimir Markobcf17522018-06-01 13:14:32 +01002739ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2740 const DexFile& dex_file,
2741 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002742 ObjPtr<mirror::String> location = nullptr;
2743 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002744 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002745 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002746 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002747 mirror::DexCache::InitializeDexCache(self,
2748 dex_cache,
2749 location,
2750 &dex_file,
2751 linear_alloc,
2752 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002753 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002754 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002755}
2756
Vladimir Marko70e2a762019-07-12 16:49:00 +01002757template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002758ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2759 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002760 uint32_t class_size,
2761 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002762 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002763 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002764 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002765 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2766 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002767 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002768 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002769 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002770 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002771 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002772}
2773
Vladimir Marko70e2a762019-07-12 16:49:00 +01002774template <bool kMovable>
2775ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2776 ObjPtr<mirror::Class> java_lang_Class,
2777 uint32_t class_size) {
2778 mirror::Class::InitializeClassVisitor visitor(class_size);
2779 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2780}
2781
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002782ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002783 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002784}
2785
Vladimir Marko70e2a762019-07-12 16:49:00 +01002786void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2787 ClassRoot primitive_root,
2788 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002789 // We make this class non-movable for the unlikely case where it were to be
2790 // moved by a sticky-bit (minor) collection when using the Generational
2791 // Concurrent Copying (CC) collector, potentially creating a stale reference
2792 // in the `klass_` field of one of its instances allocated in the Large-Object
2793 // Space (LOS) -- see the comment about the dirty card scanning logic in
2794 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002795 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2796 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2797 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2798 DCHECK(component_type->IsPrimitive());
2799 array_class->SetComponentType(component_type);
2800 SetClassRoot(array_root, array_class);
2801}
2802
2803void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2804 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2805 array_class->SetSuperClass(java_lang_Object);
2806 array_class->SetVTable(java_lang_Object->GetVTable());
2807 array_class->SetPrimitiveType(Primitive::kPrimNot);
2808 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2809 array_class->SetClassFlags(component_type->IsPrimitive()
2810 ? mirror::kClassFlagNoReferenceFields
2811 : mirror::kClassFlagObjectArray);
2812 array_class->SetClassLoader(component_type->GetClassLoader());
2813 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2814 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2815 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2816 array_class->SetImt(object_imt, image_pointer_size_);
2817 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2818 // the kAccVerificationAttempted flag is added below, and there are no
2819 // methods that need the kAccSkipAccessChecks flag.
2820 DCHECK_EQ(array_class->NumMethods(), 0u);
2821
2822 // don't need to set new_class->SetObjectSize(..)
2823 // because Object::SizeOf delegates to Array::SizeOf
2824
2825 // All arrays have java/lang/Cloneable and java/io/Serializable as
2826 // interfaces. We need to set that up here, so that stuff like
2827 // "instanceof" works right.
2828
2829 // Use the single, global copies of "interfaces" and "iftable"
2830 // (remember not to free them for arrays).
2831 {
2832 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2833 CHECK(array_iftable != nullptr);
2834 array_class->SetIfTable(array_iftable);
2835 }
2836
2837 // Inherit access flags from the component type.
2838 int access_flags = component_type->GetAccessFlags();
2839 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2840 access_flags &= kAccJavaFlagsMask;
2841 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2842 // and remove "interface".
2843 access_flags |= kAccAbstract | kAccFinal;
2844 access_flags &= ~kAccInterface;
2845 // Arrays are access-checks-clean and preverified.
2846 access_flags |= kAccVerificationAttempted;
2847
2848 array_class->SetAccessFlags(access_flags);
2849
Vladimir Markobf121912019-06-04 13:49:05 +01002850 // Array classes are fully initialized either during single threaded startup,
2851 // or from a pre-fence visitor, so visibly initialized.
2852 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002853}
2854
2855void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2856 // Do not hold lock on the array class object, the initialization of
2857 // core array classes is done while the process is still single threaded.
2858 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2859 FinishArrayClassSetup(array_class);
2860
2861 std::string temp;
2862 const char* descriptor = array_class->GetDescriptor(&temp);
2863 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2864 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2865 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002866}
2867
Vladimir Markobcf17522018-06-01 13:14:32 +01002868ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002869 Thread* self,
2870 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002871 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002872 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002873}
2874
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002875ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2876 const char* descriptor,
2877 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002878 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002879 if (kIsDebugBuild) {
2880 StackHandleScope<1> hs(self);
2881 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2882 Thread::PoisonObjectPointersIfDebug();
2883 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002884
2885 // For temporary classes we must wait for them to be retired.
2886 if (init_done_ && klass->IsTemp()) {
2887 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002888 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002889 ThrowEarlierClassFailure(klass);
2890 return nullptr;
2891 }
2892 StackHandleScope<1> hs(self);
2893 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2894 ObjectLock<mirror::Class> lock(self, h_class);
2895 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002896 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002897 lock.WaitIgnoringInterrupts();
2898 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002899 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002900 ThrowEarlierClassFailure(h_class.Get());
2901 return nullptr;
2902 }
2903 CHECK(h_class->IsRetired());
2904 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002905 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002906 }
2907
Brian Carlstromaded5f72011-10-07 17:15:04 -07002908 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002909 size_t index = 0;
2910 // Maximum number of yield iterations until we start sleeping.
2911 static const size_t kNumYieldIterations = 1000;
2912 // How long each sleep is in us.
2913 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002914 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002915 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002916 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002917 {
2918 ObjectTryLock<mirror::Class> lock(self, h_class);
2919 // Can not use a monitor wait here since it may block when returning and deadlock if another
2920 // thread has locked klass.
2921 if (lock.Acquired()) {
2922 // Check for circular dependencies between classes, the lock is required for SetStatus.
2923 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2924 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002925 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002926 return nullptr;
2927 }
2928 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002929 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002930 {
2931 // Handle wrapper deals with klass moving.
2932 ScopedThreadSuspension sts(self, kSuspended);
2933 if (index < kNumYieldIterations) {
2934 sched_yield();
2935 } else {
2936 usleep(kSleepDurationUS);
2937 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002938 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002939 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002940 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002941
Vladimir Marko72ab6842017-01-20 19:32:50 +00002942 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002943 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002944 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002945 }
2946 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002947 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002948 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002949 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002950}
2951
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002952using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002953
2954// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002955ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002956 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002957 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002958 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002959 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002960 return ClassPathEntry(dex_file, dex_class_def);
2961 }
2962 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002963 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002964}
2965
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002966bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2967 Thread* self,
2968 const char* descriptor,
2969 size_t hash,
2970 Handle<mirror::ClassLoader> class_loader,
2971 /*out*/ ObjPtr<mirror::Class>* result) {
2972 ArtField* field =
2973 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2974 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2975 if (raw_shared_libraries == nullptr) {
2976 return true;
2977 }
2978
2979 StackHandleScope<2> hs(self);
2980 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2981 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2982 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2983 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2984 temp_loader.Assign(shared_libraries->Get(i));
2985 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2986 return false; // One of the shared libraries is not supported.
2987 }
2988 if (*result != nullptr) {
2989 return true; // Found the class up the chain.
2990 }
2991 }
2992 return true;
2993}
2994
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002995bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2996 Thread* self,
2997 const char* descriptor,
2998 size_t hash,
2999 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01003000 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07003001 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07003002 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07003003 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07003004 return true;
3005 }
3006
David Brazdil05909d82018-12-06 16:25:16 +00003007 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07003008 // For regular path or dex class loader the search order is:
3009 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003010 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07003011 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07003012
Calin Juravlecdd49122017-07-05 20:09:53 -07003013 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
3014 StackHandleScope<1> hs(self);
3015 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
3016 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
3017 return false; // One of the parents is not supported.
3018 }
3019 if (*result != nullptr) {
3020 return true; // Found the class up the chain.
3021 }
Andreas Gampef865ea92015-04-13 22:14:19 -07003022
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003023 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
3024 return false; // One of the shared library loader is not supported.
3025 }
3026 if (*result != nullptr) {
3027 return true; // Found the class in a shared library.
3028 }
3029
Calin Juravlecdd49122017-07-05 20:09:53 -07003030 // Search the current class loader classpath.
3031 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00003032 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07003033 }
3034
Calin Juravlecdd49122017-07-05 20:09:53 -07003035 if (IsDelegateLastClassLoader(soa, class_loader)) {
3036 // For delegate last, the search order is:
3037 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003038 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07003039 // - class loader dex files
3040 // - parent
3041 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
3042 if (*result != nullptr) {
3043 return true; // The class is part of the boot class path.
3044 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003045 if (self->IsExceptionPending()) {
3046 // Pending exception means there was an error other than ClassNotFound that must be returned
3047 // to the caller.
3048 return false;
3049 }
Calin Juravlecdd49122017-07-05 20:09:53 -07003050
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003051 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
3052 return false; // One of the shared library loader is not supported.
3053 }
3054 if (*result != nullptr) {
3055 return true; // Found the class in a shared library.
3056 }
3057
Calin Juravlecdd49122017-07-05 20:09:53 -07003058 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
3059 if (*result != nullptr) {
3060 return true; // Found the class in the current class loader
3061 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003062 if (self->IsExceptionPending()) {
3063 // Pending exception means there was an error other than ClassNotFound that must be returned
3064 // to the caller.
3065 return false;
3066 }
Calin Juravlecdd49122017-07-05 20:09:53 -07003067
3068 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
3069 StackHandleScope<1> hs(self);
3070 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
3071 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
3072 }
3073
3074 // Unsupported class loader.
3075 *result = nullptr;
3076 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07003077}
3078
Andreas Gampe501c3b02019-04-17 21:54:27 +00003079namespace {
3080
3081// Matches exceptions caught in DexFile.defineClass.
3082ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
3083 ClassLinker* class_linker)
3084 REQUIRES_SHARED(Locks::mutator_lock_) {
3085 return
3086 // ClassNotFoundException.
3087 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
3088 class_linker))
3089 ||
3090 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
3091 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
3092}
3093
3094// Clear exceptions caught in DexFile.defineClass.
3095ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
3096 REQUIRES_SHARED(Locks::mutator_lock_) {
3097 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
3098 self->ClearException();
3099 }
3100}
3101
3102} // namespace
3103
Calin Juravle415dc3d2017-06-28 11:03:12 -07003104// Finds the class in the boot class loader.
3105// If the class is found the method returns the resolved class. Otherwise it returns null.
3106ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
3107 const char* descriptor,
3108 size_t hash) {
3109 ObjPtr<mirror::Class> result = nullptr;
3110 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
3111 if (pair.second != nullptr) {
3112 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
3113 if (klass != nullptr) {
3114 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003115 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07003116 result = DefineClass(self,
3117 descriptor,
3118 hash,
3119 ScopedNullHandle<mirror::ClassLoader>(),
3120 *pair.first,
3121 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003122 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07003123 if (result == nullptr) {
3124 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003125 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07003126 }
3127 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07003128 return result;
3129}
Andreas Gampef865ea92015-04-13 22:14:19 -07003130
Calin Juravle415dc3d2017-06-28 11:03:12 -07003131ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
3132 ScopedObjectAccessAlreadyRunnable& soa,
3133 const char* descriptor,
3134 size_t hash,
3135 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00003136 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
3137 IsInMemoryDexClassLoader(soa, class_loader) ||
3138 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07003139 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07003140
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003141 ObjPtr<mirror::Class> ret;
3142 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003143 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003144 if (dex_class_def != nullptr) {
3145 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
3146 descriptor,
3147 hash,
3148 class_loader,
3149 *cp_dex_file,
3150 *dex_class_def);
3151 if (klass == nullptr) {
3152 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003153 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003154 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00003155 } else {
3156 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003157 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003158 ret = klass;
3159 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003160 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003161 return true; // Continue with the next DexFile.
3162 };
3163
3164 VisitClassLoaderDexFiles(soa, class_loader, define_class);
3165 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003166}
3167
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003168ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
3169 const char* descriptor,
3170 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08003171 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08003172 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003173 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07003174 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003175 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003176 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
3177 // for primitive classes that aren't backed by dex files.
3178 return FindPrimitiveClass(descriptor[0]);
3179 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003180 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003181 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003182 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07003183 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003184 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003185 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003186 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003187 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003188 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003189 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07003190 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003191 return DefineClass(self,
3192 descriptor,
3193 hash,
3194 ScopedNullHandle<mirror::ClassLoader>(),
3195 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07003196 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07003197 } else {
3198 // The boot class loader is searched ahead of the application class loader, failures are
3199 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
3200 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003201 ObjPtr<mirror::Throwable> pre_allocated =
3202 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003203 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07003204 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05003205 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003206 }
3207 ObjPtr<mirror::Class> result_ptr;
3208 bool descriptor_equals;
3209 if (descriptor[0] == '[') {
3210 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
3211 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
3212 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
3213 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05003214 } else {
Ian Rogers98379392014-02-24 16:53:16 -08003215 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003216 bool known_hierarchy =
3217 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
3218 if (result_ptr != nullptr) {
3219 // The chain was understood and we found the class. We still need to add the class to
3220 // the class table to protect from racy programs that can try and redefine the path list
3221 // which would change the Class<?> returned for subsequent evaluation of const-class.
3222 DCHECK(known_hierarchy);
3223 DCHECK(result_ptr->DescriptorEquals(descriptor));
3224 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003225 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003226 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00003227 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
3228 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003229 //
3230 // If the chain was understood but we did not find the class, let the Java-side
3231 // rediscover all this and throw the exception with the right stack trace. Note that
3232 // the Java-side could still succeed for racy programs if another thread is actively
3233 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07003234
Alex Light185a4612018-10-04 15:54:25 -07003235 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07003236 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00003237 // Oops, we can't call into java so we can't run actual class-loader code.
3238 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003239 ObjPtr<mirror::Throwable> pre_allocated =
3240 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3241 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003242 return nullptr;
3243 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003244
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003245 // Inlined DescriptorToDot(descriptor) with extra validation.
3246 //
3247 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
3248 // the DescriptorEquals() check below and give a confusing error message. For example,
3249 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
3250 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
3251 // "class loader [...] returned class java.lang.String instead of java.lang.String".
3252 size_t descriptor_length = strlen(descriptor);
3253 if (UNLIKELY(descriptor[0] != 'L') ||
3254 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
3255 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
3256 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
3257 return nullptr;
3258 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003259
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003260 std::string class_name_string(descriptor + 1, descriptor_length - 2);
3261 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00003262 if (known_hierarchy &&
3263 fast_class_not_found_exceptions_ &&
3264 !Runtime::Current()->IsJavaDebuggable()) {
3265 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
3266 // debuggable, optimize this path by throwing directly here without going back to Java
3267 // language. This reduces how many ClassNotFoundExceptions happen.
3268 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
3269 "%s",
3270 class_name_string.c_str());
3271 } else {
3272 ScopedLocalRef<jobject> class_loader_object(
3273 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
3274 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
3275 {
3276 ScopedThreadStateChange tsc(self, kNative);
3277 ScopedLocalRef<jobject> class_name_object(
3278 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
3279 if (class_name_object.get() == nullptr) {
3280 DCHECK(self->IsExceptionPending()); // OOME.
3281 return nullptr;
3282 }
3283 CHECK(class_loader_object.get() != nullptr);
3284 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
3285 WellKnownClasses::java_lang_ClassLoader_loadClass,
3286 class_name_object.get()));
3287 }
3288 if (result.get() == nullptr && !self->IsExceptionPending()) {
3289 // broken loader - throw NPE to be compatible with Dalvik
3290 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
3291 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003292 return nullptr;
3293 }
Andreas Gampe87658f32019-04-18 18:39:02 +00003294 result_ptr = soa.Decode<mirror::Class>(result.get());
3295 // Check the name of the returned class.
3296 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003297 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003298 } else {
3299 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003300 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003301 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003302
3303 if (self->IsExceptionPending()) {
3304 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3305 // However, to comply with the RI behavior, first check if another thread succeeded.
3306 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3307 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3308 self->ClearException();
3309 return EnsureResolved(self, descriptor, result_ptr);
3310 }
3311 return nullptr;
3312 }
3313
3314 // Try to insert the class to the class table, checking for mismatch.
3315 ObjPtr<mirror::Class> old;
3316 {
3317 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3318 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3319 old = class_table->Lookup(descriptor, hash);
3320 if (old == nullptr) {
3321 old = result_ptr; // For the comparison below, after releasing the lock.
3322 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003323 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003324 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003325 } // else throw below, after releasing the lock.
3326 }
3327 }
3328 if (UNLIKELY(old != result_ptr)) {
3329 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3330 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003331 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003332 const char* loader_class_name =
3333 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3334 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3335 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3336 << DescriptorToDot(descriptor) << "\").";
3337 return EnsureResolved(self, descriptor, old);
3338 }
3339 if (UNLIKELY(!descriptor_equals)) {
3340 std::string result_storage;
3341 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3342 std::string loader_storage;
3343 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3344 ThrowNoClassDefFoundError(
3345 "Initiating class loader of type %s returned class %s instead of %s.",
3346 DescriptorToDot(loader_class_name).c_str(),
3347 DescriptorToDot(result_name).c_str(),
3348 DescriptorToDot(descriptor).c_str());
3349 return nullptr;
3350 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003351 // Success.
3352 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003353}
3354
Vladimir Markob9c29f62019-03-20 14:22:51 +00003355static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3356 std::string_view descriptor_sv(descriptor);
Vladimir Marko29885b32019-04-03 10:09:26 +01003357 return
3358 // Reserved conscrypt packages (includes sub-packages under these paths).
3359 StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3360 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/") ||
3361 // Reserved updatable-media package (includes sub-packages under this path).
3362 StartsWith(descriptor_sv, "Landroid/media/");
Vladimir Markob9c29f62019-03-20 14:22:51 +00003363}
3364
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003365ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3366 const char* descriptor,
3367 size_t hash,
3368 Handle<mirror::ClassLoader> class_loader,
3369 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003370 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003371 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003372 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003373
Brian Carlstromaded5f72011-10-07 17:15:04 -07003374 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003375 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003376 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003377 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003378 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003379 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003380 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003381 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003382 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003383 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003384 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003385 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003386 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003387 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003388 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003389 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003390 }
3391
Vladimir Markob9c29f62019-03-20 14:22:51 +00003392 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3393 // some runtime modules. Prevent definition of classes in app class loader that could clash
3394 // with these modules as these classes could be resolved differently during execution.
3395 if (class_loader != nullptr &&
3396 Runtime::Current()->IsAotCompiler() &&
3397 IsReservedBootClassPathDescriptor(descriptor)) {
3398 ObjPtr<mirror::Throwable> pre_allocated =
3399 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3400 self->SetException(pre_allocated);
3401 return nullptr;
3402 }
3403
Alex Lighte9f61032018-09-24 16:04:51 -07003404 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3405 // code to be executed. We put it up here so we can avoid all the allocations associated with
3406 // creating the class. This can happen with (eg) jit threads.
3407 if (!self->CanLoadClasses()) {
3408 // Make sure we don't try to load anything, potentially causing an infinite loop.
3409 ObjPtr<mirror::Throwable> pre_allocated =
3410 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3411 self->SetException(pre_allocated);
3412 return nullptr;
3413 }
3414
Andreas Gampefa4333d2017-02-14 11:10:34 -08003415 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003416 // Allocate a class with the status of not ready.
3417 // Interface object should get the right size here. Regular class will
3418 // figure out the right size later and be replaced with one of the right
3419 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003420 if (CanAllocClass()) {
3421 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3422 } else {
3423 return nullptr;
3424 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003425 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003426 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003427 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003428 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003429 }
Alex Lightb0f11922017-01-23 14:25:17 -08003430 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3431 // nothing.
3432 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003433 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003434 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3435 // will only be called once.
3436 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3437 klass,
3438 class_loader,
3439 dex_file,
3440 dex_class_def,
3441 &new_dex_file,
3442 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003443 // Check to see if an exception happened during runtime callbacks. Return if so.
3444 if (self->IsExceptionPending()) {
3445 return nullptr;
3446 }
Alex Lightb0f11922017-01-23 14:25:17 -08003447 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003448 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003449 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003450 return nullptr;
3451 }
3452 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003453 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003454
Jeff Hao848f70a2014-01-15 13:49:50 -08003455 // Mark the string class by setting its access flag.
3456 if (UNLIKELY(!init_done_)) {
3457 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3458 klass->SetStringClass();
3459 }
3460 }
3461
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003462 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003463 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003464 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003465 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003466
Mathieu Chartier590fee92013-09-13 13:46:47 -07003467 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003468 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003469 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003470 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3471 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003472 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003473 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003474
Mathieu Chartierc7853442015-03-27 14:35:38 -07003475 // Load the fields and other things after we are inserted in the table. This is so that we don't
3476 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3477 // other reason is that the field roots are only visited from the class table. So we need to be
3478 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003479 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003480 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003481 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003482 // An exception occured during load, set status to erroneous while holding klass' lock in case
3483 // notification is necessary.
3484 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003485 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003486 }
3487 return nullptr;
3488 }
3489
Brian Carlstromaded5f72011-10-07 17:15:04 -07003490 // Finish loading (if necessary) by finding parents
3491 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003492 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003493 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003494 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003495 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003496 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003497 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003498 }
3499 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003500
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003501 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003502 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003503 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003504
Brian Carlstromaded5f72011-10-07 17:15:04 -07003505 // Link the class (if necessary)
3506 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003507 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003508 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003509
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003510 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003511 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003512 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003513 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003514 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003515 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003516 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003517 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003518 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003519 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003520 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003521
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003522 // Instrumentation may have updated entrypoints for all methods of all
3523 // classes. However it could not update methods of this class while we
3524 // were loading it. Now the class is resolved, we can update entrypoints
3525 // as required by instrumentation.
3526 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3527 // We must be in the kRunnable state to prevent instrumentation from
3528 // suspending all threads to update entrypoints while we are doing it
3529 // for this class.
3530 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003531 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003532 }
3533
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003534 /*
3535 * We send CLASS_PREPARE events to the debugger from here. The
3536 * definition of "preparation" is creating the static fields for a
3537 * class and initializing them to the standard default values, but not
3538 * executing any code (that comes later, during "initialization").
3539 *
3540 * We did the static preparation in LinkClass.
3541 *
3542 * The class has been prepared and resolved but possibly not yet verified
3543 * at this point.
3544 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003545 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003546
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003547 // Notify native debugger of the new class and its layout.
3548 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3549
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003550 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003551}
3552
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003553uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003554 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003555 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003556 size_t num_8 = 0;
3557 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003558 size_t num_32 = 0;
3559 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003560 ClassAccessor accessor(dex_file, dex_class_def);
3561 // We allow duplicate definitions of the same field in a class_data_item
3562 // but ignore the repeated indexes here, b/21868015.
3563 uint32_t last_field_idx = dex::kDexNoIndex;
3564 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3565 uint32_t field_idx = field.GetIndex();
3566 // Ordering enforced by DexFileVerifier.
3567 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3568 if (UNLIKELY(field_idx == last_field_idx)) {
3569 continue;
3570 }
3571 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003572 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003573 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3574 char c = descriptor[0];
3575 switch (c) {
3576 case 'L':
3577 case '[':
3578 num_ref++;
3579 break;
3580 case 'J':
3581 case 'D':
3582 num_64++;
3583 break;
3584 case 'I':
3585 case 'F':
3586 num_32++;
3587 break;
3588 case 'S':
3589 case 'C':
3590 num_16++;
3591 break;
3592 case 'B':
3593 case 'Z':
3594 num_8++;
3595 break;
3596 default:
3597 LOG(FATAL) << "Unknown descriptor: " << c;
3598 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003599 }
3600 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003601 return mirror::Class::ComputeClassSize(false,
3602 0,
3603 num_8,
3604 num_16,
3605 num_32,
3606 num_64,
3607 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003608 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003609}
3610
Alex Lightfc49fec2018-01-16 22:28:36 +00003611// Special case to get oat code without overwriting a trampoline.
3612const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003613 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003614 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003615 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003616 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003617 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003618 if (code != nullptr) {
3619 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003620 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003621
3622 jit::Jit* jit = Runtime::Current()->GetJit();
3623 if (jit != nullptr) {
3624 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3625 if (code != nullptr) {
3626 return code;
3627 }
3628 }
3629
Alex Lightfc49fec2018-01-16 22:28:36 +00003630 if (method->IsNative()) {
3631 // No code and native? Use generic trampoline.
3632 return GetQuickGenericJniStub();
3633 }
3634 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003635}
3636
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003637bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003638 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003639 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3640 return false;
3641 }
3642
Elliott Hughes956af0f2014-12-11 14:34:28 -08003643 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003644 return true;
3645 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003646
3647 Runtime* runtime = Runtime::Current();
3648 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3649 if (instr->InterpretOnly()) {
3650 return true;
3651 }
3652
3653 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3654 // Doing this check avoids doing compiled/interpreter transitions.
3655 return true;
3656 }
3657
Alex Light3dacdd62019-03-12 15:45:47 +00003658 if (Thread::Current()->IsForceInterpreter() ||
3659 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003660 // Force the use of interpreter when it is required by the debugger.
3661 return true;
3662 }
3663
Alex Light8f34aba2017-10-09 13:46:32 -07003664 if (Thread::Current()->IsAsyncExceptionPending()) {
3665 // Force use of interpreter to handle async-exceptions
3666 return true;
3667 }
3668
Alex Light2d441b12018-06-08 15:33:21 -07003669 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3670 const void* instr_target = instr->GetCodeForInvoke(method);
3671 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3672 return ShouldUseInterpreterEntrypoint(method, instr_target);
3673 }
3674
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003675 if (runtime->IsJavaDebuggable()) {
3676 // For simplicity, we ignore precompiled code and go to the interpreter
3677 // assuming we don't already have jitted code.
3678 // We could look at the oat file where `quick_code` is being defined,
3679 // and check whether it's been compiled debuggable, but we decided to
3680 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003681 jit::Jit* jit = Runtime::Current()->GetJit();
3682 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3683 }
3684
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003685 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003686 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003687 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003688 // since we want to JIT it (at first use) with extra stackmaps for native
3689 // debugging. We keep however all AOT code from the boot image,
3690 // since the JIT-at-first-use is blocking and would result in non-negligible
3691 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003692 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003693 }
3694
3695 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003696}
3697
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003698void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003699 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003700 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003701 if (klass->NumDirectMethods() == 0) {
3702 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003703 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003704 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003705 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003706 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003707 return; // OAT file unavailable.
3708 }
Ian Rogers19846512012-02-24 11:42:47 -08003709 }
Alex Light64ad14d2014-08-19 14:23:13 -07003710
Mathieu Chartierf8322842014-05-16 10:59:25 -07003711 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003712 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3713 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3714 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003715 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003716 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003717 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003718 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3719 klass->GetDexClassDefIndex(),
3720 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003721 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003722 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003723 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003724 if (!method->IsStatic()) {
3725 // Only update static methods.
3726 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003727 }
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01003728 if (!IsQuickResolutionStub(method->GetEntryPointFromQuickCompiledCode())) {
3729 // Only update methods whose entrypoint is the resolution stub.
3730 continue;
3731 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003732 const void* quick_code = nullptr;
3733 if (has_oat_class) {
3734 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003735 quick_code = oat_method.GetQuickCode();
3736 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003737 // Check if we have JIT compiled code for it.
Nicolas Geoffray32384402019-07-17 20:06:44 +01003738 jit::Jit* jit = Runtime::Current()->GetJit();
3739 if (quick_code == nullptr && jit != nullptr) {
3740 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003741 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003742 // Check whether the method is native, in which case it's generic JNI.
3743 if (quick_code == nullptr && method->IsNative()) {
3744 quick_code = GetQuickGenericJniStub();
3745 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003746 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003747 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003748 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003749 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003750 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003751 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003752}
3753
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003754// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3755// method. Should only be called on non-invokable methods.
3756inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003757 DCHECK(method != nullptr);
3758 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003759 method->SetEntryPointFromQuickCompiledCodePtrSize(
3760 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3761 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003762}
3763
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003764static void LinkCode(ClassLinker* class_linker,
3765 ArtMethod* method,
3766 const OatFile::OatClass* oat_class,
3767 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003768 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003769 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003770 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003771 // The following code only applies to a non-compiler runtime.
3772 return;
3773 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003774
Ian Rogers62d6c772013-02-27 08:32:07 -08003775 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003776 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003777
Alex Light9139e002015-10-09 15:59:48 -07003778 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003779 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003780 return;
3781 }
Ian Rogers19846512012-02-24 11:42:47 -08003782
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003783 const void* quick_code = nullptr;
3784 if (oat_class != nullptr) {
3785 // Every kind of method should at least get an invoke stub from the oat_method.
3786 // non-abstract methods also get their code pointers.
3787 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3788 quick_code = oat_method.GetQuickCode();
3789 }
3790
3791 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3792
3793 // Note: this mimics the logic in image_writer.cc that installs the resolution
3794 // stub only if we have compiled code and the method needs a class initialization
3795 // check.
3796 if (quick_code == nullptr) {
3797 method->SetEntryPointFromQuickCompiledCode(
3798 method->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge());
3799 } else if (enter_interpreter) {
3800 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
3801 } else if (method->NeedsInitializationCheck()) {
3802 // If there is compiled code, and the method needs to make sure the class is
3803 // initialized before execution, install the resolution stub.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003804 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3805 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003806 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003807 } else {
3808 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003809 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003810
Ian Rogers62d6c772013-02-27 08:32:07 -08003811 if (method->IsNative()) {
3812 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003813 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003814
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003815 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003816 // We have a native method here without code. Then it should have the generic JNI
3817 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003818 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003819 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003820 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003821 }
3822}
3823
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003824void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003825 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003826 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003827 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003828 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003829 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003830 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003831 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003832 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003833
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003834 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003835 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003836 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003837 klass->SetAccessFlags(access_flags);
3838 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003839 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003840 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003841
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003842 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003843 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003844}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003845
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003846LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3847 LinearAlloc* allocator,
3848 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003849 if (length == 0) {
3850 return nullptr;
3851 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003852 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3853 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3854 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003855 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003856 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003857 CHECK(ret != nullptr);
3858 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3859 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003860}
3861
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003862LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3863 LinearAlloc* allocator,
3864 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003865 if (length == 0) {
3866 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003867 }
Vladimir Marko14632852015-08-17 12:07:23 +01003868 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3869 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003870 const size_t storage_size =
3871 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003872 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003873 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003874 CHECK(ret != nullptr);
3875 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003876 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003877 }
3878 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003879}
3880
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003881LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003882 if (class_loader == nullptr) {
3883 return Runtime::Current()->GetLinearAlloc();
3884 }
3885 LinearAlloc* allocator = class_loader->GetAllocator();
3886 DCHECK(allocator != nullptr);
3887 return allocator;
3888}
3889
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003890LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003891 if (class_loader == nullptr) {
3892 return Runtime::Current()->GetLinearAlloc();
3893 }
3894 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3895 LinearAlloc* allocator = class_loader->GetAllocator();
3896 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003897 RegisterClassLoader(class_loader);
3898 allocator = class_loader->GetAllocator();
3899 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003900 }
3901 return allocator;
3902}
3903
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003904void ClassLinker::LoadClass(Thread* self,
3905 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003906 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003907 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003908 ClassAccessor accessor(dex_file,
3909 dex_class_def,
3910 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003911 if (!accessor.HasClassData()) {
3912 return;
3913 }
3914 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003915 {
3916 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3917 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003918 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003919 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003920 // We allow duplicate definitions of the same field in a class_data_item
3921 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003922 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003923 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3924 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003925 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003926 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3927 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003928 accessor.NumInstanceFields());
3929 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003930 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003931 uint32_t last_static_field_idx = 0u;
3932 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003933
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003934 // Methods
3935 bool has_oat_class = false;
3936 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3937 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3938 : OatFile::OatClass::Invalid();
3939 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3940 klass->SetMethodsPtr(
3941 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3942 accessor.NumDirectMethods(),
3943 accessor.NumVirtualMethods());
3944 size_t class_def_method_index = 0;
3945 uint32_t last_dex_method_index = dex::kDexNoIndex;
3946 size_t last_class_def_method_index = 0;
3947
3948 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3949 // methods needs to decode all of the fields.
3950 accessor.VisitFieldsAndMethods([&](
3951 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3952 uint32_t field_idx = field.GetIndex();
3953 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3954 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3955 LoadField(field, klass, &sfields->At(num_sfields));
3956 ++num_sfields;
3957 last_static_field_idx = field_idx;
3958 }
3959 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3960 uint32_t field_idx = field.GetIndex();
3961 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3962 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3963 LoadField(field, klass, &ifields->At(num_ifields));
3964 ++num_ifields;
3965 last_instance_field_idx = field_idx;
3966 }
3967 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3968 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3969 image_pointer_size_);
3970 LoadMethod(dex_file, method, klass, art_method);
3971 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3972 uint32_t it_method_index = method.GetIndex();
3973 if (last_dex_method_index == it_method_index) {
3974 // duplicate case
3975 art_method->SetMethodIndex(last_class_def_method_index);
3976 } else {
3977 art_method->SetMethodIndex(class_def_method_index);
3978 last_dex_method_index = it_method_index;
3979 last_class_def_method_index = class_def_method_index;
3980 }
3981 ++class_def_method_index;
3982 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3983 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3984 class_def_method_index - accessor.NumDirectMethods(),
3985 image_pointer_size_);
3986 LoadMethod(dex_file, method, klass, art_method);
3987 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3988 ++class_def_method_index;
3989 });
3990
3991 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003992 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003993 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3994 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3995 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003996 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3997 if (sfields != nullptr) {
3998 sfields->SetSize(num_sfields);
3999 }
4000 if (ifields != nullptr) {
4001 ifields->SetSize(num_ifields);
4002 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004003 }
Vladimir Marko81819db2015-11-05 15:30:12 +00004004 // Set the field arrays.
4005 klass->SetSFieldsPtr(sfields);
4006 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004007 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004008 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07004009 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004010 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004011 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07004012 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07004013}
4014
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004015void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004016 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07004017 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004018 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004019 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004020 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00004021
David Brazdil85865692018-10-30 17:26:20 +00004022 // Get access flags from the DexFile and set hiddenapi runtime access flags.
4023 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07004024}
4025
Mathieu Chartier268764d2016-09-13 12:09:38 -07004026void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004027 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004028 Handle<mirror::Class> klass,
4029 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004030 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004031 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07004032 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07004033
Mathieu Chartier268764d2016-09-13 12:09:38 -07004034 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07004035 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004036 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004037 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07004038
David Brazdil85865692018-10-30 17:26:20 +00004039 // Get access flags from the DexFile and set hiddenapi runtime access flags.
4040 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00004041
Ian Rogersdfb325e2013-10-30 01:00:44 -07004042 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07004043 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004044 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
4045 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004046 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004047 klass->SetFinalizable();
4048 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004049 std::string temp;
4050 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07004051 // The Enum class declares a "final" finalize() method to prevent subclasses from
4052 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
4053 // subclasses, so we exclude it here.
4054 // We also want to avoid setting the flag on Object, where we know that finalize() is
4055 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07004056 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
4057 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07004058 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07004059 }
4060 }
4061 }
4062 } else if (method_name[0] == '<') {
4063 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004064 bool is_init = (strcmp("<init>", method_name) == 0);
4065 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07004066 if (UNLIKELY(!is_init && !is_clinit)) {
4067 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
4068 } else {
4069 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
4070 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07004071 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07004072 access_flags |= kAccConstructor;
4073 }
4074 }
4075 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01004076 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
4077 // Check if the native method is annotated with @FastNative or @CriticalNative.
4078 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
4079 dex_file, dst->GetClassDef(), dex_method_idx);
4080 }
Ian Rogers241b5de2013-10-09 17:58:57 -07004081 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00004082 // Must be done after SetAccessFlags since IsAbstract depends on it.
4083 if (klass->IsInterface() && dst->IsAbstract()) {
4084 dst->CalculateAndSetImtIndex();
4085 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07004086}
4087
Ian Rogers7b078e82014-09-10 14:44:24 -07004088void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004089 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004090 self,
4091 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004092 Runtime::Current()->GetLinearAlloc());
4093 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07004094 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07004095}
4096
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004097void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004098 ObjPtr<mirror::DexCache> dex_cache) {
4099 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004100 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07004101 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004102 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004103}
4104
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004105void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004106 ObjPtr<mirror::DexCache> dex_cache,
4107 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004108 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08004109 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00004110 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004111 // For app images, the dex cache location may be a suffix of the dex file location since the
4112 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08004113 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
4114 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004115 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
4116 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00004117 // The following paths checks don't work on preopt when using boot dex files, where the dex
4118 // cache location is the one on device, and the dex_file's location is the one on host.
4119 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
4120 CHECK_GE(dex_file_location.length(), dex_cache_length)
4121 << dex_cache_location << " " << dex_file.GetLocation();
4122 const std::string dex_file_suffix = dex_file_location.substr(
4123 dex_file_location.length() - dex_cache_length,
4124 dex_cache_length);
4125 // Example dex_cache location is SettingsProvider.apk and
4126 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
4127 CHECK_EQ(dex_cache_location, dex_file_suffix);
4128 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004129 const OatFile* oat_file =
4130 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00004131 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
4132 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
4133 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
4134 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08004135 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004136 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
4137 DexCacheData data = *it;
4138 if (self->IsJWeakCleared(data.weak_root)) {
4139 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004140 it = dex_caches_.erase(it);
4141 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00004142 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004143 it->dex_file->GetOatDexFile() != nullptr &&
4144 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00004145 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004146 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004147 ++it;
4148 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004149 }
Vladimir Markob066d432018-01-03 13:14:37 +00004150 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00004151 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004152 }
David Brazdila5c3a802019-03-08 14:59:41 +00004153 // Let hiddenapi assign a domain to the newly registered dex file.
4154 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
4155
Vladimir Markocd556b02017-02-03 11:47:34 +00004156 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004157 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004158 DexCacheData data;
4159 data.weak_root = dex_cache_jweak;
4160 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00004161 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00004162 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00004163 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004164 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
4165 // path dex caches without an image.
4166 data.class_table->InsertStrongRoot(dex_cache);
4167 if (class_loader != nullptr) {
4168 // Since we added a strong root to the class table, do the write barrier as required for
4169 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004170 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004171 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004172 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004173}
4174
Vladimir Markocd556b02017-02-03 11:47:34 +00004175ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
4176 return data.IsValid()
4177 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
4178 : nullptr;
4179}
4180
4181ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
4182 Thread* self,
4183 ObjPtr<mirror::DexCache> dex_cache,
4184 const DexCacheData& data,
4185 ObjPtr<mirror::ClassLoader> class_loader) {
4186 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
4187 if (data.class_table != ClassTableForClassLoader(class_loader)) {
4188 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
4189 "Attempt to register dex file %s with multiple class loaders",
4190 data.dex_file->GetLocation().c_str());
4191 return nullptr;
4192 }
4193 return dex_cache;
4194}
4195
Alex Light07f06212017-06-01 14:01:43 -07004196void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
4197 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004198 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07004199 Thread* self = Thread::Current();
4200 StackHandleScope<2> hs(self);
4201 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
4202 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
4203 const DexFile* dex_file = dex_cache->GetDexFile();
4204 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
4205 if (kIsDebugBuild) {
4206 DexCacheData old_data;
4207 {
4208 ReaderMutexLock mu(self, *Locks::dex_lock_);
4209 old_data = FindDexCacheDataLocked(*dex_file);
4210 }
4211 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
4212 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
4213 << "been registered on dex file " << dex_file->GetLocation();
4214 }
4215 ClassTable* table;
4216 {
4217 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4218 table = InsertClassTableForClassLoader(h_class_loader.Get());
4219 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004220 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4221 // a thread holding the dex lock and blocking on a condition variable regarding
4222 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004223 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07004224 WriterMutexLock mu(self, *Locks::dex_lock_);
4225 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
4226 table->InsertStrongRoot(h_dex_cache.Get());
4227 if (h_class_loader.Get() != nullptr) {
4228 // Since we added a strong root to the class table, do the write barrier as required for
4229 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004230 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004231 }
4232}
4233
Vladimir Markocd556b02017-02-03 11:47:34 +00004234ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4235 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004236 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00004237 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004238 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004239 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004240 old_data = FindDexCacheDataLocked(dex_file);
4241 }
4242 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
4243 if (old_dex_cache != nullptr) {
4244 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07004245 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004246 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004247 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4248 DCHECK(linear_alloc != nullptr);
4249 ClassTable* table;
4250 {
4251 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4252 table = InsertClassTableForClassLoader(class_loader);
4253 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004254 // Don't alloc while holding the lock, since allocation may need to
4255 // suspend all threads and another thread may need the dex_lock_ to
4256 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004257 StackHandleScope<3> hs(self);
4258 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004259 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07004260 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
4261 self,
4262 dex_file)));
4263 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004264 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004265 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4266 // a thread holding the dex lock and blocking on a condition variable regarding
4267 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004268 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004269 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004270 old_data = FindDexCacheDataLocked(dex_file);
4271 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004272 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004273 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
4274 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
4275 // that the arrays are null.
4276 mirror::DexCache::InitializeDexCache(self,
4277 h_dex_cache.Get(),
4278 h_location.Get(),
4279 &dex_file,
4280 linear_alloc,
4281 image_pointer_size_);
4282 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004283 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004284 }
4285 if (old_dex_cache != nullptr) {
4286 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4287 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004288 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00004289 self->ClearException();
4290 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
4291 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
4292 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004293 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004294 self->AssertPendingOOMException();
4295 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004296 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004297 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004298 if (h_class_loader.Get() != nullptr) {
4299 // Since we added a strong root to the class table, do the write barrier as required for
4300 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004301 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004302 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004303 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004304}
4305
Vladimir Markocd556b02017-02-03 11:47:34 +00004306bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004307 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004308 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004309}
4310
Vladimir Markocd556b02017-02-03 11:47:34 +00004311ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4312 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004313 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
4314 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004315 if (dex_cache != nullptr) {
4316 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004317 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004318 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004319 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004320 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004321 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004322 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004323 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004324 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
4325 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004326 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004327}
4328
Vladimir Markocd556b02017-02-03 11:47:34 +00004329ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4330 const DexFile* dex_file = dex_cache->GetDexFile();
4331 DCHECK(dex_file != nullptr);
4332 ReaderMutexLock mu(self, *Locks::dex_lock_);
4333 // Search assuming unique-ness of dex file.
4334 for (const DexCacheData& data : dex_caches_) {
4335 // Avoid decoding (and read barriers) other unrelated dex caches.
4336 if (data.dex_file == dex_file) {
4337 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
4338 if (registered_dex_cache != nullptr) {
4339 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4340 return data.class_table;
4341 }
4342 }
4343 }
4344 return nullptr;
4345}
4346
4347ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
4348 // Search assuming unique-ness of dex file.
4349 for (const DexCacheData& data : dex_caches_) {
4350 // Avoid decoding (and read barriers) other unrelated dex caches.
4351 if (data.dex_file == &dex_file) {
4352 return data;
4353 }
4354 }
4355 return DexCacheData();
4356}
4357
Vladimir Marko70e2a762019-07-12 16:49:00 +01004358void ClassLinker::CreatePrimitiveClass(Thread* self,
4359 Primitive::Type type,
4360 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004361 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004362 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004363 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4364 // Do not hold lock on the primitive class object, the initialization of
4365 // primitive classes is done while the process is still single threaded.
4366 primitive_class->SetAccessFlags(
4367 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4368 primitive_class->SetPrimitiveType(type);
4369 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4370 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4371 // the kAccVerificationAttempted flag was added above, and there are no
4372 // methods that need the kAccSkipAccessChecks flag.
4373 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004374 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4375 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004376 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004377 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004378 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004379 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004380 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004381 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004382}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004383
Vladimir Marko02610552018-06-04 14:38:00 +01004384inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4385 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4386}
4387
Brian Carlstrombe977852011-07-19 14:54:54 -07004388// Create an array class (i.e. the class object for the array, not the
4389// array itself). "descriptor" looks like "[C" or "[[[[B" or
4390// "[Ljava/lang/String;".
4391//
4392// If "descriptor" refers to an array of primitives, look up the
4393// primitive type's internally-generated class object.
4394//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004395// "class_loader" is the class loader of the class that's referring to
4396// us. It's used to ensure that we're looking for the element type in
4397// the right context. It does NOT become the class loader for the
4398// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004399//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004400// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004401ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4402 const char* descriptor,
4403 size_t hash,
4404 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004405 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004406 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004407 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004408
4409 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4410 // code to be executed. We put it up here so we can avoid all the allocations associated with
4411 // creating the class. This can happen with (eg) jit threads.
4412 if (!self->CanLoadClasses()) {
4413 // Make sure we don't try to load anything, potentially causing an infinite loop.
4414 ObjPtr<mirror::Throwable> pre_allocated =
4415 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4416 self->SetException(pre_allocated);
4417 return nullptr;
4418 }
4419
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004420 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4421 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004422 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004423 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004424 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004425 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4426 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004427 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004428 DCHECK(self->IsExceptionPending());
4429 return nullptr;
4430 } else {
4431 self->ClearException();
4432 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004433 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004434 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4435 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4436 return nullptr;
4437 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004438 // See if the component type is already loaded. Array classes are
4439 // always associated with the class loader of their underlying
4440 // element type -- an array of Strings goes with the loader for
4441 // java/lang/String -- so we need to look for it there. (The
4442 // caller should have checked for the existence of the class
4443 // before calling here, but they did so with *their* class loader,
4444 // not the component type's loader.)
4445 //
4446 // If we find it, the caller adds "loader" to the class' initiating
4447 // loader list, which should prevent us from going through this again.
4448 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004449 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004450 // are the same, because our caller (FindClass) just did the
4451 // lookup. (Even if we get this wrong we still have correct behavior,
4452 // because we effectively do this lookup again when we add the new
4453 // class to the hash table --- necessary because of possible races with
4454 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004455 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004456 ObjPtr<mirror::Class> new_class =
4457 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004458 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004459 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004460 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004461 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004462 // Core array classes, i.e. Object[], Class[], String[] and primitive
4463 // arrays, have special initialization and they should be found above.
4464 DCHECK(!component_type->IsObjectClass() ||
4465 // Guard from false positives for errors before setting superclass.
4466 component_type->IsErroneousUnresolved());
4467 DCHECK(!component_type->IsStringClass());
4468 DCHECK(!component_type->IsClassClass());
4469 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004470
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004471 // Fill out the fields in the Class.
4472 //
4473 // It is possible to execute some methods against arrays, because
4474 // all arrays are subclasses of java_lang_Object_, so we need to set
4475 // up a vtable. We can just point at the one in java_lang_Object_.
4476 //
4477 // Array classes are simple enough that we don't need to do a full
4478 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004479 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4480 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4481 size_t usable_size)
4482 REQUIRES_SHARED(Locks::mutator_lock_) {
4483 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4484 init_class(obj, usable_size);
4485 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4486 klass->SetComponentType(component_type.Get());
4487 // Do not hold lock for initialization, the fence issued after the visitor
4488 // returns ensures memory visibility together with the implicit consume
4489 // semantics (for all supported architectures) for any thread that loads
4490 // the array class reference from any memory locations afterwards.
4491 FinishArrayClassSetup(klass);
4492 };
4493 auto new_class = hs.NewHandle<mirror::Class>(
4494 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004495 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004496 self->AssertPendingOOMException();
4497 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004498 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004499
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004500 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004501 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004502 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4503 // duplicate events in case of races. Array classes don't really follow dedicated
4504 // load and prepare, anyways.
4505 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4506 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4507
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004508 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004509 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004510 }
4511 // Another thread must have loaded the class after we
4512 // started but before we finished. Abandon what we've
4513 // done.
4514 //
4515 // (Yes, this happens.)
4516
Vladimir Markobcf17522018-06-01 13:14:32 +01004517 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004518}
4519
Vladimir Marko9186b182018-11-06 14:55:54 +00004520ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4521 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004522 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004523 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4524 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4525 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4526 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4527 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4528 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4529 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4530 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4531 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004532 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004533 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004534 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004535 return GetClassRoot(class_root, this);
4536}
4537
4538ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4539 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4540 if (UNLIKELY(result == nullptr)) {
4541 std::string printable_type(PrintableChar(type));
4542 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4543 }
4544 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004545}
4546
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004547ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4548 ObjPtr<mirror::Class> klass,
4549 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004550 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004551 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004552 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004553 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004554 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004555 source += " from ";
4556 source += dex_cache->GetLocation()->ToModifiedUtf8();
4557 }
4558 LOG(INFO) << "Loaded class " << descriptor << source;
4559 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004560 {
4561 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004562 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004563 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004564 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004565 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004566 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004567 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004568 VerifyObject(klass);
4569 class_table->InsertWithHash(klass, hash);
4570 if (class_loader != nullptr) {
4571 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004572 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004573 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004574 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004575 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004576 }
4577 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004578 if (kIsDebugBuild) {
4579 // Test that copied methods correctly can find their holder.
4580 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4581 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4582 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004583 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004584 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004585}
4586
Vladimir Marko1998cd02017-01-13 13:02:58 +00004587void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004588 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4589 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4590 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4591 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004592 }
4593}
4594
Alex Lighte64300b2015-12-15 15:02:47 -08004595// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004596void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004597 LengthPrefixedArray<ArtMethod>* new_methods) {
4598 klass->SetMethodsPtrUnchecked(new_methods,
4599 klass->NumDirectMethods(),
4600 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004601 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004602 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004603}
4604
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004605ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4606 const char* descriptor,
4607 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004608 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4609}
4610
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004611ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4612 const char* descriptor,
4613 size_t hash,
4614 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004615 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4616 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4617 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004618 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004619 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004620 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004621 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004622 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004623 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004624}
4625
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004626class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4627 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004628 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004629
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004630 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004631 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004632 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004633 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004634 if (class_table != nullptr) {
4635 class_table->FreezeSnapshot();
4636 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004637 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004638};
4639
4640void ClassLinker::MoveClassTableToPreZygote() {
4641 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004642 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004643 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004644 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004645}
4646
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004647// Look up classes by hash and descriptor and put all matching ones in the result array.
4648class LookupClassesVisitor : public ClassLoaderVisitor {
4649 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004650 LookupClassesVisitor(const char* descriptor,
4651 size_t hash,
4652 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004653 : descriptor_(descriptor),
4654 hash_(hash),
4655 result_(result) {}
4656
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004657 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004658 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004659 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004660 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004661 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4662 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004663 result_->push_back(klass);
4664 }
4665 }
4666
4667 private:
4668 const char* const descriptor_;
4669 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004670 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004671};
4672
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004673void ClassLinker::LookupClasses(const char* descriptor,
4674 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004675 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004676 Thread* const self = Thread::Current();
4677 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004678 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004679 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004680 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004681 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004682 result.push_back(klass);
4683 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004684 LookupClassesVisitor visitor(descriptor, hash, &result);
4685 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004686}
4687
Alex Lightf1f10492015-10-07 16:08:36 -07004688bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4689 Handle<mirror::Class> klass,
4690 Handle<mirror::Class> supertype) {
4691 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004692 DCHECK(klass != nullptr);
4693 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004694
Alex Lightf1f10492015-10-07 16:08:36 -07004695 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4696 VerifyClass(self, supertype);
4697 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004698
4699 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4700 // The supertype is either verified, or we soft failed at AOT time.
4701 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004702 return true;
4703 }
4704 // If we got this far then we have a hard failure.
4705 std::string error_msg =
4706 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004707 klass->PrettyDescriptor().c_str(),
4708 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004709 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004710 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004711 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004712 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004713 // Set during VerifyClass call (if at all).
4714 self->ClearException();
4715 }
4716 // Change into a verify error.
4717 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004718 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004719 self->GetException()->SetCause(cause.Get());
4720 }
4721 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4722 if (Runtime::Current()->IsAotCompiler()) {
4723 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4724 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004725 // Need to grab the lock to change status.
4726 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004727 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004728 return false;
4729}
4730
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004731verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004732 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004733 {
4734 // TODO: assert that the monitor on the Class is held
4735 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004736
Andreas Gampe884f3b82016-03-30 19:52:58 -07004737 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004738 ClassStatus old_status = klass->GetStatus();
4739 while (old_status == ClassStatus::kVerifying ||
4740 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004741 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004742 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4743 // case we may see the same status again. b/62912904. This is why the check is
4744 // greater or equal.
4745 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004746 << "Class '" << klass->PrettyClass()
4747 << "' performed an illegal verification state transition from " << old_status
4748 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004749 old_status = klass->GetStatus();
4750 }
jeffhao98eacac2011-09-14 16:11:53 -07004751
Andreas Gampe884f3b82016-03-30 19:52:58 -07004752 // The class might already be erroneous, for example at compile time if we attempted to verify
4753 // this class as a parent to another.
4754 if (klass->IsErroneous()) {
4755 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004756 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004757 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004758
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004759 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004760 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004761 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004762 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004763 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004764
4765 // For AOT, don't attempt to re-verify if we have already found we should
4766 // verify at runtime.
4767 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004768 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004769 }
jeffhao98eacac2011-09-14 16:11:53 -07004770
Vladimir Marko2c64a832018-01-04 11:31:56 +00004771 if (klass->GetStatus() == ClassStatus::kResolved) {
4772 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004773 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004774 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004775 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004776 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004777 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004778 }
4779
4780 // Skip verification if disabled.
4781 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004782 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004783 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004784 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004785 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004786 }
4787
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004788 VLOG(class_linker) << "Beginning verification for class: "
4789 << klass->PrettyDescriptor()
4790 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4791
Ian Rogers9ffb0392012-09-10 11:56:50 -07004792 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004793 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004794 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4795 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004796 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004797 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004798 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004799 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004800
Alex Lightf1f10492015-10-07 16:08:36 -07004801 // Verify all default super-interfaces.
4802 //
4803 // (1) Don't bother if the superclass has already had a soft verification failure.
4804 //
4805 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4806 // recursive initialization by themselves. This is because when an interface is initialized
4807 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4808 // but choose not to for an optimization. If the interfaces is being verified due to a class
4809 // initialization (which would need all the default interfaces to be verified) the class code
4810 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004811 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004812 && !klass->IsInterface()) { // See (2)
4813 int32_t iftable_count = klass->GetIfTableCount();
4814 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4815 // Loop through all interfaces this class has defined. It doesn't matter the order.
4816 for (int32_t i = 0; i < iftable_count; i++) {
4817 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004818 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004819 // We only care if we have default interfaces and can skip if we are already verified...
4820 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4821 continue;
4822 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4823 // We had a hard failure while verifying this interface. Just return immediately.
4824 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004825 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004826 } else if (UNLIKELY(!iface->IsVerified())) {
4827 // We softly failed to verify the iface. Stop checking and clean up.
4828 // Put the iface into the supertype handle so we know what caused us to fail.
4829 supertype.Assign(iface.Get());
4830 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004831 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004832 }
4833 }
4834
Alex Lightf1f10492015-10-07 16:08:36 -07004835 // At this point if verification failed, then supertype is the "first" supertype that failed
4836 // verification (without a specific order). If verification succeeded, then supertype is either
4837 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004838 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004839 supertype.Get() == klass->GetSuperClass() ||
4840 !supertype->IsVerified());
4841
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004842 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004843 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004844 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004845 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004846
4847 VLOG(class_linker) << "Class preverified status for class "
4848 << klass->PrettyDescriptor()
4849 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4850 << ": "
4851 << preverified;
4852
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004853 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4854 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004855 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4856 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004857
Ian Rogers62d6c772013-02-27 08:32:07 -08004858 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004859 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004860 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004861 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004862 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004863
4864 // Verification is done, grab the lock again.
4865 ObjectLock<mirror::Class> lock(self, klass);
4866
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004867 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4868 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004869 VLOG(class_linker) << "Soft verification failure in class "
4870 << klass->PrettyDescriptor()
4871 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4872 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004873 }
Ian Rogers1f539342012-10-03 21:09:42 -07004874 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004875 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004876 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004877 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004878 // Even though there were no verifier failures we need to respect whether the super-class and
4879 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004880 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004881 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004882 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004883 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4884 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004885 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004886 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004887 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004888 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004889 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004890 // Soft failures at compile time should be retried at runtime. Soft
4891 // failures at runtime will be handled by slow paths in the generated
4892 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004893 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004894 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004895 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004896 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004897 // As this is a fake verified status, make sure the methods are _not_ marked
4898 // kAccSkipAccessChecks later.
4899 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004900 }
4901 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004902 } else {
David Sehr709b0702016-10-13 09:12:37 -07004903 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004904 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4905 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004906 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004907 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004908 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004909 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004910 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004911 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004912 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004913 // method.
4914 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004915 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004916 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004917
4918 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4919 // Never skip access checks if the verification soft fail is forced.
4920 // Mark the class as having a verification attempt to avoid re-running the verifier.
4921 klass->SetVerificationAttempted();
4922 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004923 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004924 }
Andreas Gampe48498592014-09-10 19:48:05 -07004925 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004926 // Done verifying. Notify the compiler about the verification status, in case the class
4927 // was verified implicitly (eg super class of a compiled class).
4928 if (Runtime::Current()->IsAotCompiler()) {
4929 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4930 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4931 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004932 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004933}
4934
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004935verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4936 Handle<mirror::Class> klass,
4937 verifier::HardFailLogMode log_level,
4938 std::string* error_msg) {
4939 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004940 return verifier::ClassVerifier::VerifyClass(self,
4941 klass.Get(),
4942 runtime->GetCompilerCallbacks(),
4943 runtime->IsAotCompiler(),
4944 log_level,
4945 Runtime::Current()->GetTargetSdkVersion(),
4946 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004947}
4948
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004949bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004950 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004951 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004952 // If we're compiling, we can only verify the class using the oat file if
4953 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004954 // the compilation unit (app - dependencies). We will let the compiler callback
4955 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004956 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004957 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004958 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004959 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004960 return false;
4961 }
4962 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004963 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004964 return false;
4965 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004966 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004967
Andreas Gampeb40d3612018-06-26 15:49:42 -07004968 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004969 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004970 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004971 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4972 // For boot classpath classes in the case we're not using a default boot image:
4973 // we don't have the infrastructure yet to query verification data on individual
4974 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4975 // verified. This should be taken into account when measuring boot time and app
4976 // startup compare to the (current) production system where both:
4977 // 1) updatable boot classpath classes, and
4978 // 2) classes in /system referencing updatable classes
4979 // will be verified at runtime.
David Srbecky3db3d372019-04-17 18:19:17 +01004980 if (Runtime::Current()->IsUsingApexBootImageLocation()) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004981 oat_file_class_status = ClassStatus::kVerified;
4982 return true;
4983 }
4984 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004985 return false;
4986 }
4987
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004988 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004989 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004990 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004991 return true;
4992 }
4993 // If we only verified a subset of the classes at compile time, we can end up with classes that
4994 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004995 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004996 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004997 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004998 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004999 // Compile time verification failed with a soft error. Compile time verification can fail
5000 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08005001 // class ... {
5002 // Foo x;
5003 // .... () {
5004 // if (...) {
5005 // v1 gets assigned a type of resolved class Foo
5006 // } else {
5007 // v1 gets assigned a type of unresolved class Bar
5008 // }
5009 // iput x = v1
5010 // } }
5011 // when we merge v1 following the if-the-else it results in Conflict
5012 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
5013 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
5014 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
5015 // at compile time).
5016 return false;
5017 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00005018 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07005019 // Compile time verification failed with a hard error. This is caused by invalid instructions
5020 // in the class. These errors are unrecoverable.
5021 return false;
5022 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005023 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08005024 // Status is uninitialized if we couldn't determine the status at compile time, for example,
5025 // not loading the class.
5026 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
5027 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005028 return false;
5029 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07005030 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07005031 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07005032 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07005033 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005034 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005035}
5036
Alex Light5a559862016-01-29 12:24:48 -08005037void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08005038 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08005039 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005040 }
5041}
5042
Alex Light5a559862016-01-29 12:24:48 -08005043void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005044 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00005045 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005046 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005047 return; // native or abstract method
5048 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005049 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005050 return; // nothing to process
5051 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005052 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005053 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005054 for (uint32_t idx = 0; idx < handlers_size; idx++) {
5055 CatchHandlerIterator iterator(handlers_ptr);
5056 for (; iterator.HasNext(); iterator.Next()) {
5057 // Ensure exception types are resolved so that they don't need resolution to be delivered,
5058 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08005059 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005060 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005061 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005062 DCHECK(Thread::Current()->IsExceptionPending());
5063 Thread::Current()->ClearException();
5064 }
5065 }
5066 }
5067 handlers_ptr = iterator.EndDataPointer();
5068 }
5069}
5070
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01005071ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
5072 jstring name,
5073 jobjectArray interfaces,
5074 jobject loader,
5075 jobjectArray methods,
5076 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005077 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07005078
5079 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
5080 // code to be executed. We put it up here so we can avoid all the allocations associated with
5081 // creating the class. This can happen with (eg) jit-threads.
5082 if (!self->CanLoadClasses()) {
5083 // Make sure we don't try to load anything, potentially causing an infinite loop.
5084 ObjPtr<mirror::Throwable> pre_allocated =
5085 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
5086 self->SetException(pre_allocated);
5087 return nullptr;
5088 }
5089
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005090 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005091 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005092 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005093 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005094 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005095 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005096 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005097 DCHECK(temp_klass->GetClass() != nullptr);
5098 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08005099 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
5100 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005101 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
5102 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
5103 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
5104 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005105 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08005106 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005107 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005108 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00005109 std::string storage;
5110 const char* descriptor = temp_klass->GetDescriptor(&storage);
5111 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005112
Mathieu Chartierd57d4542015-10-14 10:55:30 -07005113 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005114 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07005115
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005116 // Insert the class before loading the fields as the field roots
5117 // (ArtField::declaring_class_) are only visited from the class
5118 // table. There can't be any suspend points between inserting the
5119 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00005120 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005121 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08005122
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005123 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07005124 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07005125 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005126 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005127
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005128 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
5129 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005130 ArtField& interfaces_sfield = sfields->At(0);
5131 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005132 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005133 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005134
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005135 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005136 ArtField& throws_sfield = sfields->At(1);
5137 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005138 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005139 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04005140
Ian Rogers466bb252011-10-14 03:29:56 -07005141 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08005142 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04005143
Alex Lighte64300b2015-12-15 15:02:47 -08005144 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07005145 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01005146 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07005147 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005148 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08005149
5150 // Create the methods array.
5151 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
5152 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005153 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
5154 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08005155 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005156 self->AssertPendingOOMException();
5157 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005158 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005159 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005160
5161 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005162 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005163
5164 // Create virtual method using specified prototypes.
5165 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005166 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005167 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005168 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005169 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005170 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5171 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005172 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005173
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005174 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005175 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005176 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005177 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005178 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005179
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005180 // At this point the class is loaded. Publish a ClassLoad event.
5181 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5182 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5183
5184 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005185 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005186 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005187 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005188 // Link the fields and virtual methods, creating vtable and iftables.
5189 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005190 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005191 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005192 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005193 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005194 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005195 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005196 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005197 CHECK(temp_klass->IsRetired());
5198 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005199
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005200 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005201 interfaces_sfield.SetObject<false>(
5202 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005203 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005204 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5205 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005206 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005207 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005208
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005209 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5210
Vladimir Marko305c38b2018-02-14 11:50:07 +00005211 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5212 // See also ClassLinker::EnsureInitialized().
5213 if (kBitstringSubtypeCheckEnabled) {
5214 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5215 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5216 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5217 }
5218
Vladimir Markobf121912019-06-04 13:49:05 +01005219 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005220 {
5221 // Lock on klass is released. Lock new class object.
5222 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005223 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005224 // Conservatively go through the ClassStatus::kInitialized state.
5225 callback = MarkClassInitialized(self, klass);
5226 }
5227 if (callback != nullptr) {
5228 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005229 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005230
5231 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07005232 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005233 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005234 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5235
Ian Rogersc2b44472011-12-14 21:17:17 -08005236 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005237 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
5238 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005239 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08005240 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005241
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005242 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005243 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005244 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005245 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005246 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005247
5248 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005249 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005250 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005251
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005252 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005253 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005254 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005255 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08005256 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005257 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005258}
5259
Mathieu Chartiere401d142015-04-22 13:56:20 -07005260void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5261 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005262 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5263 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005264
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005265 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5266 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005267 ArtMethod* proxy_constructor =
5268 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005269 DCHECK(proxy_constructor != nullptr)
5270 << "Could not find <init> method in java.lang.reflect.Proxy";
5271
Jeff Haodb8a6642014-08-14 17:18:52 -07005272 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5273 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005274 DCHECK(out != nullptr);
5275 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005276 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005277 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005278 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005279 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5280 kAccPublic |
5281 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005282 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005283
5284 // Set the original constructor method.
5285 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005286}
5287
Mathieu Chartiere401d142015-04-22 13:56:20 -07005288void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005289 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005290 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5291 CHECK_STREQ(np->GetName(), "<init>");
5292 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005293 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005294}
5295
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005296void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005297 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005298 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005299 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005300 DCHECK(out != nullptr);
5301 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005302
Alex Lighte9dd04f2016-03-16 16:09:45 -07005303 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005304 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005305 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5306 // preference to the invocation handler.
5307 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5308 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005309 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5310 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005311 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5312
5313 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5314 // method they copy might (if it's a default method).
5315 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005316
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005317 // Set the original interface method.
5318 out->SetDataPtrSize(prototype, image_pointer_size_);
5319
Ian Rogers466bb252011-10-14 03:29:56 -07005320 // At runtime the method looks like a reference and argument saving method, clone the code
5321 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005322 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005323}
Jesse Wilson95caa792011-10-12 18:14:17 -04005324
Mathieu Chartiere401d142015-04-22 13:56:20 -07005325void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005326 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005327 CHECK(!prototype->IsFinal());
5328 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005329 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005330
5331 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5332 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005333 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005334 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005335}
5336
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005337bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005338 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005339 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005340 return true;
5341 }
5342 if (!can_init_statics) {
5343 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005344 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005345 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005346 return false;
5347 }
5348 // Check if there are encoded static values needing initialization.
5349 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005350 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005351 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005352 if (dex_class_def->static_values_off_ != 0) {
5353 return false;
5354 }
5355 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005356 // If we are a class we need to initialize all interfaces with default methods when we are
5357 // initialized. Check all of them.
5358 if (!klass->IsInterface()) {
5359 size_t num_interfaces = klass->GetIfTableCount();
5360 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005361 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005362 if (iface->HasDefaultMethods() &&
5363 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5364 return false;
5365 }
5366 }
5367 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005368 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005369 if (klass->IsInterface() || !klass->HasSuperClass()) {
5370 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005371 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005372 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005373 if (!can_init_parents && !super_class->IsInitialized()) {
5374 return false;
5375 }
5376 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005377}
5378
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005379bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5380 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005381 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5382
5383 // Are we already initialized and therefore done?
5384 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5385 // an initialized class will never change its state.
5386 if (klass->IsInitialized()) {
5387 return true;
5388 }
5389
5390 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005391 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005392 return false;
5393 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005394
Ian Rogers7b078e82014-09-10 14:44:24 -07005395 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005396 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005397 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005398 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005399
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005400 // Re-check under the lock in case another thread initialized ahead of us.
5401 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005402 return true;
5403 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005404
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005405 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005406 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005407 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005408 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005409 return false;
5410 }
5411
Vladimir Marko72ab6842017-01-20 19:32:50 +00005412 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5413 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005414
5415 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005416 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005417 if (!klass->IsVerified()) {
5418 // We failed to verify, expect either the klass to be erroneous or verification failed at
5419 // compile time.
5420 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005421 // The class is erroneous. This may be a verifier error, or another thread attempted
5422 // verification and/or initialization and failed. We can distinguish those cases by
5423 // whether an exception is already pending.
5424 if (self->IsExceptionPending()) {
5425 // Check that it's a VerifyError.
5426 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005427 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005428 } else {
5429 // Check that another thread attempted initialization.
5430 DCHECK_NE(0, klass->GetClinitThreadId());
5431 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5432 // Need to rethrow the previous failure now.
5433 ThrowEarlierClassFailure(klass.Get(), true);
5434 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005435 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005436 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005437 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005438 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005439 self->AssertNoPendingException();
5440 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005441 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005442 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005443 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005444 } else {
5445 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005446 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005447
5448 // A separate thread could have moved us all the way to initialized. A "simple" example
5449 // involves a subclass of the current class being initialized at the same time (which
5450 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005451 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005452 if (klass->IsInitialized()) {
5453 return true;
5454 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005455 }
5456
Vladimir Marko2c64a832018-01-04 11:31:56 +00005457 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005458 // initializing higher up the stack or another thread has beat us
5459 // to initializing and we need to wait. Either way, this
5460 // invocation of InitializeClass will not be responsible for
5461 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005462 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005463 // Could have got an exception during verification.
5464 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005465 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005466 return false;
5467 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005468 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005469 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005470 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005471 return true;
5472 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005473 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005474 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005475 }
5476
Jeff Haoe2e40342017-07-19 10:45:18 -07005477 // Try to get the oat class's status for this class if the oat file is present. The compiler
5478 // tries to validate superclass descriptors, and writes the result into the oat file.
5479 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5480 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5481 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005482 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005483 const Runtime* runtime = Runtime::Current();
5484 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5485 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5486 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005487 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005488 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005489 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005490 return false;
5491 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005492 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005493
Vladimir Marko2c64a832018-01-04 11:31:56 +00005494 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005495 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005496
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005497 // From here out other threads may observe that we're initializing and so changes of state
5498 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005499 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005500 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005501
5502 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005503 }
5504
Andreas Gampeaf864702019-07-23 14:05:35 -07005505 uint64_t t_sub = 0;
5506
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005507 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005508 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005509 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005510 if (!super_class->IsInitialized()) {
5511 CHECK(!super_class->IsInterface());
5512 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005513 StackHandleScope<1> hs(self);
5514 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Andreas Gampeaf864702019-07-23 14:05:35 -07005515 uint64_t super_t0 = NanoTime();
Ian Rogers7b078e82014-09-10 14:44:24 -07005516 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Andreas Gampeaf864702019-07-23 14:05:35 -07005517 uint64_t super_t1 = NanoTime();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005518 if (!super_initialized) {
5519 // The super class was verified ahead of entering initializing, we should only be here if
5520 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005521 // For the case of aot compiler, the super class might also be initializing but we don't
5522 // want to process circular dependencies in pre-compile.
5523 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005524 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005525 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005526 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005527 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005528 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005529 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005530 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005531 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005532 return false;
5533 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005534 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005535 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005536 }
5537
Alex Lighteb7c1442015-08-31 13:17:42 -07005538 if (!klass->IsInterface()) {
5539 // Initialize interfaces with default methods for the JLS.
5540 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005541 // Only setup the (expensive) handle scope if we actually need to.
5542 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005543 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005544 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5545 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005546 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005547 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005548 CHECK(handle_scope_iface->IsInterface());
5549 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5550 // We have already done this for this interface. Skip it.
5551 continue;
5552 }
5553 // We cannot just call initialize class directly because we need to ensure that ALL
5554 // interfaces with default methods are initialized. Non-default interface initialization
5555 // will not affect other non-default super-interfaces.
Andreas Gampeaf864702019-07-23 14:05:35 -07005556 uint64_t inf_t0 = NanoTime(); // This is not very precise, misses all walking.
Alex Light56a40f52015-10-14 11:07:41 -07005557 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5558 handle_scope_iface,
5559 can_init_statics,
5560 can_init_parents);
Andreas Gampeaf864702019-07-23 14:05:35 -07005561 uint64_t inf_t1 = NanoTime();
Alex Light56a40f52015-10-14 11:07:41 -07005562 if (!iface_initialized) {
5563 ObjectLock<mirror::Class> lock(self, klass);
5564 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005565 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005566 return false;
5567 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005568 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005569 }
5570 }
5571 }
5572
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005573 const size_t num_static_fields = klass->NumStaticFields();
5574 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005575 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005576 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005577 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005578 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005579 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005580
5581 // Eagerly fill in static fields so that the we don't have to do as many expensive
5582 // Class::FindStaticField in ResolveField.
5583 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005584 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005585 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005586 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005587 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005588 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005589 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5590 field,
5591 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5592 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005593 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005594 } else {
5595 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005596 }
5597 }
5598
Vladimir Markoe11dd502017-12-08 14:09:45 +00005599 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5600 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005601 this,
5602 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005603 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005604
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005605 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005606 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005607 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005608 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5609 if (!value_it.HasNext()) {
5610 break;
5611 }
5612 ArtField* art_field = ResolveField(field.GetIndex(),
5613 dex_cache,
5614 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005615 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005616 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005617 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005618 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005619 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005620 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005621 if (self->IsExceptionPending()) {
5622 break;
5623 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005624 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005625 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005626 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005627 }
5628 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005629
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005630
Mathieu Chartierda595be2016-08-10 13:57:39 -07005631 if (!self->IsExceptionPending()) {
5632 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5633 if (clinit != nullptr) {
5634 CHECK(can_init_statics);
5635 JValue result;
5636 clinit->Invoke(self, nullptr, 0, &result, "V");
5637 }
5638 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005639 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005640 uint64_t t1 = NanoTime();
5641
Vladimir Markobf121912019-06-04 13:49:05 +01005642 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005643 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005644 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005645 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005646
5647 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005648 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005649 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005650 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005651 } else if (Runtime::Current()->IsTransactionAborted()) {
5652 // The exception thrown when the transaction aborted has been caught and cleared
5653 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005654 VLOG(compiler) << "Return from class initializer of "
5655 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005656 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005657 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005658 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005659 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005660 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005661 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5662 RuntimeStats* thread_stats = self->GetStats();
5663 ++global_stats->class_init_count;
5664 ++thread_stats->class_init_count;
Andreas Gampeaf864702019-07-23 14:05:35 -07005665 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5666 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005667 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005668 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005669 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005670 std::string temp;
5671 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005672 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005673 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005674 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005675 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005676 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005677 }
Vladimir Markobf121912019-06-04 13:49:05 +01005678 if (callback != nullptr) {
5679 callback->MakeVisible(self);
5680 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005681 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005682}
5683
Alex Lighteb7c1442015-08-31 13:17:42 -07005684// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5685// and perform the initialization only on those interfaces that contain default methods.
5686bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5687 Handle<mirror::Class> iface,
5688 bool can_init_statics,
5689 bool can_init_parents) {
5690 CHECK(iface->IsInterface());
5691 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005692 // Only create the (expensive) handle scope if we need it.
5693 if (UNLIKELY(num_direct_ifaces > 0)) {
5694 StackHandleScope<1> hs(self);
5695 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5696 // First we initialize all of iface's super-interfaces recursively.
5697 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005698 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005699 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005700 if (!super_iface->HasBeenRecursivelyInitialized()) {
5701 // Recursive step
5702 handle_super_iface.Assign(super_iface);
5703 if (!InitializeDefaultInterfaceRecursive(self,
5704 handle_super_iface,
5705 can_init_statics,
5706 can_init_parents)) {
5707 return false;
5708 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005709 }
5710 }
5711 }
5712
5713 bool result = true;
5714 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5715 // initialize if we don't have default methods.
5716 if (iface->HasDefaultMethods()) {
5717 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5718 }
5719
5720 // Mark that this interface has undergone recursive default interface initialization so we know we
5721 // can skip it on any later class initializations. We do this even if we are not a default
5722 // interface since we can still avoid the traversal. This is purely a performance optimization.
5723 if (result) {
5724 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005725 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5726 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5727 // initialization is a performance optimization (to avoid another idempotent visit
5728 // for other implementing classes/interfaces), and can be revisited later.
5729 ObjectTryLock<mirror::Class> lock(self, iface);
5730 if (lock.Acquired()) {
5731 iface->SetRecursivelyInitialized();
5732 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005733 }
5734 return result;
5735}
5736
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005737bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5738 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005739 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005740 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005741 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005742 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005743 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005744 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005745
5746 // When we wake up, repeat the test for init-in-progress. If
5747 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005748 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005749 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005750 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005751 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005752 return false;
5753 }
5754 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005755 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005756 continue;
5757 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005758 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005759 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005760 // Compile time initialization failed.
5761 return false;
5762 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005763 if (klass->IsErroneous()) {
5764 // The caller wants an exception, but it was thrown in a
5765 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005766 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005767 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005768 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005769 return false;
5770 }
5771 if (klass->IsInitialized()) {
5772 return true;
5773 }
David Sehr709b0702016-10-13 09:12:37 -07005774 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005775 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005776 }
Ian Rogers07140832014-09-30 15:43:59 -07005777 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005778}
5779
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005780static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5781 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005782 ArtMethod* method,
5783 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005784 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005785 DCHECK(Thread::Current()->IsExceptionPending());
5786 DCHECK(!m->IsProxyMethod());
5787 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005788 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5789 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005790 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005791 std::string return_type = dex_file->PrettyType(return_type_idx);
5792 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005793 ThrowWrappedLinkageError(klass.Get(),
5794 "While checking class %s method %s signature against %s %s: "
5795 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005796 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5797 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005798 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005799 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005800 return_type.c_str(), class_loader.c_str());
5801}
5802
5803static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5804 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005805 ArtMethod* method,
5806 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005807 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005808 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005809 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005810 DCHECK(Thread::Current()->IsExceptionPending());
5811 DCHECK(!m->IsProxyMethod());
5812 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005813 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5814 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005815 ThrowWrappedLinkageError(klass.Get(),
5816 "While checking class %s method %s signature against %s %s: "
5817 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005818 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5819 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005820 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005821 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005822 index, arg_type.c_str(), class_loader.c_str());
5823}
5824
5825static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5826 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005827 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005828 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005829 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005830 ThrowLinkageError(klass.Get(),
5831 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005832 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5833 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005834 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005835 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005836 error_msg.c_str());
5837}
5838
Ian Rogersb5fb2072014-12-02 17:22:02 -08005839static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005840 Handle<mirror::Class> klass,
5841 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005842 ArtMethod* method1,
5843 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005844 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005845 {
5846 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005847 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005848 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005849 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005850 return false;
5851 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005852 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005853 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005854 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005855 return false;
5856 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005857 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005858 ThrowSignatureMismatch(klass, super_klass, method1,
5859 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005860 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005861 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005862 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005863 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005864 return false;
5865 }
5866 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005867 const dex::TypeList* types1 = method1->GetParameterTypeList();
5868 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005869 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005870 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005871 ThrowSignatureMismatch(klass, super_klass, method1,
5872 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005873 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005874 return false;
5875 }
5876 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005877 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005878 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005879 ThrowSignatureMismatch(klass, super_klass, method1,
5880 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005881 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005882 return false;
5883 }
5884 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005885 }
5886 uint32_t num_types = types1->Size();
5887 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005888 ThrowSignatureMismatch(klass, super_klass, method1,
5889 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005890 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005891 return false;
5892 }
5893 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005894 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005895 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005896 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005897 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005898 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005899 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005900 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005901 return false;
5902 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005903 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005904 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005905 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005906 if (UNLIKELY(other_param_type == nullptr)) {
5907 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005908 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005909 return false;
5910 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005911 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005912 ThrowSignatureMismatch(klass, super_klass, method1,
5913 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5914 i,
David Sehr709b0702016-10-13 09:12:37 -07005915 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005916 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005917 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005918 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005919 return false;
5920 }
5921 }
5922 return true;
5923}
5924
5925
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005926bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005927 if (klass->IsInterface()) {
5928 return true;
5929 }
Ian Rogers151f2212014-05-06 11:27:27 -07005930 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005931 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005932 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005933 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005934 if (klass->HasSuperClass() &&
5935 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005936 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005937 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005938 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5939 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5940 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005941 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5942 klass,
5943 super_klass,
5944 m,
5945 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005946 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005947 return false;
5948 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005949 }
5950 }
5951 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005952 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005953 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5954 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5955 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005956 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005957 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5958 j, image_pointer_size_);
5959 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5960 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005961 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5962 klass,
5963 super_klass,
5964 m,
5965 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005966 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005967 return false;
5968 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005969 }
5970 }
5971 }
5972 }
5973 return true;
5974}
5975
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005976bool ClassLinker::EnsureInitialized(Thread* self,
5977 Handle<mirror::Class> c,
5978 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005979 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005980 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005981
Mathieu Chartier524507a2014-08-27 15:28:28 -07005982 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005983 // If we've seen an initialized but not visibly initialized class
5984 // many times, request visible initialization.
5985 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5986 // Thanks to the x86 memory model classes skip the initialized status.
5987 DCHECK(c->IsVisiblyInitialized());
5988 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5989 if (self->IncrementMakeVisiblyInitializedCounter()) {
5990 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5991 }
5992 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005993 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005994 return true;
5995 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005996 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5997 //
5998 // Ensure the bitstring is initialized before any of the class initialization
5999 // logic occurs. Once a class initializer starts running, objects can
6000 // escape into the heap and use the subtype checking code.
6001 //
6002 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
6003 // can be used as a source for the IsSubClass check, and that all ancestors
6004 // of the class are Assigned (can be used as a target for IsSubClass check)
6005 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00006006 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07006007 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00006008 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07006009 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
6010 }
Ian Rogers7b078e82014-09-10 14:44:24 -07006011 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07006012 if (!success) {
6013 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07006014 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07006015 }
6016 } else {
6017 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08006018 }
6019 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07006020}
6021
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006022void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
6023 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006024 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006025 for (ArtField& field : new_class->GetIFields()) {
6026 if (field.GetDeclaringClass() == temp_class) {
6027 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006028 }
6029 }
6030
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006031 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006032 for (ArtField& field : new_class->GetSFields()) {
6033 if (field.GetDeclaringClass() == temp_class) {
6034 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006035 }
6036 }
6037
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006038 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006039 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08006040 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006041 if (method.GetDeclaringClass() == temp_class) {
6042 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006043 }
6044 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006045
6046 // Make sure the remembered set and mod-union tables know that we updated some of the native
6047 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006048 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006049}
6050
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006051void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08006052 CHECK(class_loader->GetAllocator() == nullptr);
6053 CHECK(class_loader->GetClassTable() == nullptr);
6054 Thread* const self = Thread::Current();
6055 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08006056 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08006057 // Create and set the class table.
6058 data.class_table = new ClassTable;
6059 class_loader->SetClassTable(data.class_table);
6060 // Create and set the linear allocator.
6061 data.allocator = Runtime::Current()->CreateLinearAlloc();
6062 class_loader->SetAllocator(data.allocator);
6063 // Add to the list so that we know to free the data later.
6064 class_loaders_.push_back(data);
6065}
6066
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006067ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07006068 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07006069 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006070 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07006071 ClassTable* class_table = class_loader->GetClassTable();
6072 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08006073 RegisterClassLoader(class_loader);
6074 class_table = class_loader->GetClassTable();
6075 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07006076 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006077 return class_table;
6078}
6079
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006080ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07006081 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006082}
6083
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006084static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006085 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006086 while (klass->HasSuperClass()) {
6087 klass = klass->GetSuperClass();
6088 if (klass->ShouldHaveImt()) {
6089 return klass->GetImt(pointer_size);
6090 }
6091 }
6092 return nullptr;
6093}
6094
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006095bool ClassLinker::LinkClass(Thread* self,
6096 const char* descriptor,
6097 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006098 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006099 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006100 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006101
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006102 if (!LinkSuperClass(klass)) {
6103 return false;
6104 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006105 ArtMethod* imt_data[ImTable::kSize];
6106 // If there are any new conflicts compared to super class.
6107 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006108 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006109 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006110 return false;
6111 }
Ian Rogers7b078e82014-09-10 14:44:24 -07006112 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006113 return false;
6114 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006115 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006116 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07006117 return false;
6118 }
6119 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00006120 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006121
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006122 ImTable* imt = nullptr;
6123 if (klass->ShouldHaveImt()) {
6124 // If there are any new conflicts compared to the super class we can not make a copy. There
6125 // can be cases where both will have a conflict method at the same slot without having the same
6126 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
6127 // will possibly create a table that is incorrect for either of the classes.
6128 // Same IMT with new_conflict does not happen very often.
6129 if (!new_conflict) {
6130 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
6131 if (super_imt != nullptr) {
6132 bool imt_equals = true;
6133 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
6134 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
6135 }
6136 if (imt_equals) {
6137 imt = super_imt;
6138 }
6139 }
6140 }
6141 if (imt == nullptr) {
6142 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
6143 imt = reinterpret_cast<ImTable*>(
6144 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
6145 if (imt == nullptr) {
6146 return false;
6147 }
6148 imt->Populate(imt_data, image_pointer_size_);
6149 }
6150 }
6151
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006152 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
6153 // We don't need to retire this class as it has no embedded tables or it was created the
6154 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006155 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006156
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006157 if (klass->ShouldHaveEmbeddedVTable()) {
6158 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006159 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006160 if (klass->ShouldHaveImt()) {
6161 klass->SetImt(imt, image_pointer_size_);
6162 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006163
6164 // Update CHA info based on whether we override methods.
6165 // Have to do this before setting the class as resolved which allows
6166 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006167 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006168 cha_->UpdateAfterLoadingOf(klass);
6169 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006170
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006171 // This will notify waiters on klass that saw the not yet resolved
6172 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006173 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006174 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006175 } else {
6176 CHECK(!klass->IsResolved());
6177 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006178 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006179 Handle<mirror::Class> h_new_class =
6180 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006181 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6182 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6183 // may not see any references to the target space and clean the card for a class if another
6184 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006185 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006186 klass->SetSFieldsPtrUnchecked(nullptr);
6187 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006188 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006189 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006190 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006191 return false;
6192 }
6193
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006194 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6195 ObjectLock<mirror::Class> lock(self, h_new_class);
6196 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006197
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006198 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006199 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006200 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006201 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006202 const ObjPtr<mirror::Class> existing =
6203 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006204 if (class_loader != nullptr) {
6205 // We updated the class in the class table, perform the write barrier so that the GC knows
6206 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006207 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006208 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006209 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006210 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006211 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6212 }
6213 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006214
Mingyao Yang063fc772016-08-02 11:02:54 -07006215 // Update CHA info based on whether we override methods.
6216 // Have to do this before setting the class as resolved which allows
6217 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006218 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006219 cha_->UpdateAfterLoadingOf(h_new_class);
6220 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006221
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006222 // This will notify waiters on temp class that saw the not yet resolved class in the
6223 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006224 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006225
Vladimir Marko2c64a832018-01-04 11:31:56 +00006226 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006227 // This will notify waiters on new_class that saw the not yet resolved
6228 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006229 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006230 // Return the new class.
6231 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006232 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006233 return true;
6234}
6235
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006236bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006237 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006238 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006239 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6240 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006241 // Check that a class does not inherit from itself directly.
6242 //
6243 // TODO: This is a cheap check to detect the straightforward case
6244 // of a class extending itself (b/28685551), but we should do a
6245 // proper cycle detection on loaded classes, to detect all cases
6246 // of class circularity errors (b/28830038).
6247 if (super_class_idx == class_def.class_idx_) {
6248 ThrowClassCircularityError(klass.Get(),
6249 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006250 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006251 return false;
6252 }
6253
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006254 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006255 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006256 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006257 return false;
6258 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006259 // Verify
6260 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006261 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006262 super_class->PrettyDescriptor().c_str(),
6263 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006264 return false;
6265 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006266 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006267 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006268 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006269 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006270 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006271 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006272 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006273 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006274 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006275 DCHECK(Thread::Current()->IsExceptionPending());
6276 return false;
6277 }
6278 // Verify
6279 if (!klass->CanAccess(interface)) {
6280 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006281 ThrowIllegalAccessError(klass.Get(),
6282 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006283 interface->PrettyDescriptor().c_str(),
6284 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006285 return false;
6286 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006287 }
6288 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006289 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006290 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006291 return true;
6292}
6293
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006294bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006295 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006296 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006297 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6298 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006299 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006300 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006301 return false;
6302 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006303 return true;
6304 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006305 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006306 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006307 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006308 return false;
6309 }
6310 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006311 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006312 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6313 return false;
6314 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006315 if (super->IsFinal()) {
6316 ThrowVerifyError(klass.Get(),
6317 "Superclass %s of %s is declared final",
6318 super->PrettyDescriptor().c_str(),
6319 klass->PrettyDescriptor().c_str());
6320 return false;
6321 }
6322 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006323 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006324 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006325 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006326 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006327 return false;
6328 }
6329 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006330 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006331 super->PrettyDescriptor().c_str(),
6332 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006333 return false;
6334 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006335
Brian Carlstromf3632832014-05-20 15:36:53 -07006336 // Inherit kAccClassIsFinalizable from the superclass in case this
6337 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006338 if (super->IsFinalizable()) {
6339 klass->SetFinalizable();
6340 }
6341
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006342 // Inherit class loader flag form super class.
6343 if (super->IsClassLoaderClass()) {
6344 klass->SetClassLoaderClass();
6345 }
6346
Elliott Hughes2da50362011-10-10 16:57:08 -07006347 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006348 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006349 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006350 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006351 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006352 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006353 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006354 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006355 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006356 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006357 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006358 return false;
6359 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006360
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006361 if (kIsDebugBuild) {
6362 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006363 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006364 CHECK(super->IsResolved());
6365 super = super->GetSuperClass();
6366 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006367 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006368 return true;
6369}
6370
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006371// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006372bool ClassLinker::LinkMethods(Thread* self,
6373 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006374 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006375 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006376 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006377 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006378 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6379 // need to have default methods be in the virtuals array of each class but we don't set that up
6380 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006381 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006382 // Link virtual methods then interface methods.
6383 // We set up the interface lookup table first because we need it to determine if we need to update
6384 // any vtable entries with new default method implementations.
6385 return SetupInterfaceLookupTable(self, klass, interfaces)
6386 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006387 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006388}
6389
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006390// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6391// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6392// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006393class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006394 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006395 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006396 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006397 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6398 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006399 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006400 }
6401
6402 const char* GetName() {
6403 if (name_ == nullptr) {
6404 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6405 }
6406 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006407 }
6408
Mathieu Chartiere401d142015-04-22 13:56:20 -07006409 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006410 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006411 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006412 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006413 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006414 if (dex_file_ == other_dex_file) {
6415 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6416 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006417 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006418 uint32_t other_name_len;
6419 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6420 &other_name_len);
6421 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6422 return false;
6423 }
6424 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6425 }
6426
6427 private:
6428 // Dex file for the method to compare against.
6429 const DexFile* const dex_file_;
6430 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006431 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006432 // Lazily computed name from the dex file's strings.
6433 const char* name_;
6434 // Lazily computed name length.
6435 uint32_t name_len_;
6436};
6437
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006438class LinkVirtualHashTable {
6439 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006440 LinkVirtualHashTable(Handle<mirror::Class> klass,
6441 size_t hash_size,
6442 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006443 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006444 : klass_(klass),
6445 hash_size_(hash_size),
6446 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006447 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006448 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6449 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006450
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006451 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006452 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6453 virtual_method_index, image_pointer_size_);
6454 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006455 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006456 uint32_t index = hash % hash_size_;
6457 // Linear probe until we have an empty slot.
6458 while (hash_table_[index] != invalid_index_) {
6459 if (++index == hash_size_) {
6460 index = 0;
6461 }
6462 }
6463 hash_table_[index] = virtual_method_index;
6464 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006465
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006466 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006467 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006468 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006469 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006470 size_t index = hash % hash_size_;
6471 while (true) {
6472 const uint32_t value = hash_table_[index];
6473 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6474 // the block and can safely assume not found.
6475 if (value == invalid_index_) {
6476 break;
6477 }
6478 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006479 ArtMethod* virtual_method =
6480 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6481 if (comparator->HasSameNameAndSignature(
6482 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006483 hash_table_[index] = removed_index_;
6484 return value;
6485 }
6486 }
6487 if (++index == hash_size_) {
6488 index = 0;
6489 }
6490 }
6491 return GetNotFoundIndex();
6492 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006493
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006494 static uint32_t GetNotFoundIndex() {
6495 return invalid_index_;
6496 }
6497
6498 private:
6499 static const uint32_t invalid_index_;
6500 static const uint32_t removed_index_;
6501
6502 Handle<mirror::Class> klass_;
6503 const size_t hash_size_;
6504 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006505 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006506};
6507
6508const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6509const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6510
Stephen Hines1ddd9132017-02-08 01:51:18 -08006511bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006512 Thread* self,
6513 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006514 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006515 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006516 if (klass->IsInterface()) {
6517 // No vtable.
6518 if (!IsUint<16>(num_virtual_methods)) {
6519 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6520 return false;
6521 }
6522 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006523 // Assign each method an IMT index and set the default flag.
6524 for (size_t i = 0; i < num_virtual_methods; ++i) {
6525 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6526 m->SetMethodIndex(i);
6527 if (!m->IsAbstract()) {
6528 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6529 has_defaults = true;
6530 }
6531 }
6532 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6533 // during initialization. This is a performance optimization. We could simply traverse the
6534 // virtual_methods_ array again during initialization.
6535 if (has_defaults) {
6536 klass->SetHasDefaultMethods();
6537 }
6538 return true;
6539 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006540 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6541 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006542 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006543 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006544 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006545 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006546 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006547 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006548 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006549 return false;
6550 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006551 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006552 vtable->SetElementPtrSize(
6553 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006554 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006555 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6556 // might give us new default methods). If no new interfaces then we can skip the rest since
6557 // the class cannot override any of the super-class's methods. This is required for
6558 // correctness since without it we might not update overridden default method vtable entries
6559 // correctly.
6560 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006561 klass->SetVTable(vtable.Get());
6562 return true;
6563 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006564 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006565 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006566 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006567 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006568 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6569 // might give us new default methods). See comment above.
6570 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006571 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006572 return true;
6573 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006574 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6575 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006576 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006577 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006578 return false;
6579 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006580 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006581 // How the algorithm works:
6582 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6583 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6584 // method which has not been matched to a vtable method, and j if the virtual method at the
6585 // index overrode the super virtual method at index j.
6586 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6587 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6588 // the need for the initial vtable which we later shrink back down).
6589 // 3. Add non overridden methods to the end of the vtable.
6590 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006591 // + 1 so that even if we only have new default methods we will still be able to use this hash
6592 // table (i.e. it will never have 0 size).
6593 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006594 uint32_t* hash_table_ptr;
6595 std::unique_ptr<uint32_t[]> hash_heap_storage;
6596 if (hash_table_size <= kMaxStackHash) {
6597 hash_table_ptr = reinterpret_cast<uint32_t*>(
6598 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6599 } else {
6600 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6601 hash_table_ptr = hash_heap_storage.get();
6602 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006603 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006604 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006605 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006606 DCHECK(klass->GetVirtualMethodDuringLinking(
6607 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006608 hash_table.Add(i);
6609 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006610 // 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 -07006611 // the hash table.
6612 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006613 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006614 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006615 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6616 super_method->GetAccessFlags())) {
6617 // Continue on to the next method since this one is package private and canot be overridden.
6618 // Before Android 4.1, the package-private method super_method might have been incorrectly
6619 // overridden.
6620 continue;
6621 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006622 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006623 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006624 // We remove the method so that subsequent lookups will be faster by making the hash-map
6625 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006626 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6627 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006628 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6629 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006630 if (super_method->IsFinal()) {
6631 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6632 virtual_method->PrettyMethod().c_str(),
6633 super_method->GetDeclaringClassDescriptor());
6634 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006635 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006636 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6637 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006638 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006639 // We didn't directly override this method but we might through default methods...
6640 // Check for default method update.
6641 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006642 switch (FindDefaultMethodImplementation(self,
6643 super_method,
6644 klass,
6645 /*out*/&default_method)) {
6646 case DefaultMethodSearchResult::kDefaultConflict: {
6647 // A conflict was found looking for default methods. Note this (assuming it wasn't
6648 // pre-existing) in the translations map.
6649 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6650 // Don't generate another conflict method to reduce memory use as an optimization.
6651 default_translations->insert(
6652 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6653 }
6654 break;
6655 }
6656 case DefaultMethodSearchResult::kAbstractFound: {
6657 // No conflict but method is abstract.
6658 // We note that this vtable entry must be made abstract.
6659 if (UNLIKELY(!super_method->IsAbstract())) {
6660 default_translations->insert(
6661 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6662 }
6663 break;
6664 }
6665 case DefaultMethodSearchResult::kDefaultFound: {
6666 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6667 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6668 // Found a default method implementation that is new.
6669 // TODO Refactor this add default methods to virtuals here and not in
6670 // LinkInterfaceMethods maybe.
6671 // The problem is default methods might override previously present
6672 // default-method or miranda-method vtable entries from the superclass.
6673 // Unfortunately we need these to be entries in this class's virtuals. We do not
6674 // give these entries there until LinkInterfaceMethods so we pass this map around
6675 // to let it know which vtable entries need to be updated.
6676 // Make a note that vtable entry j must be updated, store what it needs to be updated
6677 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6678 // then.
6679 default_translations->insert(
6680 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006681 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6682 << " overridden by default "
6683 << default_method->PrettyMethod()
6684 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006685 }
6686 break;
6687 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006688 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006689 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006690 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006691 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006692 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006693 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006694 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006695 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6696 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006697 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006698 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006699 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006700 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006701 local_method->SetMethodIndex(actual_count);
6702 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006703 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006704 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006705 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006706 return false;
6707 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006708 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006709 CHECK_LE(actual_count, max_count);
6710 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006711 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6712 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006713 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006714 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006715 return false;
6716 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006717 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006718 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006719 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006720 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006721 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006722 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6723 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006724 return false;
6725 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006726 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006727 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006728 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006729 return false;
6730 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006731 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006732 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6733 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006734 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006735 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006736 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006737 }
6738 return true;
6739}
6740
Alex Light9139e002015-10-09 15:59:48 -07006741// Determine if the given iface has any subinterface in the given list that declares the method
6742// specified by 'target'.
6743//
6744// Arguments
6745// - self: The thread we are running on
6746// - target: A comparator that will match any method that overrides the method we are checking for
6747// - iftable: The iftable we are searching for an overriding method on.
6748// - ifstart: The index of the interface we are checking to see if anything overrides
6749// - iface: The interface we are checking to see if anything overrides.
6750// - image_pointer_size:
6751// The image pointer size.
6752//
6753// Returns
6754// - True: There is some method that matches the target comparator defined in an interface that
6755// is a subtype of iface.
6756// - False: There is no method that matches the target comparator in any interface that is a subtype
6757// of iface.
6758static bool ContainsOverridingMethodOf(Thread* self,
6759 MethodNameAndSignatureComparator& target,
6760 Handle<mirror::IfTable> iftable,
6761 size_t ifstart,
6762 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006763 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006764 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006765 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006766 DCHECK(iface != nullptr);
6767 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006768 DCHECK_GE(ifstart, 0u);
6769 DCHECK_LT(ifstart, iftable->Count());
6770 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6771 DCHECK(iface->IsInterface());
6772
6773 size_t iftable_count = iftable->Count();
6774 StackHandleScope<1> hs(self);
6775 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6776 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6777 // Skip ifstart since our current interface obviously cannot override itself.
6778 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006779 // Iterate through every method on this interface. The order does not matter.
6780 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006781 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006782 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006783 // Check if the i'th interface is a subtype of this one.
6784 if (iface->IsAssignableFrom(current_iface.Get())) {
6785 return true;
6786 }
6787 break;
6788 }
6789 }
6790 }
6791 return false;
6792}
6793
Alex Lighteb7c1442015-08-31 13:17:42 -07006794// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006795// out_default_method and returns kDefaultFound on success. If no default method was found return
6796// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6797// default_method conflict) it will return kDefaultConflict.
6798ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6799 Thread* self,
6800 ArtMethod* target_method,
6801 Handle<mirror::Class> klass,
6802 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006803 DCHECK(self != nullptr);
6804 DCHECK(target_method != nullptr);
6805 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006806
6807 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006808
6809 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6810 // table. This lets us walk the table backwards when searching for default methods. The first one
6811 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6812 // track of it and then continue checking all other interfaces, since we need to throw an error if
6813 // we encounter conflicting default method implementations (one is not a subtype of the other).
6814 //
6815 // The order of unrelated interfaces does not matter and is not defined.
6816 size_t iftable_count = klass->GetIfTableCount();
6817 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006818 // No interfaces. We have already reset out to null so just return kAbstractFound.
6819 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006820 }
6821
Alex Light9139e002015-10-09 15:59:48 -07006822 StackHandleScope<3> hs(self);
6823 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006824 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006825 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006826 MethodNameAndSignatureComparator target_name_comparator(
6827 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6828 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006829 for (size_t k = iftable_count; k != 0; ) {
6830 --k;
6831
Alex Lighteb7c1442015-08-31 13:17:42 -07006832 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006833
6834 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006835 // Iterate through every declared method on this interface. The order does not matter.
6836 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6837 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006838 // Skip abstract methods and methods with different names.
6839 if (current_method->IsAbstract() ||
6840 !target_name_comparator.HasSameNameAndSignature(
6841 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6842 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006843 } else if (!current_method->IsPublic()) {
6844 // The verifier should have caught the non-public method for dex version 37. Just warn and
6845 // skip it since this is from before default-methods so we don't really need to care that it
6846 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006847 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6848 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006849 << "This will be a fatal error in subsequent versions of android. "
6850 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006851 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006852 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006853 // We have multiple default impls of the same method. This is a potential default conflict.
6854 // We need to check if this possibly conflicting method is either a superclass of the chosen
6855 // default implementation or is overridden by a non-default interface method. In either case
6856 // there is no conflict.
6857 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6858 !ContainsOverridingMethodOf(self,
6859 target_name_comparator,
6860 iftable,
6861 k,
6862 iface,
6863 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006864 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006865 << current_method->PrettyMethod() << " and "
6866 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6867 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006868 *out_default_method = nullptr;
6869 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006870 } else {
6871 break; // Continue checking at the next interface.
6872 }
6873 } else {
Alex Light9139e002015-10-09 15:59:48 -07006874 // chosen_iface == null
6875 if (!ContainsOverridingMethodOf(self,
6876 target_name_comparator,
6877 iftable,
6878 k,
6879 iface,
6880 image_pointer_size_)) {
6881 // Don't set this as the chosen interface if something else is overriding it (because that
6882 // other interface would be potentially chosen instead if it was default). If the other
6883 // interface was abstract then we wouldn't select this interface as chosen anyway since
6884 // the abstract method masks it.
6885 *out_default_method = current_method;
6886 chosen_iface.Assign(iface.Get());
6887 // We should now finish traversing the graph to find if we have default methods that
6888 // conflict.
6889 } else {
David Sehr709b0702016-10-13 09:12:37 -07006890 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6891 << "' was "
6892 << "skipped because it was overridden by an abstract method in a "
6893 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006894 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006895 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006896 break;
6897 }
6898 }
Alex Light9139e002015-10-09 15:59:48 -07006899 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006900 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6901 << "' selected "
6902 << "as the implementation for '" << target_method->PrettyMethod()
6903 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006904 return DefaultMethodSearchResult::kDefaultFound;
6905 } else {
6906 return DefaultMethodSearchResult::kAbstractFound;
6907 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006908}
6909
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006910ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006911 ArtMethod* conflict_method,
6912 ArtMethod* interface_method,
6913 ArtMethod* method,
6914 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006915 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006916 Runtime* const runtime = Runtime::Current();
6917 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6918 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6919
6920 // Create a new entry if the existing one is the shared conflict method.
6921 ArtMethod* new_conflict_method = new_entry
6922 ? runtime->CreateImtConflictMethod(linear_alloc)
6923 : conflict_method;
6924
6925 // Allocate a new table. Note that we will leak this table at the next conflict,
6926 // but that's a tradeoff compared to making the table fixed size.
6927 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006928 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6929 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006930 if (data == nullptr) {
6931 LOG(ERROR) << "Failed to allocate conflict table";
6932 return conflict_method;
6933 }
6934 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6935 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006936 method,
6937 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006938
6939 // Do a fence to ensure threads see the data in the table before it is assigned
6940 // to the conflict method.
6941 // Note that there is a race in the presence of multiple threads and we may leak
6942 // memory from the LinearAlloc, but that's a tradeoff compared to using
6943 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006944 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006945 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006946 return new_conflict_method;
6947}
6948
Vladimir Marko921094a2017-01-12 18:37:06 +00006949bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6950 Handle<mirror::Class> klass,
6951 Handle<mirror::IfTable> iftable) {
6952 DCHECK(!klass->IsInterface());
6953 const bool has_superclass = klass->HasSuperClass();
6954 const bool extend_super_iftable = has_superclass;
6955 const size_t ifcount = klass->GetIfTableCount();
6956 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6957 for (size_t i = 0; i < ifcount; ++i) {
6958 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6959 if (num_methods > 0) {
6960 const bool is_super = i < super_ifcount;
6961 // This is an interface implemented by a super-class. Therefore we can just copy the method
6962 // array from the superclass.
6963 const bool super_interface = is_super && extend_super_iftable;
6964 ObjPtr<mirror::PointerArray> method_array;
6965 if (super_interface) {
6966 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6967 DCHECK(if_table != nullptr);
6968 DCHECK(if_table->GetMethodArray(i) != nullptr);
6969 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006970 StackHandleScope<1u> hs(self);
6971 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6972 method_array =
6973 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006974 } else {
6975 method_array = AllocPointerArray(self, num_methods);
6976 }
6977 if (UNLIKELY(method_array == nullptr)) {
6978 self->AssertPendingOOMException();
6979 return false;
6980 }
6981 iftable->SetMethodArray(i, method_array);
6982 }
6983 }
6984 return true;
6985}
6986
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006987void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6988 ArtMethod* imt_conflict_method,
6989 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006990 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006991 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006992 // Place method in imt if entry is empty, place conflict otherwise.
6993 if (*imt_ref == unimplemented_method) {
6994 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006995 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006996 // If we are not a conflict and we have the same signature and name as the imt
6997 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006998 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6999 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007000 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007001 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07007002 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007003 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007004 *imt_ref = current_method;
7005 } else {
Alex Light9139e002015-10-09 15:59:48 -07007006 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007007 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07007008 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00007009 } else {
7010 // Place the default conflict method. Note that there may be an existing conflict
7011 // method in the IMT, but it could be one tailored to the super class, with a
7012 // specific ImtConflictTable.
7013 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007014 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07007015 }
7016}
7017
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007018void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07007019 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
7020 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007021 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007022 Runtime* const runtime = Runtime::Current();
7023 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
7024 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007025 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007026 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007027 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007028 FillIMTFromIfTable(klass->GetIfTable(),
7029 unimplemented_method,
7030 conflict_method,
7031 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007032 /*create_conflict_tables=*/true,
7033 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007034 &new_conflict,
7035 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007036 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007037 if (!klass->ShouldHaveImt()) {
7038 return;
7039 }
7040 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
7041 // we can just use the same pointer.
7042 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007043 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007044 if (super_class != nullptr && super_class->ShouldHaveImt()) {
7045 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7046 bool same = true;
7047 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
7048 ArtMethod* method = imt_data[i];
7049 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
7050 if (method != super_method) {
7051 bool is_conflict_table = method->IsRuntimeMethod() &&
7052 method != unimplemented_method &&
7053 method != conflict_method;
7054 // Verify conflict contents.
7055 bool super_conflict_table = super_method->IsRuntimeMethod() &&
7056 super_method != unimplemented_method &&
7057 super_method != conflict_method;
7058 if (!is_conflict_table || !super_conflict_table) {
7059 same = false;
7060 } else {
7061 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
7062 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
7063 same = same && table1->Equals(table2, image_pointer_size_);
7064 }
7065 }
7066 }
7067 if (same) {
7068 imt = super_imt;
7069 }
7070 }
7071 if (imt == nullptr) {
7072 imt = klass->GetImt(image_pointer_size_);
7073 DCHECK(imt != nullptr);
7074 imt->Populate(imt_data, image_pointer_size_);
7075 } else {
7076 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007077 }
7078}
7079
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007080ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
7081 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07007082 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007083 void* data = linear_alloc->Alloc(Thread::Current(),
7084 ImtConflictTable::ComputeSize(count,
7085 image_pointer_size));
7086 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
7087}
7088
7089ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
7090 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
7091}
7092
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007093void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007094 ArtMethod* unimplemented_method,
7095 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007096 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007097 bool create_conflict_tables,
7098 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007099 /*out*/bool* new_conflict,
7100 /*out*/ArtMethod** imt) {
7101 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007102 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007103 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007104 const size_t num_virtuals = interface->NumVirtualMethods();
7105 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7106 // Virtual methods can be larger than the if table methods if there are default methods.
7107 DCHECK_GE(num_virtuals, method_array_count);
7108 if (kIsDebugBuild) {
7109 if (klass->IsInterface()) {
7110 DCHECK_EQ(method_array_count, 0u);
7111 } else {
7112 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
7113 }
7114 }
7115 if (method_array_count == 0) {
7116 continue;
7117 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007118 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007119 for (size_t j = 0; j < method_array_count; ++j) {
7120 ArtMethod* implementation_method =
7121 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7122 if (ignore_copied_methods && implementation_method->IsCopied()) {
7123 continue;
7124 }
7125 DCHECK(implementation_method != nullptr);
7126 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7127 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7128 // or interface methods in the IMT here they will not create extra conflicts since we compare
7129 // names and signatures in SetIMTRef.
7130 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007131 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007132
7133 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7134 // the same implementation method, keep track of this to avoid creating a conflict table in
7135 // this case.
7136
7137 // Conflict table size for each IMT slot.
7138 ++conflict_counts[imt_index];
7139
7140 SetIMTRef(unimplemented_method,
7141 imt_conflict_method,
7142 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007143 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007144 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007145 }
7146 }
7147
7148 if (create_conflict_tables) {
7149 // Create the conflict tables.
7150 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007151 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007152 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007153 if (imt[i] == imt_conflict_method) {
7154 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7155 if (new_table != nullptr) {
7156 ArtMethod* new_conflict_method =
7157 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7158 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7159 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007160 } else {
7161 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007162 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007163 }
7164 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007165 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007166 }
7167 }
7168
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007169 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007170 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007171 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7172 // Virtual methods can be larger than the if table methods if there are default methods.
7173 if (method_array_count == 0) {
7174 continue;
7175 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007176 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007177 for (size_t j = 0; j < method_array_count; ++j) {
7178 ArtMethod* implementation_method =
7179 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7180 if (ignore_copied_methods && implementation_method->IsCopied()) {
7181 continue;
7182 }
7183 DCHECK(implementation_method != nullptr);
7184 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007185 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007186 if (!imt[imt_index]->IsRuntimeMethod() ||
7187 imt[imt_index] == unimplemented_method ||
7188 imt[imt_index] == imt_conflict_method) {
7189 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007190 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007191 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7192 const size_t num_entries = table->NumEntries(image_pointer_size_);
7193 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7194 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007195 }
7196 }
7197 }
7198}
7199
Alex Lighteb7c1442015-08-31 13:17:42 -07007200// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7201// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007202static bool NotSubinterfaceOfAny(
7203 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
7204 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007205 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007206 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007207 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007208 for (ObjPtr<mirror::Class> c : classes) {
7209 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007210 return false;
7211 }
7212 }
7213 return true;
7214}
7215
7216// Fills in and flattens the interface inheritance hierarchy.
7217//
7218// By the end of this function all interfaces in the transitive closure of to_process are added to
7219// the iftable and every interface precedes all of its sub-interfaces in this list.
7220//
7221// all I, J: Interface | I <: J implies J precedes I
7222//
7223// (note A <: B means that A is a subtype of B)
7224//
7225// This returns the total number of items in the iftable. The iftable might be resized down after
7226// this call.
7227//
7228// We order this backwards so that we do not need to reorder superclass interfaces when new
7229// interfaces are added in subclass's interface tables.
7230//
7231// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7232// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7233// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7234// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007235static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007236 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07007237 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07007238 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007239 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007240 // This is the set of all class's already in the iftable. Used to make checking if a class has
7241 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007242 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07007243 // The first super_ifcount elements are from the superclass. We note that they are already added.
7244 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007245 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007246 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
7247 classes_in_iftable.insert(iface);
7248 }
7249 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007250 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007251 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7252 // At this point in the loop current-iface-list has the invariant that:
7253 // for every pair of interfaces I,J within it:
7254 // if index_of(I) < index_of(J) then I is not a subtype of J
7255
7256 // If we have already seen this element then all of its super-interfaces must already be in the
7257 // current-iface-list so we can skip adding it.
7258 if (!ContainsElement(classes_in_iftable, interface)) {
7259 // We haven't seen this interface so add all of its super-interfaces onto the
7260 // current-iface-list, skipping those already on it.
7261 int32_t ifcount = interface->GetIfTableCount();
7262 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007263 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007264 if (!ContainsElement(classes_in_iftable, super_interface)) {
7265 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
7266 classes_in_iftable.insert(super_interface);
7267 iftable->SetInterface(filled_ifcount, super_interface);
7268 filled_ifcount++;
7269 }
7270 }
7271 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7272 // Place this interface onto the current-iface-list after all of its super-interfaces.
7273 classes_in_iftable.insert(interface);
7274 iftable->SetInterface(filled_ifcount, interface);
7275 filled_ifcount++;
7276 } else if (kIsDebugBuild) {
7277 // Check all super-interfaces are already in the list.
7278 int32_t ifcount = interface->GetIfTableCount();
7279 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007280 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007281 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007282 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7283 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007284 }
7285 }
7286 }
7287 if (kIsDebugBuild) {
7288 // Check that the iftable is ordered correctly.
7289 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007290 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007291 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007292 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007293 // !(if_a <: if_b)
7294 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007295 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7296 << ") extends "
7297 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007298 << "interface list.";
7299 }
7300 }
7301 }
7302 return filled_ifcount;
7303}
7304
7305bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
7306 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7307 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007308 const bool has_superclass = klass->HasSuperClass();
7309 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007310 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007311 const size_t num_interfaces =
7312 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007313 if (num_interfaces == 0) {
7314 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007315 if (LIKELY(has_superclass)) {
7316 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7317 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007318 // Class implements no interfaces.
7319 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007320 return true;
7321 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007322 // Class implements same interfaces as parent, are any of these not marker interfaces?
7323 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007324 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007325 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007326 if (super_iftable->GetMethodArrayCount(i) > 0) {
7327 has_non_marker_interface = true;
7328 break;
7329 }
7330 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007331 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007332 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007333 klass->SetIfTable(super_iftable);
7334 return true;
7335 }
7336 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007337 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007338 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007339 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007340 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007341 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007342 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007343 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007344 if (UNLIKELY(!interface->IsInterface())) {
7345 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007346 ThrowIncompatibleClassChangeError(klass.Get(),
7347 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007348 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007349 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7350 return false;
7351 }
7352 ifcount += interface->GetIfTableCount();
7353 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007354 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007355 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007356 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007357 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007358 return false;
7359 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007360 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007361 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007362 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007363 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007364 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007365 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007366 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007367 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007368
7369 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7370 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7371 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007372 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007373
7374 size_t new_ifcount;
7375 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007376 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007377 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007378 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007379 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007380 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007381 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007382 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007383
7384 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007385 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007386
Ian Rogers7b078e82014-09-10 14:44:24 -07007387 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007388
Ian Rogersb52b01a2012-01-12 17:01:38 -08007389 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007390 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007391 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007392 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007393 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007394 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007395 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007396 return false;
7397 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007398 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007399 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007400 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007401 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007402 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007403 return true;
7404}
7405
Alex Light1f3925d2016-09-07 12:04:20 -07007406// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7407// of methods must be unique.
7408static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7409 return nullptr;
7410}
7411
7412template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007413static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007414 const ScopedArenaVector<ArtMethod*>& list,
7415 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007416 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007417 for (ArtMethod* method : list) {
7418 if (cmp.HasSameNameAndSignature(method)) {
7419 return method;
7420 }
7421 }
Alex Light1f3925d2016-09-07 12:04:20 -07007422 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007423}
7424
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007425namespace {
7426
Alex Light1f3925d2016-09-07 12:04:20 -07007427// Check that all vtable entries are present in this class's virtuals or are the same as a
7428// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007429void CheckClassOwnsVTableEntries(Thread* self,
7430 Handle<mirror::Class> klass,
7431 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007432 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007433 StackHandleScope<2> hs(self);
7434 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007435 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007436 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007437 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007438 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7439 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7440 CHECK(m != nullptr);
7441
Alex Lighta41a30782017-03-29 11:33:19 -07007442 if (m->GetMethodIndexDuringLinking() != i) {
7443 LOG(WARNING) << m->PrettyMethod()
7444 << " has an unexpected method index for its spot in the vtable for class"
7445 << klass->PrettyClass();
7446 }
Alex Lighte64300b2015-12-15 15:02:47 -08007447 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7448 auto is_same_method = [m] (const ArtMethod& meth) {
7449 return &meth == m;
7450 };
Alex Light3f980532017-03-17 15:10:32 -07007451 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7452 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7453 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7454 << klass->PrettyClass() << " or any of its superclasses!";
7455 }
Alex Lighte64300b2015-12-15 15:02:47 -08007456 }
7457}
7458
Alex Light1f3925d2016-09-07 12:04:20 -07007459// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7460// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007461template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007462void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007463 REQUIRES_SHARED(Locks::mutator_lock_) {
7464 StackHandleScope<1> hs(self);
7465 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7466 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007467
7468 // Observations:
7469 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7470 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7471 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7472 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7473 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7474 // * The single-pass algorithm will trade memory for speed, but that is OK.
7475
7476 CHECK_GT(num_entries, 0);
7477
7478 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7479 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7480 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7481 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7482 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7483 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7484 << m2->PrettyMethod() << " (0x" << std::hex
7485 << reinterpret_cast<uintptr_t>(m2) << ")";
7486 };
7487 struct BaseHashType {
7488 static size_t HashCombine(size_t seed, size_t val) {
7489 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7490 }
7491 };
7492
7493 // Check assuming all entries come from the same dex file.
7494 {
7495 // Find the first interesting method and its dex file.
7496 int32_t start = 0;
7497 for (; start < num_entries; ++start) {
7498 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7499 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7500 // maybe).
7501 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7502 vtable_entry->GetAccessFlags())) {
7503 continue;
7504 }
7505 break;
7506 }
7507 if (start == num_entries) {
7508 return;
7509 }
7510 const DexFile* dex_file =
7511 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7512 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7513
7514 // Helper function to avoid logging if we have to run the cross-file checks.
7515 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7516 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7517 using PairType = std::pair<uint32_t, uint16_t>;
7518 struct PairHash : BaseHashType {
7519 size_t operator()(const PairType& key) const {
7520 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7521 }
7522 };
7523 std::unordered_map<PairType, int32_t, PairHash> seen;
7524 seen.reserve(2 * num_entries);
7525 bool need_slow_path = false;
7526 bool found_dup = false;
7527 for (int i = start; i < num_entries; ++i) {
7528 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7529 // wrt/ kPointerSize.
7530 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7531 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7532 vtable_entry->GetAccessFlags())) {
7533 continue;
7534 }
7535 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7536 if (dex_file != m->GetDexFile()) {
7537 need_slow_path = true;
7538 break;
7539 }
7540 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7541 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7542 auto it = seen.find(pair);
7543 if (it != seen.end()) {
7544 found_dup = true;
7545 if (log_warn) {
7546 log_fn(it->second, i);
7547 }
7548 } else {
7549 seen.emplace(pair, i);
7550 }
7551 }
7552 return std::make_pair(need_slow_path, found_dup);
7553 };
7554 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7555 if (!result.first) {
7556 if (result.second) {
7557 check_fn(/* log_warn= */ true);
7558 }
7559 return;
7560 }
7561 }
7562
7563 // Need to check across dex files.
7564 struct Entry {
7565 size_t cached_hash = 0;
7566 const char* name = nullptr;
7567 Signature signature = Signature::NoSignature();
7568 uint32_t name_len = 0;
7569
7570 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7571 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7572 signature(dex_file->GetMethodSignature(mid)) {
7573 }
7574
7575 bool operator==(const Entry& other) const {
7576 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7577 return false;
7578 }
7579 return signature == other.signature;
7580 }
7581 };
7582 struct EntryHash {
7583 size_t operator()(const Entry& key) const {
7584 return key.cached_hash;
7585 }
7586 };
7587 std::unordered_map<Entry, int32_t, EntryHash> map;
7588 for (int32_t i = 0; i < num_entries; ++i) {
7589 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7590 // wrt/ kPointerSize.
7591 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7592 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7593 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007594 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7595 vtable_entry->GetAccessFlags())) {
7596 continue;
7597 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007598 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7599 const DexFile* dex_file = m->GetDexFile();
7600 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7601
7602 Entry e(dex_file, mid);
7603
7604 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7605 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7606 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7607 sig_hash);
7608
7609 auto it = map.find(e);
7610 if (it != map.end()) {
7611 log_fn(it->second, i);
7612 } else {
7613 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007614 }
7615 }
7616}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007617
7618void CheckVTableHasNoDuplicates(Thread* self,
7619 Handle<mirror::Class> klass,
7620 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007621 REQUIRES_SHARED(Locks::mutator_lock_) {
7622 switch (pointer_size) {
7623 case PointerSize::k64:
7624 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7625 break;
7626 case PointerSize::k32:
7627 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7628 break;
7629 }
7630}
Alex Light1f3925d2016-09-07 12:04:20 -07007631
7632static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7633 REQUIRES_SHARED(Locks::mutator_lock_) {
7634 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7635 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7636}
7637
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007638} // namespace
7639
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007640void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7641 ArtMethod* unimplemented_method,
7642 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007643 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007644 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007645 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007646 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007647 if (super_class->ShouldHaveImt()) {
7648 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7649 for (size_t i = 0; i < ImTable::kSize; ++i) {
7650 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007651 }
7652 } else {
7653 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007654 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007655 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007656 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007657 FillIMTFromIfTable(if_table,
7658 unimplemented_method,
7659 imt_conflict_method,
7660 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007661 /*create_conflict_tables=*/false,
7662 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007663 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007664 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007665 }
7666 }
7667}
7668
Vladimir Marko921094a2017-01-12 18:37:06 +00007669class ClassLinker::LinkInterfaceMethodsHelper {
7670 public:
7671 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7672 Handle<mirror::Class> klass,
7673 Thread* self,
7674 Runtime* runtime)
7675 : class_linker_(class_linker),
7676 klass_(klass),
7677 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7678 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7679 self_(self),
7680 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7681 allocator_(&stack_),
7682 default_conflict_methods_(allocator_.Adapter()),
7683 overriding_default_conflict_methods_(allocator_.Adapter()),
7684 miranda_methods_(allocator_.Adapter()),
7685 default_methods_(allocator_.Adapter()),
7686 overriding_default_methods_(allocator_.Adapter()),
7687 move_table_(allocator_.Adapter()) {
7688 }
7689
7690 ArtMethod* FindMethod(ArtMethod* interface_method,
7691 MethodNameAndSignatureComparator& interface_name_comparator,
7692 ArtMethod* vtable_impl)
7693 REQUIRES_SHARED(Locks::mutator_lock_);
7694
7695 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7696 MethodNameAndSignatureComparator& interface_name_comparator)
7697 REQUIRES_SHARED(Locks::mutator_lock_);
7698
7699 bool HasNewVirtuals() const {
7700 return !(miranda_methods_.empty() &&
7701 default_methods_.empty() &&
7702 overriding_default_methods_.empty() &&
7703 overriding_default_conflict_methods_.empty() &&
7704 default_conflict_methods_.empty());
7705 }
7706
7707 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7708
7709 ObjPtr<mirror::PointerArray> UpdateVtable(
7710 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007711 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007712
7713 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7714
7715 void UpdateIMT(ArtMethod** out_imt);
7716
7717 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7718 if (kIsDebugBuild) {
7719 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7720 // Check that there are no stale methods are in the dex cache array.
7721 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7722 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007723 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7724 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007725 CHECK(move_table_.find(m) == move_table_.end() ||
7726 // The original versions of copied methods will still be present so allow those too.
7727 // Note that if the first check passes this might fail to GetDeclaringClass().
7728 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7729 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7730 [m] (ArtMethod& meth) {
7731 return &meth == m;
7732 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7733 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7734 }
7735 }
7736 }
7737
7738 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7739 LengthPrefixedArray<ArtMethod>* methods) {
7740 if (kIsDebugBuild) {
7741 CHECK(methods != nullptr);
7742 // Put some random garbage in old methods to help find stale pointers.
7743 if (methods != old_methods && old_methods != nullptr) {
7744 // Need to make sure the GC is not running since it could be scanning the methods we are
7745 // about to overwrite.
7746 ScopedThreadStateChange tsc(self_, kSuspended);
7747 gc::ScopedGCCriticalSection gcs(self_,
7748 gc::kGcCauseClassLinker,
7749 gc::kCollectorTypeClassLinker);
7750 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7751 method_size_,
7752 method_alignment_);
7753 memset(old_methods, 0xFEu, old_size);
7754 }
7755 }
7756 }
7757
7758 private:
7759 size_t NumberOfNewVirtuals() const {
7760 return miranda_methods_.size() +
7761 default_methods_.size() +
7762 overriding_default_conflict_methods_.size() +
7763 overriding_default_methods_.size() +
7764 default_conflict_methods_.size();
7765 }
7766
7767 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7768 return !klass_->IsInterface();
7769 }
7770
7771 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7772 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7773 << "Interfaces should only have default-conflict methods appended to them.";
7774 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7775 << miranda_methods_.size()
7776 << " default_methods=" << default_methods_.size()
7777 << " overriding_default_methods=" << overriding_default_methods_.size()
7778 << " default_conflict_methods=" << default_conflict_methods_.size()
7779 << " overriding_default_conflict_methods="
7780 << overriding_default_conflict_methods_.size();
7781 }
7782
7783 ClassLinker* class_linker_;
7784 Handle<mirror::Class> klass_;
7785 size_t method_alignment_;
7786 size_t method_size_;
7787 Thread* const self_;
7788
7789 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7790 // the virtual methods array.
7791 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7792 // during cross compilation.
7793 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7794 ArenaStack stack_;
7795 ScopedArenaAllocator allocator_;
7796
7797 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7798 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7799 ScopedArenaVector<ArtMethod*> miranda_methods_;
7800 ScopedArenaVector<ArtMethod*> default_methods_;
7801 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7802
7803 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7804};
7805
7806ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7807 ArtMethod* interface_method,
7808 MethodNameAndSignatureComparator& interface_name_comparator,
7809 ArtMethod* vtable_impl) {
7810 ArtMethod* current_method = nullptr;
7811 switch (class_linker_->FindDefaultMethodImplementation(self_,
7812 interface_method,
7813 klass_,
7814 /*out*/&current_method)) {
7815 case DefaultMethodSearchResult::kDefaultConflict: {
7816 // Default method conflict.
7817 DCHECK(current_method == nullptr);
7818 ArtMethod* default_conflict_method = nullptr;
7819 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7820 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7821 default_conflict_method = vtable_impl;
7822 } else {
7823 // See if we already have a conflict method for this method.
7824 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7825 interface_name_comparator,
7826 default_conflict_methods_,
7827 overriding_default_conflict_methods_);
7828 if (LIKELY(preexisting_conflict != nullptr)) {
7829 // We already have another conflict we can reuse.
7830 default_conflict_method = preexisting_conflict;
7831 } else {
7832 // Note that we do this even if we are an interface since we need to create this and
7833 // cannot reuse another classes.
7834 // Create a new conflict method for this to use.
7835 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7836 new(default_conflict_method) ArtMethod(interface_method,
7837 class_linker_->GetImagePointerSize());
7838 if (vtable_impl == nullptr) {
7839 // Save the conflict method. We need to add it to the vtable.
7840 default_conflict_methods_.push_back(default_conflict_method);
7841 } else {
7842 // Save the conflict method but it is already in the vtable.
7843 overriding_default_conflict_methods_.push_back(default_conflict_method);
7844 }
7845 }
7846 }
7847 current_method = default_conflict_method;
7848 break;
7849 } // case kDefaultConflict
7850 case DefaultMethodSearchResult::kDefaultFound: {
7851 DCHECK(current_method != nullptr);
7852 // Found a default method.
7853 if (vtable_impl != nullptr &&
7854 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7855 // We found a default method but it was the same one we already have from our
7856 // superclass. Don't bother adding it to our vtable again.
7857 current_method = vtable_impl;
7858 } else if (LIKELY(FillTables())) {
7859 // Interfaces don't need to copy default methods since they don't have vtables.
7860 // Only record this default method if it is new to save space.
7861 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7862 // would make lookup for interface super much faster. (We would only need to scan
7863 // the iftable to find if there is a NSME or AME.)
7864 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7865 default_methods_,
7866 overriding_default_methods_);
7867 if (old == nullptr) {
7868 // We found a default method implementation and there were no conflicts.
7869 if (vtable_impl == nullptr) {
7870 // Save the default method. We need to add it to the vtable.
7871 default_methods_.push_back(current_method);
7872 } else {
7873 // Save the default method but it is already in the vtable.
7874 overriding_default_methods_.push_back(current_method);
7875 }
7876 } else {
7877 CHECK(old == current_method) << "Multiple default implementations selected!";
7878 }
7879 }
7880 break;
7881 } // case kDefaultFound
7882 case DefaultMethodSearchResult::kAbstractFound: {
7883 DCHECK(current_method == nullptr);
7884 // Abstract method masks all defaults.
7885 if (vtable_impl != nullptr &&
7886 vtable_impl->IsAbstract() &&
7887 !vtable_impl->IsDefaultConflicting()) {
7888 // We need to make this an abstract method but the version in the vtable already is so
7889 // don't do anything.
7890 current_method = vtable_impl;
7891 }
7892 break;
7893 } // case kAbstractFound
7894 }
7895 return current_method;
7896}
7897
7898ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7899 ArtMethod* interface_method,
7900 MethodNameAndSignatureComparator& interface_name_comparator) {
7901 // Find out if there is already a miranda method we can use.
7902 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7903 miranda_methods_);
7904 if (miranda_method == nullptr) {
7905 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7906 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7907 CHECK(miranda_method != nullptr);
7908 // Point the interface table at a phantom slot.
7909 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7910 miranda_methods_.push_back(miranda_method);
7911 }
7912 return miranda_method;
7913}
7914
7915void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7916 LogNewVirtuals();
7917
7918 const size_t old_method_count = klass_->NumMethods();
7919 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7920 DCHECK_NE(old_method_count, new_method_count);
7921
7922 // Attempt to realloc to save RAM if possible.
7923 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7924 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7925 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7926 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7927 // CopyFrom has internal read barriers.
7928 //
7929 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7930 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7931 method_size_,
7932 method_alignment_);
7933 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7934 method_size_,
7935 method_alignment_);
7936 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7937 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007938 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007939 self_, old_methods, old_methods_ptr_size, new_size));
7940 CHECK(methods != nullptr); // Native allocation failure aborts.
7941
7942 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7943 if (methods != old_methods) {
7944 // Maps from heap allocated miranda method to linear alloc miranda method.
7945 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7946 // Copy over the old methods.
7947 for (auto& m : klass_->GetMethods(pointer_size)) {
7948 move_table_.emplace(&m, &*out);
7949 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7950 // barriers when it copies.
7951 out->CopyFrom(&m, pointer_size);
7952 ++out;
7953 }
7954 }
7955 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7956 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7957 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007958 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7959 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007960 ArtMethod& new_method = *out;
7961 new_method.CopyFrom(mir_method, pointer_size);
7962 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7963 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7964 << "Miranda method should be abstract!";
7965 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007966 // Update the entry in the method array, as the array will be used for future lookups,
7967 // where thread suspension is allowed.
7968 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7969 // would not see them.
7970 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007971 ++out;
7972 }
7973 // We need to copy the default methods into our own method table since the runtime requires that
7974 // every method on a class's vtable be in that respective class's virtual method table.
7975 // NOTE This means that two classes might have the same implementation of a method from the same
7976 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7977 // default method found on a class with one found on the declaring interface directly and must
7978 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007979 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7980 &overriding_default_methods_}) {
7981 for (size_t i = 0; i < methods_vec->size(); ++i) {
7982 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007983 ArtMethod& new_method = *out;
7984 new_method.CopyFrom(def_method, pointer_size);
7985 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7986 // verified yet it shouldn't have methods that are skipping access checks.
7987 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7988 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007989 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007990 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7991 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7992 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7993 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007994 // Update the entry in the method array, as the array will be used for future lookups,
7995 // where thread suspension is allowed.
7996 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7997 // would not see them.
7998 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007999 ++out;
8000 }
8001 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008002 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
8003 &overriding_default_conflict_methods_}) {
8004 for (size_t i = 0; i < methods_vec->size(); ++i) {
8005 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00008006 ArtMethod& new_method = *out;
8007 new_method.CopyFrom(conf_method, pointer_size);
8008 // This is a type of default method (there are default method impls, just a conflict) so
8009 // mark this as a default, non-abstract method, since thats what it is. Also clear the
8010 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
8011 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01008012 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
8013 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01008014 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00008015 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01008016 constexpr uint32_t kMaskFlags =
8017 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00008018 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
8019 DCHECK(new_method.IsDefaultConflicting());
8020 // The actual method might or might not be marked abstract since we just copied it from a
8021 // (possibly default) interface method. We need to set it entry point to be the bridge so
8022 // that the compiler will not invoke the implementation of whatever method we copied from.
8023 EnsureThrowsInvocationError(class_linker_, &new_method);
8024 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008025 // Update the entry in the method array, as the array will be used for future lookups,
8026 // where thread suspension is allowed.
8027 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
8028 // would not see them.
8029 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00008030 ++out;
8031 }
8032 }
8033 methods->SetSize(new_method_count);
8034 class_linker_->UpdateClassMethods(klass_.Get(), methods);
8035}
8036
8037ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
8038 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01008039 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008040 // Update the vtable to the new method structures. We can skip this for interfaces since they
8041 // do not have vtables.
8042 const size_t old_vtable_count = old_vtable->GetLength();
8043 const size_t new_vtable_count = old_vtable_count +
8044 miranda_methods_.size() +
8045 default_methods_.size() +
8046 default_conflict_methods_.size();
8047
Vladimir Marko3068d582019-05-28 16:39:29 +01008048 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
8049 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00008050 if (UNLIKELY(vtable == nullptr)) {
8051 self_->AssertPendingOOMException();
8052 return nullptr;
8053 }
8054
8055 size_t vtable_pos = old_vtable_count;
8056 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8057 // Update all the newly copied method's indexes so they denote their placement in the vtable.
8058 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
8059 default_conflict_methods_,
8060 miranda_methods_}) {
8061 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008062 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008063 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
8064 // fields are references into the dex file the method was defined in. Since the ArtMethod
8065 // does not store that information it uses declaring_class_->dex_cache_.
8066 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
8067 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
8068 ++vtable_pos;
8069 }
8070 }
8071 DCHECK_EQ(vtable_pos, new_vtable_count);
8072
8073 // Update old vtable methods. We use the default_translations map to figure out what each
8074 // vtable entry should be updated to, if they need to be at all.
8075 for (size_t i = 0; i < old_vtable_count; ++i) {
8076 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
8077 // Try and find what we need to change this method to.
8078 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008079 if (translation_it != default_translations.end()) {
8080 if (translation_it->second.IsInConflict()) {
8081 // Find which conflict method we are to use for this method.
8082 MethodNameAndSignatureComparator old_method_comparator(
8083 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8084 // We only need to look through overriding_default_conflict_methods since this is an
8085 // overridden method we are fixing up here.
8086 ArtMethod* new_conflict_method = FindSameNameAndSignature(
8087 old_method_comparator, overriding_default_conflict_methods_);
8088 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
8089 translated_method = new_conflict_method;
8090 } else if (translation_it->second.IsAbstract()) {
8091 // Find which miranda method we are to use for this method.
8092 MethodNameAndSignatureComparator old_method_comparator(
8093 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8094 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
8095 miranda_methods_);
8096 DCHECK(miranda_method != nullptr);
8097 translated_method = miranda_method;
8098 } else {
8099 // Normal default method (changed from an older default or abstract interface method).
8100 DCHECK(translation_it->second.IsTranslation());
8101 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008102 auto it = move_table_.find(translated_method);
8103 DCHECK(it != move_table_.end());
8104 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00008105 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008106 } else {
8107 auto it = move_table_.find(translated_method);
8108 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008109 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008110
8111 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008112 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008113 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008114 if (kIsDebugBuild) {
8115 auto* methods = klass_->GetMethodsPtr();
8116 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008117 reinterpret_cast<uintptr_t>(translated_method));
8118 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008119 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8120 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008121 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008122 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008123 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008124 }
8125 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008126 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008127 return vtable;
8128}
8129
8130void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8131 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8132 const size_t ifcount = klass_->GetIfTableCount();
8133 // Go fix up all the stale iftable pointers.
8134 for (size_t i = 0; i < ifcount; ++i) {
8135 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008136 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8137 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008138 DCHECK(m != nullptr) << klass_->PrettyClass();
8139 auto it = move_table_.find(m);
8140 if (it != move_table_.end()) {
8141 auto* new_m = it->second;
8142 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8143 method_array->SetElementPtrSize(j, new_m, pointer_size);
8144 }
8145 }
8146 }
8147}
8148
8149void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8150 // Fix up IMT next.
8151 for (size_t i = 0; i < ImTable::kSize; ++i) {
8152 auto it = move_table_.find(out_imt[i]);
8153 if (it != move_table_.end()) {
8154 out_imt[i] = it->second;
8155 }
8156 }
8157}
8158
Alex Light705ad492015-09-21 11:36:30 -07008159// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008160bool ClassLinker::LinkInterfaceMethods(
8161 Thread* self,
8162 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07008163 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008164 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008165 ArtMethod** out_imt) {
8166 StackHandleScope<3> hs(self);
8167 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008168
8169 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008170 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008171 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008172 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008173 const size_t ifcount = klass->GetIfTableCount();
8174
Vladimir Marko921094a2017-01-12 18:37:06 +00008175 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008176
8177 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8178 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008179 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008180 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008181 const bool extend_super_iftable = has_superclass;
8182 if (has_superclass && fill_tables) {
8183 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008184 unimplemented_method,
8185 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008186 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008187 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008188 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008189 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8190 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008191 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008192 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8193 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008194 }
8195 }
8196
Vladimir Marko921094a2017-01-12 18:37:06 +00008197 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8198
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008199 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008200 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008201 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8202 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8203 // they will already be null. This has the additional benefit that the declarer of a miranda
8204 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008205 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008206 --i;
Alex Light9139e002015-10-09 15:59:48 -07008207 DCHECK_LT(i, ifcount);
8208
Alex Light705ad492015-09-21 11:36:30 -07008209 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008210 if (num_methods > 0) {
8211 StackHandleScope<2> hs2(self);
8212 const bool is_super = i < super_ifcount;
8213 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008214 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8215 // conflict methods. Just set this as nullptr in those cases.
8216 Handle<mirror::PointerArray> method_array(fill_tables
8217 ? hs2.NewHandle(iftable->GetMethodArray(i))
8218 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008219
Alex Lighte64300b2015-12-15 15:02:47 -08008220 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008221 ScopedNullHandle<mirror::PointerArray> null_handle;
8222 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008223 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008224
Alex Light9139e002015-10-09 15:59:48 -07008225 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8226 // and confusing. Default methods should always look through all the superclasses
8227 // because they are the last choice of an implementation. We get around this by looking
8228 // at the super-classes iftable methods (copied into method_array previously) when we are
8229 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008230 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008231 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008232 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008233 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008234 using_virtuals = true;
8235 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
8236 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008237 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008238 // For a new interface, however, we need the whole vtable in case a new
8239 // interface method is implemented in the whole superclass.
8240 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008241 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008242 input_vtable_array = vtable;
8243 input_array_length = input_vtable_array->GetLength();
8244 }
Alex Lighte64300b2015-12-15 15:02:47 -08008245
Alex Lighteb7c1442015-08-31 13:17:42 -07008246 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008247 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008248 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008249 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008250 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008251 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008252 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008253 // For each method listed in the interface's method list, find the
8254 // matching method in our class's method list. We want to favor the
8255 // subclass over the superclass, which just requires walking
8256 // back from the end of the vtable. (This only matters if the
8257 // superclass defines a private method and this class redefines
8258 // it -- otherwise it would use the same vtable slot. In .dex files
8259 // those don't end up in the virtual method table, so it shouldn't
8260 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008261 //
8262 // To find defaults we need to do the same but also go over interfaces.
8263 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008264 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008265 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008266 ArtMethod* vtable_method = using_virtuals ?
8267 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008268 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8269 ArtMethod* vtable_method_for_name_comparison =
8270 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008271 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008272 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008273 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008274 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8275 // allocations.
8276 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008277 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008278 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008279 vtable_method->PrettyMethod().c_str(),
8280 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008281 return false;
Alex Light9139e002015-10-09 15:59:48 -07008282 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008283 // We might have a newer, better, default method for this, so we just skip it. If we
8284 // are still using this we will select it again when scanning for default methods. To
8285 // obviate the need to copy the method again we will make a note that we already found
8286 // a default here.
8287 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008288 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008289 break;
8290 } else {
8291 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008292 if (LIKELY(fill_tables)) {
8293 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8294 // Place method in imt if entry is empty, place conflict otherwise.
8295 SetIMTRef(unimplemented_method,
8296 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008297 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008298 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008299 /*out*/imt_ptr);
8300 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008301 break;
8302 }
8303 }
Alex Light9139e002015-10-09 15:59:48 -07008304 }
8305 // Continue on to the next method if we are done.
8306 if (LIKELY(found_impl)) {
8307 continue;
8308 } else if (LIKELY(super_interface)) {
8309 // Don't look for a default implementation when the super-method is implemented directly
8310 // by the class.
8311 //
8312 // See if we can use the superclasses method and skip searching everything else.
8313 // Note: !found_impl && super_interface
8314 CHECK(extend_super_iftable);
8315 // If this is a super_interface method it is possible we shouldn't override it because a
8316 // superclass could have implemented it directly. We get the method the superclass used
8317 // to implement this to know if we can override it with a default method. Doing this is
8318 // safe since we know that the super_iftable is filled in so we can simply pull it from
8319 // there. We don't bother if this is not a super-classes interface since in that case we
8320 // have scanned the entire vtable anyway and would have found it.
8321 // TODO This is rather dirty but it is faster than searching through the entire vtable
8322 // every time.
8323 ArtMethod* supers_method =
8324 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8325 DCHECK(supers_method != nullptr);
8326 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008327 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008328 // The method is not overridable by a default method (i.e. it is directly implemented
8329 // in some class). Therefore move onto the next interface method.
8330 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008331 } else {
8332 // If the super-classes method is override-able by a default method we need to keep
8333 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8334 // 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 -07008335 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8336 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8337 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008338 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008339 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8340 << " and not 'nullptr' or "
8341 << supers_method->PrettyMethod()
8342 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008343 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008344 }
8345 }
8346 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008347 ArtMethod* current_method = helper.FindMethod(interface_method,
8348 interface_name_comparator,
8349 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008350 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008351 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008352 // We could not find an implementation for this method and since it is a brand new
8353 // interface we searched the entire vtable (and all default methods) for an
8354 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008355 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8356 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008357 }
8358
8359 if (current_method != nullptr) {
8360 // We found a default method implementation. Record it in the iftable and IMT.
8361 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8362 SetIMTRef(unimplemented_method,
8363 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008364 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008365 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008366 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008367 }
8368 }
Alex Light705ad492015-09-21 11:36:30 -07008369 } // For each method in interface end.
8370 } // if (num_methods > 0)
8371 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008372 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008373 if (helper.HasNewVirtuals()) {
8374 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8375 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8376 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8377
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008378 // 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 -07008379 // suspension assert.
8380 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008381
Alex Light705ad492015-09-21 11:36:30 -07008382 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008383 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008384 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008385 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008386 return false;
8387 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008388 helper.UpdateIfTable(iftable);
8389 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008390 }
Alex Light705ad492015-09-21 11:36:30 -07008391
Vladimir Marko921094a2017-01-12 18:37:06 +00008392 helper.CheckNoStaleMethodsInDexCache();
8393 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008394 } else {
8395 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008396 }
Alex Light705ad492015-09-21 11:36:30 -07008397 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008398 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008399 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008400 return true;
8401}
8402
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008403bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008404 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008405 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008406}
8407
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008408bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008409 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008410 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008411}
8412
Brian Carlstromdbc05252011-09-09 01:59:59 -07008413struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008414 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008415 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008416 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008417 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008418 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008419 // 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 -07008420 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8421 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008422 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008423 if (type1 == Primitive::kPrimNot) {
8424 // Reference always goes first.
8425 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008426 }
Vladimir Markod5777482014-11-12 17:02:02 +00008427 if (type2 == Primitive::kPrimNot) {
8428 // Reference always goes first.
8429 return false;
8430 }
8431 size_t size1 = Primitive::ComponentSize(type1);
8432 size_t size2 = Primitive::ComponentSize(type2);
8433 if (size1 != size2) {
8434 // Larger primitive types go first.
8435 return size1 > size2;
8436 }
8437 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8438 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008439 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008440 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8441 // by name and for equal names by type id index.
8442 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8443 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008444 }
8445};
8446
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008447bool ClassLinker::LinkFields(Thread* self,
8448 Handle<mirror::Class> klass,
8449 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008450 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008451 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008452 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008453 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8454 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008455
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008456 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008457 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008458 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008459 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008460 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008461 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008462 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008463 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008464 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008465 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008466 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008467 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008468
David Sehr709b0702016-10-13 09:12:37 -07008469 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008470
Brian Carlstromdbc05252011-09-09 01:59:59 -07008471 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008472 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008473 //
8474 // The overall sort order order is:
8475 // 1) All object reference fields, sorted alphabetically.
8476 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8477 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8478 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8479 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8480 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8481 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8482 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8483 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8484 //
8485 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8486 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008487 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008488 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008489 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008490 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008491 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008492 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008493 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8494 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008495
Fred Shih381e4ca2014-08-25 17:24:27 -07008496 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008497 size_t current_field = 0;
8498 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008499 FieldGaps gaps;
8500
Brian Carlstromdbc05252011-09-09 01:59:59 -07008501 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008502 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008503 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008504 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008505 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008506 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008507 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008508 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8509 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008510 MemberOffset old_offset = field_offset;
8511 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8512 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8513 }
Roland Levillain14d90572015-07-16 10:52:26 +01008514 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008515 grouped_and_sorted_fields.pop_front();
8516 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008517 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008518 field_offset = MemberOffset(field_offset.Uint32Value() +
8519 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008520 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008521 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8522 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008523 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8524 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8525 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8526 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008527 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8528 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008529 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008530
Elliott Hughesadb460d2011-10-05 17:02:34 -07008531 // 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 -07008532 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008533 // We know there are no non-reference fields in the Reference classes, and we know
8534 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008535 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008536 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008537 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008538 --num_reference_fields;
8539 }
8540
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008541 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008542 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008543 if (is_static) {
8544 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008545 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008546 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008547 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008548 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008549 if (num_reference_fields == 0 || super_class == nullptr) {
8550 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008551 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008552 if (super_class == nullptr ||
8553 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8554 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008555 }
8556 }
8557 if (kIsDebugBuild) {
8558 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8559 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008560 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008561 while (cur_super != nullptr) {
8562 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8563 cur_super = cur_super->GetSuperClass();
8564 }
8565 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008566 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008567 } else {
8568 // Check that there is at least num_reference_fields other than Object.class.
8569 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008570 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008571 }
8572 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008573 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008574 std::string temp;
8575 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8576 size_t previous_size = klass->GetObjectSize();
8577 if (previous_size != 0) {
8578 // Make sure that we didn't originally have an incorrect size.
8579 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008580 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008581 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008582 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008583 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008584
8585 if (kIsDebugBuild) {
8586 // Make sure that the fields array is ordered by name but all reference
8587 // offsets are at the beginning as far as alignment allows.
8588 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008589 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008590 : klass->GetFirstReferenceInstanceFieldOffset();
8591 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8592 num_reference_fields *
8593 sizeof(mirror::HeapReference<mirror::Object>));
8594 MemberOffset current_ref_offset = start_ref_offset;
8595 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008596 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008597 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008598 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8599 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008600 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008601 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008602 // NOTE: The field names can be the same. This is not possible in the Java language
8603 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008604 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008605 }
8606 Primitive::Type type = field->GetTypeAsPrimitiveType();
8607 bool is_primitive = type != Primitive::kPrimNot;
8608 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8609 strcmp("referent", field->GetName()) == 0) {
8610 is_primitive = true; // We lied above, so we have to expect a lie here.
8611 }
8612 MemberOffset offset = field->GetOffsetDuringLinking();
8613 if (is_primitive) {
8614 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8615 // Shuffled before references.
8616 size_t type_size = Primitive::ComponentSize(type);
8617 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8618 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8619 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8620 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8621 }
8622 } else {
8623 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8624 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8625 sizeof(mirror::HeapReference<mirror::Object>));
8626 }
8627 }
8628 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8629 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008630 return true;
8631}
8632
Vladimir Marko76649e82014-11-10 18:32:59 +00008633// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008634void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008635 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008636 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008637 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008638 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008639 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008640 // Compute reference offsets unless our superclass overflowed.
8641 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8642 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008643 if (num_reference_fields != 0u) {
8644 // All of the fields that contain object references are guaranteed be grouped in memory
8645 // starting at an appropriately aligned address after super class object data.
8646 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8647 sizeof(mirror::HeapReference<mirror::Object>));
8648 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008649 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008650 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008651 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008652 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008653 reference_offsets |= (0xffffffffu << start_bit) &
8654 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008655 }
8656 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008657 }
8658 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008659 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008660}
8661
Vladimir Marko18090d12018-06-01 16:53:12 +01008662ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8663 ObjPtr<mirror::DexCache> dex_cache) {
8664 StackHandleScope<1> hs(Thread::Current());
8665 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8666 return DoResolveString(string_idx, h_dex_cache);
8667}
8668
8669ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8670 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008671 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008672 uint32_t utf16_length;
8673 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008674 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008675 if (string != nullptr) {
8676 dex_cache->SetResolvedString(string_idx, string);
8677 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008678 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008679}
8680
Vladimir Marko18090d12018-06-01 16:53:12 +01008681ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8682 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008683 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008684 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008685 uint32_t utf16_length;
8686 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008687 ObjPtr<mirror::String> string =
8688 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008689 if (string != nullptr) {
8690 dex_cache->SetResolvedString(string_idx, string);
8691 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008692 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008693}
8694
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008695ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008696 ObjPtr<mirror::Class> referrer) {
8697 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8698}
8699
8700ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008701 ObjPtr<mirror::DexCache> dex_cache,
8702 ObjPtr<mirror::ClassLoader> class_loader) {
8703 const DexFile& dex_file = *dex_cache->GetDexFile();
8704 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8705 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8706 ObjPtr<mirror::Class> type = nullptr;
8707 if (descriptor[1] == '\0') {
8708 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8709 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008710 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008711 } else {
8712 Thread* const self = Thread::Current();
8713 DCHECK(self != nullptr);
8714 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8715 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008716 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008717 }
8718 if (type != nullptr) {
8719 if (type->IsResolved()) {
8720 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008721 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008722 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008723 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008724 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008725 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008726}
8727
Andreas Gampeb0625e02019-05-01 12:43:31 -07008728template <typename RefType>
8729ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008730 StackHandleScope<2> hs(Thread::Current());
8731 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8732 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8733 return DoResolveType(type_idx, dex_cache, class_loader);
8734}
8735
Andreas Gampe4835d212018-11-21 14:55:10 -08008736// Instantiate the above.
8737template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8738 ArtField* referrer);
8739template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8740 ArtMethod* referrer);
8741template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8742 ObjPtr<mirror::Class> referrer);
8743
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008744ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008745 Handle<mirror::DexCache> dex_cache,
8746 Handle<mirror::ClassLoader> class_loader) {
8747 Thread* self = Thread::Current();
8748 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8749 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8750 if (resolved != nullptr) {
8751 // TODO: we used to throw here if resolved's class loader was not the
8752 // boot class loader. This was to permit different classes with the
8753 // same name to be loaded simultaneously by different loaders
8754 dex_cache->SetResolvedType(type_idx, resolved);
8755 } else {
8756 CHECK(self->IsExceptionPending())
8757 << "Expected pending exception for failed resolution of: " << descriptor;
8758 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8759 StackHandleScope<1> hs(self);
8760 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008761 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008762 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8763 self->ClearException();
8764 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8765 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008766 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008767 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008768 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008769 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008770 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008771}
8772
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008773ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8774 ObjPtr<mirror::DexCache> dex_cache,
8775 ObjPtr<mirror::ClassLoader> class_loader,
8776 uint32_t method_idx) {
8777 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8778 // functions can optimize the search if the dex_cache is the same as the DexCache
8779 // of the class, with fall-back to name and signature search otherwise.
8780 ArtMethod* resolved = nullptr;
8781 if (klass->IsInterface()) {
8782 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8783 } else {
8784 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8785 }
8786 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008787 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008788 hiddenapi::ShouldDenyAccessToMember(resolved,
8789 hiddenapi::AccessContext(class_loader, dex_cache),
8790 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008791 resolved = nullptr;
8792 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008793 if (resolved != nullptr) {
8794 // In case of jmvti, the dex file gets verified before being registered, so first
8795 // check if it's registered before checking class tables.
8796 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008797 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8798 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008799 << "DexFile referrer: " << dex_file.GetLocation()
8800 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8801 // Be a good citizen and update the dex cache to speed subsequent calls.
8802 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008803 // Disable the following invariant check as the verifier breaks it. b/73760543
8804 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8805 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8806 // << "Method: " << resolved->PrettyMethod() << ", "
8807 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8808 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008809 }
8810 return resolved;
8811}
8812
David Brazdil4525e0b2018-04-05 16:57:32 +01008813// Returns true if `method` is either null or hidden.
8814// Does not print any warnings if it is hidden.
8815static bool CheckNoSuchMethod(ArtMethod* method,
8816 ObjPtr<mirror::DexCache> dex_cache,
8817 ObjPtr<mirror::ClassLoader> class_loader)
8818 REQUIRES_SHARED(Locks::mutator_lock_) {
8819 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008820 hiddenapi::ShouldDenyAccessToMember(method,
8821 hiddenapi::AccessContext(class_loader, dex_cache),
8822 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008823}
8824
8825ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8826 ObjPtr<mirror::DexCache> dex_cache,
8827 ObjPtr<mirror::ClassLoader> class_loader,
8828 uint32_t method_idx) {
8829 if (klass->IsInterface()) {
8830 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8831 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8832 } else {
8833 // If there was an interface method with the same signature, we would have
8834 // found it in the "copied" methods. Only DCHECK that the interface method
8835 // really does not exist.
8836 if (kIsDebugBuild) {
8837 ArtMethod* method =
8838 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8839 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8840 }
8841 return nullptr;
8842 }
8843}
8844
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008845template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008846ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008847 Handle<mirror::DexCache> dex_cache,
8848 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008849 ArtMethod* referrer,
8850 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008851 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008852 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008853 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008854 PointerSize pointer_size = image_pointer_size_;
8855 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008856 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008857 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8858 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008859 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8860 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008861 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008862 return resolved;
8863 }
Vladimir Marko89011192017-12-11 13:45:05 +00008864 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008865 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008866 ObjPtr<mirror::Class> klass = nullptr;
8867 if (valid_dex_cache_method) {
8868 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8869 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008870 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008871 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008872 // We normaly should not end up here. However the verifier currently doesn't guarantee
8873 // the invariant of having the klass in the class table. b/73760543
8874 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008875 }
Vladimir Markoba118822017-06-12 15:41:56 +01008876 } else {
8877 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008878 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008879 if (klass == nullptr) {
8880 DCHECK(Thread::Current()->IsExceptionPending());
8881 return nullptr;
8882 }
8883 }
8884
8885 // Check if the invoke type matches the class type.
8886 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008887 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008888 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008889 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008890 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008891 }
Vladimir Markoba118822017-06-12 15:41:56 +01008892
8893 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008894 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008895 }
Vladimir Markoba118822017-06-12 15:41:56 +01008896
8897 // Note: We can check for IllegalAccessError only if we have a referrer.
8898 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8899 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8900 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8901 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8902 resolved,
8903 dex_cache.Get(),
8904 method_idx,
8905 type)) {
8906 DCHECK(Thread::Current()->IsExceptionPending());
8907 return nullptr;
8908 }
8909 }
8910
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008911 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008912 if (LIKELY(resolved != nullptr) &&
8913 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8914 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008915 return resolved;
8916 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008917 // If we had a method, or if we can find one with another lookup type,
8918 // it's an incompatible-class-change error.
8919 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008920 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008921 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008922 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008923 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008924 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008925 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008926 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8927 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008928 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008929 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008930 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008931 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008932 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008933}
8934
Vladimir Marko89011192017-12-11 13:45:05 +00008935ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008936 Handle<mirror::DexCache> dex_cache,
8937 Handle<mirror::ClassLoader> class_loader) {
8938 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008939 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008940 if (resolved != nullptr) {
8941 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008942 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8943 return resolved;
8944 }
8945 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008946 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008947 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008948 if (klass == nullptr) {
8949 Thread::Current()->AssertPendingException();
8950 return nullptr;
8951 }
8952 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008953 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8954 } else {
8955 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008956 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008957 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008958 hiddenapi::ShouldDenyAccessToMember(
8959 resolved,
8960 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8961 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008962 resolved = nullptr;
8963 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008964 return resolved;
8965}
8966
Vladimir Markof44d36c2017-03-14 14:18:46 +00008967ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8968 ObjPtr<mirror::DexCache> dex_cache,
8969 ObjPtr<mirror::ClassLoader> class_loader,
8970 bool is_static) {
8971 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008972 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008973 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8974 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008975 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008976 }
8977 if (klass == nullptr) {
8978 // The class has not been resolved yet, so the field is also unresolved.
8979 return nullptr;
8980 }
8981 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008982
David Brazdil1ab0fa82018-05-04 11:28:03 +01008983 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008984}
8985
Vladimir Markoe11dd502017-12-08 14:09:45 +00008986ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008987 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008988 Handle<mirror::ClassLoader> class_loader,
8989 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008990 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008991 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008992 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008993 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008994 return resolved;
8995 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008996 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008997 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008998 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008999 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08009000 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07009001 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009002 }
9003
David Brazdil1ab0fa82018-05-04 11:28:03 +01009004 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07009005 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08009006 const char* name = dex_file.GetFieldName(field_id);
9007 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009008 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009009 }
Ian Rogersb067ac22011-12-13 18:05:09 -08009010 return resolved;
9011}
9012
Vladimir Markoe11dd502017-12-08 14:09:45 +00009013ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009014 Handle<mirror::DexCache> dex_cache,
9015 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009016 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009017 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009018 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009019 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009020 return resolved;
9021 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009022 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009023 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009024 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009025 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009026 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009027 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009028 }
9029
David Brazdil1ab0fa82018-05-04 11:28:03 +01009030 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9031 if (resolved == nullptr) {
9032 const char* name = dex_file.GetFieldName(field_id);
9033 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009034 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009035 }
9036 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009037}
9038
David Brazdil1ab0fa82018-05-04 11:28:03 +01009039ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9040 ObjPtr<mirror::DexCache> dex_cache,
9041 ObjPtr<mirror::ClassLoader> class_loader,
9042 uint32_t field_idx,
9043 bool is_static) {
9044 ArtField* resolved = nullptr;
9045 Thread* self = is_static ? Thread::Current() : nullptr;
9046 const DexFile& dex_file = *dex_cache->GetDexFile();
9047
9048 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
9049 : klass->FindInstanceField(dex_cache, field_idx);
9050
9051 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009052 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009053 const char* name = dex_file.GetFieldName(field_id);
9054 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9055 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
9056 : klass->FindInstanceField(name, type);
9057 }
9058
9059 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009060 hiddenapi::ShouldDenyAccessToMember(resolved,
9061 hiddenapi::AccessContext(class_loader, dex_cache),
9062 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009063 resolved = nullptr;
9064 }
9065
9066 if (resolved != nullptr) {
9067 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9068 }
9069
9070 return resolved;
9071}
9072
9073ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9074 ObjPtr<mirror::DexCache> dex_cache,
9075 ObjPtr<mirror::ClassLoader> class_loader,
9076 uint32_t field_idx) {
9077 ArtField* resolved = nullptr;
9078 Thread* self = Thread::Current();
9079 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009080 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009081
9082 const char* name = dex_file.GetFieldName(field_id);
9083 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9084 resolved = mirror::Class::FindField(self, klass, name, type);
9085
9086 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009087 hiddenapi::ShouldDenyAccessToMember(resolved,
9088 hiddenapi::AccessContext(class_loader, dex_cache),
9089 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009090 resolved = nullptr;
9091 }
9092
9093 if (resolved != nullptr) {
9094 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9095 }
9096
9097 return resolved;
9098}
9099
Vladimir Markoaf940202017-12-08 15:01:18 +00009100ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9101 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009102 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009103 Handle<mirror::DexCache> dex_cache,
9104 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009105 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009106 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009107
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009108 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009109 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009110 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009111 }
9112
Narayan Kamath25352fc2016-08-03 12:46:58 +01009113 StackHandleScope<4> hs(self);
9114
9115 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009116 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009117 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009118 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009119 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009120 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009121 DCHECK(self->IsExceptionPending());
9122 return nullptr;
9123 }
9124
9125 // Then resolve the argument types.
9126 //
9127 // TODO: Is there a better way to figure out the number of method arguments
9128 // other than by looking at the shorty ?
9129 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9130
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009131 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009132 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9133 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009134 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009135 DCHECK(self->IsExceptionPending());
9136 return nullptr;
9137 }
9138
9139 DexFileParameterIterator it(dex_file, proto_id);
9140 int32_t i = 0;
9141 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9142 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009143 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009144 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009145 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009146 DCHECK(self->IsExceptionPending());
9147 return nullptr;
9148 }
9149
9150 method_params->Set(i++, param_class.Get());
9151 }
9152
9153 DCHECK(!it.HasNext());
9154
9155 Handle<mirror::MethodType> type = hs.NewHandle(
9156 mirror::MethodType::Create(self, return_type, method_params));
9157 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9158
9159 return type.Get();
9160}
9161
Vladimir Markoaf940202017-12-08 15:01:18 +00009162ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009163 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009164 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009165 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009166 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9167 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009168 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009169}
9170
Vladimir Marko5aead702019-03-27 11:00:36 +00009171ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009172 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009173 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009174 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009175 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009176 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9177 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009178 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009179 bool is_static;
9180 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009181 switch (handle_type) {
9182 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009183 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009184 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009185 is_static = true;
9186 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009187 break;
9188 }
9189 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009190 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009191 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009192 is_static = true;
9193 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009194 break;
9195 }
9196 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009197 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009198 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009199 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009200 num_params = 2;
9201 break;
9202 }
9203 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009204 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009205 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009206 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009207 num_params = 1;
9208 break;
9209 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009210 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009211 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009212 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009213 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009214 case DexFile::MethodHandleType::kInvokeInterface:
9215 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009216 }
9217
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009218 ArtField* target_field =
9219 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9220 if (LIKELY(target_field != nullptr)) {
9221 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9222 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9223 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9224 ThrowIllegalAccessErrorField(referring_class, target_field);
9225 return nullptr;
9226 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009227 if (UNLIKELY(is_put && target_field->IsFinal())) {
9228 ThrowIllegalAccessErrorField(referring_class, target_field);
9229 return nullptr;
9230 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009231 } else {
9232 DCHECK(Thread::Current()->IsExceptionPending());
9233 return nullptr;
9234 }
9235
9236 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009237 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009238 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9239 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009240 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009241 DCHECK(self->IsExceptionPending());
9242 return nullptr;
9243 }
9244
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009245 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009246 Handle<mirror::Class> return_type;
9247 switch (handle_type) {
9248 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009249 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009250 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009251 break;
9252 }
9253 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009254 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009255 break;
9256 }
9257 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009258 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009259 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009260 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009261 break;
9262 }
9263 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009264 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009265 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009266 break;
9267 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009268 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009269 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009270 case DexFile::MethodHandleType::kInvokeConstructor:
9271 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009272 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009273 UNREACHABLE();
9274 }
9275
9276 for (int32_t i = 0; i < num_params; ++i) {
9277 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9278 DCHECK(self->IsExceptionPending());
9279 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009280 }
9281 }
9282
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009283 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009284 DCHECK(self->IsExceptionPending());
9285 return nullptr;
9286 }
9287
9288 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009289 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9290 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009291 DCHECK(self->IsExceptionPending());
9292 return nullptr;
9293 }
Orion Hodson631827d2017-04-10 14:53:47 +01009294
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009295 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9296 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9297}
9298
Vladimir Marko5aead702019-03-27 11:00:36 +00009299ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009300 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009301 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009302 ArtMethod* referrer) {
9303 DexFile::MethodHandleType handle_type =
9304 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9305 mirror::MethodHandle::Kind kind;
9306 uint32_t receiver_count = 0;
9307 ArtMethod* target_method = nullptr;
9308 switch (handle_type) {
9309 case DexFile::MethodHandleType::kStaticPut:
9310 case DexFile::MethodHandleType::kStaticGet:
9311 case DexFile::MethodHandleType::kInstancePut:
9312 case DexFile::MethodHandleType::kInstanceGet:
9313 UNREACHABLE();
9314 case DexFile::MethodHandleType::kInvokeStatic: {
9315 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9316 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009317 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9318 method_handle.field_or_method_idx_,
9319 referrer,
9320 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009321 break;
9322 }
9323 case DexFile::MethodHandleType::kInvokeInstance: {
9324 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9325 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009326 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9327 method_handle.field_or_method_idx_,
9328 referrer,
9329 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009330 break;
9331 }
9332 case DexFile::MethodHandleType::kInvokeConstructor: {
9333 // Constructors are currently implemented as a transform. They
9334 // are special cased later in this method.
9335 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9336 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009337 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9338 method_handle.field_or_method_idx_,
9339 referrer,
9340 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009341 break;
9342 }
9343 case DexFile::MethodHandleType::kInvokeDirect: {
9344 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9345 receiver_count = 1;
9346 StackHandleScope<2> hs(self);
9347 // A constant method handle with type kInvokeDirect can refer to
9348 // a method that is private or to a method in a super class. To
9349 // disambiguate the two options, we resolve the method ignoring
9350 // the invocation type to determine if the method is private. We
9351 // then resolve again specifying the intended invocation type to
9352 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009353 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009354 hs.NewHandle(referrer->GetDexCache()),
9355 hs.NewHandle(referrer->GetClassLoader()));
9356 if (UNLIKELY(target_method == nullptr)) {
9357 break;
9358 }
9359
9360 if (target_method->IsPrivate()) {
9361 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009362 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9363 method_handle.field_or_method_idx_,
9364 referrer,
9365 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009366 } else {
9367 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009368 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9369 method_handle.field_or_method_idx_,
9370 referrer,
9371 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009372 if (UNLIKELY(target_method == nullptr)) {
9373 break;
9374 }
9375 // Find the method specified in the parent in referring class
9376 // so invoke-super invokes the method in the parent of the
9377 // referrer.
9378 target_method =
9379 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9380 kRuntimePointerSize);
9381 }
9382 break;
9383 }
9384 case DexFile::MethodHandleType::kInvokeInterface: {
9385 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9386 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009387 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9388 method_handle.field_or_method_idx_,
9389 referrer,
9390 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009391 break;
9392 }
Orion Hodson631827d2017-04-10 14:53:47 +01009393 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009394
9395 if (UNLIKELY(target_method == nullptr)) {
9396 DCHECK(Thread::Current()->IsExceptionPending());
9397 return nullptr;
9398 }
9399
9400 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9401 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9402 uint32_t access_flags = target_method->GetAccessFlags();
9403 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9404 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9405 return nullptr;
9406 }
9407
9408 // Calculate the number of parameters from the method shorty. We add the
9409 // receiver count (0 or 1) and deduct one for the return value.
9410 uint32_t shorty_length;
9411 target_method->GetShorty(&shorty_length);
9412 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9413
Orion Hodsonecd58562018-09-24 11:27:33 +01009414 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009415 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009416 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9417 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9418 if (method_params.Get() == nullptr) {
9419 DCHECK(self->IsExceptionPending());
9420 return nullptr;
9421 }
9422
Orion Hodsonecd58562018-09-24 11:27:33 +01009423 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009424 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009425 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009426 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009427 // Insert receiver. Use the class identified in the method handle rather than the declaring
9428 // class of the resolved method which may be super class or default interface method
9429 // (b/115964401).
9430 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9431 // receiver_class should have been resolved when resolving the target method.
9432 DCHECK(receiver_class != nullptr);
9433 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009434 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009435
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009436 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009437 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009438 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009439 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009440 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009441 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009442 if (nullptr == klass) {
9443 DCHECK(self->IsExceptionPending());
9444 return nullptr;
9445 }
9446 method_params->Set(index++, klass);
9447 it.Next();
9448 }
9449
Orion Hodsonecd58562018-09-24 11:27:33 +01009450 Handle<mirror::Class> return_type =
9451 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009452 if (UNLIKELY(return_type.IsNull())) {
9453 DCHECK(self->IsExceptionPending());
9454 return nullptr;
9455 }
9456
9457 Handle<mirror::MethodType>
9458 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9459 if (UNLIKELY(method_type.IsNull())) {
9460 DCHECK(self->IsExceptionPending());
9461 return nullptr;
9462 }
9463
9464 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9465 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9466 Handle<mirror::MethodHandlesLookup> lookup =
9467 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9468 return lookup->FindConstructor(self, constructor_class, method_type);
9469 }
9470
9471 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9472 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9473}
9474
Vladimir Markoaf940202017-12-08 15:01:18 +00009475ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9476 uint32_t method_handle_idx,
9477 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009478 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009479 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009480 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009481 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9482 case DexFile::MethodHandleType::kStaticPut:
9483 case DexFile::MethodHandleType::kStaticGet:
9484 case DexFile::MethodHandleType::kInstancePut:
9485 case DexFile::MethodHandleType::kInstanceGet:
9486 return ResolveMethodHandleForField(self, method_handle, referrer);
9487 case DexFile::MethodHandleType::kInvokeStatic:
9488 case DexFile::MethodHandleType::kInvokeInstance:
9489 case DexFile::MethodHandleType::kInvokeConstructor:
9490 case DexFile::MethodHandleType::kInvokeDirect:
9491 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009492 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009493 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009494}
9495
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009496bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9497 return (entry_point == GetQuickResolutionStub()) ||
9498 (quick_resolution_trampoline_ == entry_point);
9499}
9500
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009501bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9502 return (entry_point == GetQuickToInterpreterBridge()) ||
9503 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9504}
9505
9506bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9507 return (entry_point == GetQuickGenericJniStub()) ||
9508 (quick_generic_jni_trampoline_ == entry_point);
9509}
9510
David Sehra49e0532017-08-25 08:05:29 -07009511bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9512 return entry_point == GetJniDlsymLookupStub();
9513}
9514
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009515const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9516 return GetQuickGenericJniStub();
9517}
9518
Mathieu Chartiere401d142015-04-22 13:56:20 -07009519void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009520 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009521 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9522 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009523 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009524 }
9525}
9526
Alex Lightdb01a092017-04-03 15:39:55 -07009527void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9528 DCHECK(method->IsObsolete());
9529 // We cannot mess with the entrypoints of native methods because they are used to determine how
9530 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9531 if (!method->IsNative()) {
9532 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9533 }
9534}
9535
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009536void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009537 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009538 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009539 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9540 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009541 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9542 os << "Dumping registered class loaders\n";
9543 size_t class_loader_index = 0;
9544 for (const ClassLoaderData& class_loader : class_loaders_) {
9545 ObjPtr<mirror::ClassLoader> loader =
9546 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9547 if (loader != nullptr) {
9548 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9549 bool saw_one_dex_file = false;
9550 for (const DexCacheData& dex_cache : dex_caches_) {
9551 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9552 if (saw_one_dex_file) {
9553 os << ":";
9554 }
9555 saw_one_dex_file = true;
9556 os << dex_cache.dex_file->GetLocation();
9557 }
9558 }
9559 os << "]";
9560 bool found_parent = false;
9561 if (loader->GetParent() != nullptr) {
9562 size_t parent_index = 0;
9563 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9564 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9565 soa.Self()->DecodeJObject(class_loader2.weak_root));
9566 if (loader2 == loader->GetParent()) {
9567 os << ", parent #" << parent_index;
9568 found_parent = true;
9569 break;
9570 }
9571 parent_index++;
9572 }
9573 if (!found_parent) {
9574 os << ", unregistered parent of type "
9575 << loader->GetParent()->GetClass()->PrettyDescriptor();
9576 }
9577 } else {
9578 os << ", no parent";
9579 }
9580 os << "\n";
9581 }
9582 }
9583 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009584 Runtime* runtime = Runtime::Current();
9585 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9586 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009587}
9588
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009589class CountClassesVisitor : public ClassLoaderVisitor {
9590 public:
9591 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9592
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009593 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009594 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009595 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009596 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009597 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9598 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009599 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009600 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009601
9602 size_t num_zygote_classes;
9603 size_t num_non_zygote_classes;
9604};
9605
9606size_t ClassLinker::NumZygoteClasses() const {
9607 CountClassesVisitor visitor;
9608 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009609 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009610}
9611
9612size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009613 CountClassesVisitor visitor;
9614 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009615 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009616}
9617
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009618size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009619 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009620 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009621 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009622}
9623
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009624pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009625 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009626}
9627
9628pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009629 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009630}
9631
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009632void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009633 DCHECK(!init_done_);
9634
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009635 DCHECK(klass != nullptr);
9636 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009637
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009638 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009639 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009640 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9641 int32_t index = static_cast<int32_t>(class_root);
9642 DCHECK(class_roots->Get(index) == nullptr);
9643 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009644}
9645
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009646ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9647 Thread* self,
9648 const std::vector<const DexFile*>& dex_files,
9649 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009650 Handle<mirror::ClassLoader> parent_loader,
9651 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009652
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009653 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009654
Mathieu Chartierc7853442015-03-27 14:35:38 -07009655 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009656 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009657
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009658 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009659 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009660 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009661 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009662 mirror::ObjectArray<mirror::Object>::Alloc(self,
9663 dex_elements_class.Get(),
9664 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009665 Handle<mirror::Class> h_dex_element_class =
9666 hs.NewHandle(dex_elements_class->GetComponentType());
9667
Mathieu Chartierc7853442015-03-27 14:35:38 -07009668 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009669 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009670 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009671
Andreas Gampe08883de2016-11-08 13:20:52 -08009672 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009673 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009674
Andreas Gampe08883de2016-11-08 13:20:52 -08009675 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009676 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009677
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009678 // Fill the elements array.
9679 int32_t index = 0;
9680 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009681 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009682
Calin Juravle7865ac72017-06-28 11:03:12 -07009683 // CreateWellKnownClassLoader is only used by gtests and compiler.
9684 // 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 -07009685 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9686 self,
9687 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009688 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009689 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009690
Mathieu Chartier3738e982017-05-12 16:07:28 -07009691 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9692 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009693 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009694 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009695 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009696 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009697
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009698 Handle<mirror::String> h_file_name = hs2.NewHandle(
9699 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009700 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009701 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9702
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009703 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009704 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009705 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009706
9707 h_dex_elements->Set(index, h_element.Get());
9708 index++;
9709 }
9710 DCHECK_EQ(index, h_dex_elements->GetLength());
9711
9712 // Create DexPathList.
9713 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009714 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009715 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009716 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009717 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009718 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9719 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9720 // elements.
9721 {
9722 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9723 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9724 DCHECK(native_lib_dirs != nullptr);
9725 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9726 DCHECK(list_class != nullptr);
9727 {
9728 StackHandleScope<1> h_list_scope(self);
9729 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9730 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9731 DCHECK(list_init);
9732 list_class = h_list_class.Get();
9733 }
9734 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9735 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9736 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9737 // normally never null), as long as one does not try to add elements, this will still
9738 // work.
9739 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9740 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009741
Calin Juravle7865ac72017-06-28 11:03:12 -07009742 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009743 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9744 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009745 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009746 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009747 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009748 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009749 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009750 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009751
9752 // Make a pretend boot-classpath.
9753 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009754 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009755 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009756 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009757 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009758 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009759 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009760 if (parent_loader.Get() == nullptr) {
9761 ScopedObjectAccessUnchecked soa(self);
9762 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9763 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9764 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9765 } else {
9766 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9767 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009768
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009769 ArtField* shared_libraries_field =
9770 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9771 DCHECK(shared_libraries_field != nullptr);
9772 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9773
9774 return h_class_loader.Get();
9775}
9776
9777jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9778 const std::vector<const DexFile*>& dex_files,
9779 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009780 jobject parent_loader,
9781 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009782 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9783 WellKnownClasses::dalvik_system_PathClassLoader) ||
9784 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009785 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9786 self->GetJniEnv()->IsSameObject(loader_class,
9787 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009788
9789 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9790 // We could move the jobject to the callers, but all call-sites do this...
9791 ScopedObjectAccessUnchecked soa(self);
9792
9793 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009794 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009795
9796 Handle<mirror::Class> h_loader_class =
9797 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009798 Handle<mirror::ClassLoader> h_parent =
9799 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9800 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9801 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009802
9803 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9804 self,
9805 dex_files,
9806 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009807 h_parent,
9808 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009809
9810 // Make it a global ref and return.
9811 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009812 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009813 return soa.Env()->NewGlobalRef(local_ref.get());
9814}
9815
Calin Juravle7865ac72017-06-28 11:03:12 -07009816jobject ClassLinker::CreatePathClassLoader(Thread* self,
9817 const std::vector<const DexFile*>& dex_files) {
9818 return CreateWellKnownClassLoader(self,
9819 dex_files,
9820 WellKnownClasses::dalvik_system_PathClassLoader,
9821 nullptr);
9822}
9823
Andreas Gampe8ac75952015-06-02 21:01:45 -07009824void ClassLinker::DropFindArrayClassCache() {
9825 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9826 find_array_class_cache_next_victim_ = 0;
9827}
9828
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009829void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009830 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009831 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009832 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009833 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9834 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009835 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009836 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009837 }
9838 }
9839}
9840
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009841void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9842 for (const ClassLoaderData& data : class_loaders_) {
9843 LinearAlloc* alloc = data.allocator;
9844 if (alloc != nullptr && !visitor->Visit(alloc)) {
9845 break;
9846 }
9847 }
9848}
9849
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009850void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9851 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009852 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009853 Thread* const self = Thread::Current();
9854 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009855 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009856 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009857 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009858 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9859 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009860 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009861 }
9862}
9863
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009864void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009865 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009866 std::vector<ClassLoaderData> to_delete;
9867 // Do the delete outside the lock to avoid lock violation in jit code cache.
9868 {
9869 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9870 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9871 const ClassLoaderData& data = *it;
9872 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009873 ObjPtr<mirror::ClassLoader> class_loader =
9874 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009875 if (class_loader != nullptr) {
9876 ++it;
9877 } else {
9878 VLOG(class_linker) << "Freeing class loader";
9879 to_delete.push_back(data);
9880 it = class_loaders_.erase(it);
9881 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009882 }
9883 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009884 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009885 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009886 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009887 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009888}
9889
Vladimir Marko21300532017-01-24 18:06:55 +00009890class GetResolvedClassesVisitor : public ClassVisitor {
9891 public:
9892 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9893 : result_(result),
9894 ignore_boot_classes_(ignore_boot_classes),
9895 last_resolved_classes_(result->end()),
9896 last_dex_file_(nullptr),
9897 vlog_is_on_(VLOG_IS_ON(class_linker)),
9898 extra_stats_(),
9899 last_extra_stats_(extra_stats_.end()) { }
9900
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009901 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009902 if (!klass->IsProxyClass() &&
9903 !klass->IsArrayClass() &&
9904 klass->IsResolved() &&
9905 !klass->IsErroneousResolved() &&
9906 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9907 const DexFile& dex_file = klass->GetDexFile();
9908 if (&dex_file != last_dex_file_) {
9909 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009910 DexCacheResolvedClasses resolved_classes(
9911 dex_file.GetLocation(),
9912 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9913 dex_file.GetLocationChecksum(),
9914 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009915 last_resolved_classes_ = result_->find(resolved_classes);
9916 if (last_resolved_classes_ == result_->end()) {
9917 last_resolved_classes_ = result_->insert(resolved_classes).first;
9918 }
9919 }
9920 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9921 if (UNLIKELY(vlog_is_on_) && added) {
9922 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9923 if (last_extra_stats_ == extra_stats_.end() ||
9924 last_extra_stats_->first != resolved_classes) {
9925 last_extra_stats_ = extra_stats_.find(resolved_classes);
9926 if (last_extra_stats_ == extra_stats_.end()) {
9927 last_extra_stats_ =
9928 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9929 }
9930 }
9931 }
9932 }
9933 return true;
9934 }
9935
9936 void PrintStatistics() const {
9937 if (vlog_is_on_) {
9938 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9939 auto it = extra_stats_.find(std::addressof(resolved_classes));
9940 DCHECK(it != extra_stats_.end());
9941 const ExtraStats& extra_stats = it->second;
9942 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9943 << " has " << resolved_classes.GetClasses().size() << " / "
9944 << extra_stats.number_of_class_defs_ << " resolved classes";
9945 }
9946 }
9947 }
9948
9949 private:
9950 struct ExtraStats {
9951 explicit ExtraStats(uint32_t number_of_class_defs)
9952 : number_of_class_defs_(number_of_class_defs) {}
9953 uint32_t number_of_class_defs_;
9954 };
9955
9956 std::set<DexCacheResolvedClasses>* result_;
9957 bool ignore_boot_classes_;
9958 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9959 const DexFile* last_dex_file_;
9960
9961 // Statistics.
9962 bool vlog_is_on_;
9963 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9964 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9965};
9966
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009967std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009968 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009969 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009970 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009971 std::set<DexCacheResolvedClasses> ret;
9972 VLOG(class_linker) << "Collecting resolved classes";
9973 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009974 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9975 VisitClasses(&visitor);
9976 if (VLOG_IS_ON(class_linker)) {
9977 visitor.PrintStatistics();
9978 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009979 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009980 return ret;
9981}
9982
Mathieu Chartier65975772016-08-05 10:46:36 -07009983class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9984 public:
9985 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9986 : method_(method),
9987 pointer_size_(pointer_size) {}
9988
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009989 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009990 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9991 holder_ = klass;
9992 }
9993 // Return false to stop searching if holder_ is not null.
9994 return holder_ == nullptr;
9995 }
9996
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009997 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009998 const ArtMethod* const method_;
9999 const PointerSize pointer_size_;
10000};
10001
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010002ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010003 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10004 CHECK(method->IsCopied());
10005 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10006 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010007 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010008}
10009
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010010ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
10011 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010012 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +010010013 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010014 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010015}
10016
Roland Levillain0e840272018-08-23 19:55:30 +010010017// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +010010018template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010019 uint32_t method_idx,
10020 Handle<mirror::DexCache> dex_cache,
10021 Handle<mirror::ClassLoader> class_loader,
10022 ArtMethod* referrer,
10023 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +010010024template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010025 uint32_t method_idx,
10026 Handle<mirror::DexCache> dex_cache,
10027 Handle<mirror::ClassLoader> class_loader,
10028 ArtMethod* referrer,
10029 InvokeType type);
10030
Roland Levillain0e840272018-08-23 19:55:30 +010010031// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010032template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010033 Thread* self,
10034 ObjPtr<mirror::Class> java_lang_Class,
10035 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010036template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010037 Thread* self,
10038 ObjPtr<mirror::Class> java_lang_Class,
10039 uint32_t class_size);
10040
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010041} // namespace art