blob: 9d9abe3d892debc3f45b9a99c8552eef47408c53 [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
390ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
391 Thread* self, Handle<mirror::Class> klass) {
392 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
393 // Thanks to the x86 memory model, we do not need any memory fences and
394 // we can immediately mark the class as visibly initialized.
395 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
396 return nullptr;
397 }
398 if (Runtime::Current()->IsActiveTransaction()) {
399 // Transactions are single-threaded, so we can mark the class as visibly intialized.
400 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
401 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
402 return nullptr;
403 }
404 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
405 MutexLock lock(self, visibly_initialized_callback_lock_);
406 if (visibly_initialized_callback_ == nullptr) {
407 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
408 }
409 DCHECK(!visibly_initialized_callback_->IsFull());
410 visibly_initialized_callback_->AddClass(self, klass.Get());
411
412 if (visibly_initialized_callback_->IsFull()) {
413 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
414 running_visibly_initialized_callbacks_.push_front(*callback);
415 return callback;
416 } else {
417 return nullptr;
418 }
419}
420
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800421void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
422 bool wrap_in_no_class_def,
423 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700424 // The class failed to initialize on a previous attempt, so we want to throw
425 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
426 // failed in verification, in which case v2 5.4.1 says we need to re-throw
427 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800428 Runtime* const runtime = Runtime::Current();
429 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700430 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000431 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
432 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800433 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700434 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800435 } else {
436 extra = verify_error->AsThrowable()->Dump();
437 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700438 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800439 if (log) {
440 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
441 << ": " << extra;
442 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700443 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700444
David Sehr709b0702016-10-13 09:12:37 -0700445 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800446 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800447 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700448 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700449 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000450 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700451 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000452 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
453 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800454 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800455 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800456 }
Alex Lightd6251582016-10-31 11:12:30 -0700457 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
458 // might have meant to go down the earlier if statement with the original error but it got
459 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000460 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800461 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
462 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
463 // exception will be a cause.
464 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700465 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700466 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700467 }
468}
469
Brian Carlstromb23eab12014-10-08 17:55:21 -0700470static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700471 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700472 if (VLOG_IS_ON(class_linker)) {
473 std::string temp;
474 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000475 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700476 }
477}
478
479static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700480 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700481 Thread* self = Thread::Current();
482 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700483
484 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700485 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700486
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800487 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
488 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
489 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800490 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800491 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
492 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
493 // could have caused the error.
494 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
495 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
496 << " failed initialization: "
497 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800498 }
499
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700500 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700501 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
502 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700503
Elliott Hughesa4f94742012-05-29 16:28:38 -0700504 // We only wrap non-Error exceptions; an Error can just be used as-is.
505 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000506 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700507 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700508 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700509}
510
Fred Shih381e4ca2014-08-25 17:24:27 -0700511// Gap between two fields in object layout.
512struct FieldGap {
513 uint32_t start_offset; // The offset from the start of the object.
514 uint32_t size; // The gap size of 1, 2, or 4 bytes.
515};
516struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800517 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700518 }
519 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
520 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800521 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700522 // Note that the priority queue returns the largest element, so operator()
523 // should return true if lhs is less than rhs.
524 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700525 }
526};
Andreas Gampec55bb392018-09-21 00:02:02 +0000527using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700528
529// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800530static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700531 DCHECK(gaps != nullptr);
532
533 uint32_t current_offset = gap_start;
534 while (current_offset != gap_end) {
535 size_t remaining = gap_end - current_offset;
536 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
537 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
538 current_offset += sizeof(uint32_t);
539 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
540 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
541 current_offset += sizeof(uint16_t);
542 } else {
543 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
544 current_offset += sizeof(uint8_t);
545 }
546 DCHECK_LE(current_offset, gap_end) << "Overran gap";
547 }
548}
549// Shuffle fields forward, making use of gaps whenever possible.
550template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000551static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700552 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700553 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700554 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700555 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700556 DCHECK(current_field_idx != nullptr);
557 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700558 DCHECK(gaps != nullptr);
559 DCHECK(field_offset != nullptr);
560
561 DCHECK(IsPowerOfTwo(n));
562 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700563 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700564 Primitive::Type type = field->GetTypeAsPrimitiveType();
565 if (Primitive::ComponentSize(type) < n) {
566 break;
567 }
568 if (!IsAligned<n>(field_offset->Uint32Value())) {
569 MemberOffset old_offset = *field_offset;
570 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
571 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
572 }
David Sehr709b0702016-10-13 09:12:37 -0700573 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700574 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700575 if (!gaps->empty() && gaps->top().size >= n) {
576 FieldGap gap = gaps->top();
577 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100578 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700579 field->SetOffset(MemberOffset(gap.start_offset));
580 if (gap.size > n) {
581 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
582 }
583 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100584 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700585 field->SetOffset(*field_offset);
586 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
587 }
588 ++(*current_field_idx);
589 }
590}
591
Andreas Gampe87658f32019-04-18 18:39:02 +0000592ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700593 : boot_class_table_(new ClassTable()),
594 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800595 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800596 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700597 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000598 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700599 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000600 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Ian Rogers98379392014-02-24 16:53:16 -0800601 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800602 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100603 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800604 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700605 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100606 visibly_initialized_callback_lock_("visibly initialized callback lock"),
607 visibly_initialized_callback_(nullptr),
Andreas Gampe7dface32017-07-25 21:32:59 -0700608 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
609 // For CHA disabled during Aot, see b/34193647.
610
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700611 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700612 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
613 "Array cache size wrong.");
614 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700615}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700616
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800617void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700618 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800619 if (c2 == nullptr) {
620 LOG(FATAL) << "Could not find class " << descriptor;
621 UNREACHABLE();
622 }
623 if (c1.Get() != c2) {
624 std::ostringstream os1, os2;
625 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
626 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
627 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
628 << ". This is most likely the result of a broken build. Make sure that "
629 << "libcore and art projects match.\n\n"
630 << os1.str() << "\n\n" << os2.str();
631 UNREACHABLE();
632 }
633}
634
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800635bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
636 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800637 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700638
Mathieu Chartiere401d142015-04-22 13:56:20 -0700639 Thread* const self = Thread::Current();
640 Runtime* const runtime = Runtime::Current();
641 gc::Heap* const heap = runtime->GetHeap();
642
Jeff Haodcdc85b2015-12-04 14:06:18 -0800643 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700644 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700645
Mathieu Chartiere401d142015-04-22 13:56:20 -0700646 // Use the pointer size from the runtime since we are probably creating the image.
647 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
648
Elliott Hughes30646832011-10-13 16:59:46 -0700649 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700650 // 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 -0800651 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700652 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700653 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700654 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
655 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000656 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100657 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800658 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100659 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700660 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700661 if (kUseBakerReadBarrier) {
662 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800663 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700664 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700665 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800666 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700667 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700668
Elliott Hughes418d20f2011-09-22 14:00:39 -0700669 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700670 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700671 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700672 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700673 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700674
Ian Rogers23435d02012-09-24 11:23:12 -0700675 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700676 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700677 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800678 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700679 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700680 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000681 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700682
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700683 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800684 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
685 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100686 runtime->SetSentinel(heap->AllocNonMovableObject(self,
687 java_lang_Object.Get(),
688 java_lang_Object->GetObjectSize(),
689 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700690
Igor Murashkin86083f72017-10-27 10:59:04 -0700691 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000692 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700693 // It might seem the lock here is unnecessary, however all the SubtypeCheck
694 // functions are annotated to require locks all the way down.
695 //
696 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
697 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000698 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
699 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700700 }
701
Ian Rogers23435d02012-09-24 11:23:12 -0700702 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700703 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700704 AllocClass(self, java_lang_Class.Get(),
705 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700706 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700707
Roland Levillain0e840272018-08-23 19:55:30 +0100708 // Setup java.lang.String.
709 //
710 // We make this class non-movable for the unlikely case where it were to be
711 // moved by a sticky-bit (minor) collection when using the Generational
712 // Concurrent Copying (CC) collector, potentially creating a stale reference
713 // in the `klass_` field of one of its instances allocated in the Large-Object
714 // Space (LOS) -- see the comment about the dirty card scanning logic in
715 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700716 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700717 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100718 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700719 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000720 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400721
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700722 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700723 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700724 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700725 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000726 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700727
Ian Rogers23435d02012-09-24 11:23:12 -0700728 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700729 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100730 mirror::ObjectArray<mirror::Class>::Alloc(self,
731 object_array_class.Get(),
732 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700733 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100734 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
735 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
736 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
737 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100738 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
739 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700740
Mathieu Chartier6beced42016-11-15 15:51:31 -0800741 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
742 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
743
Vladimir Marko02610552018-06-04 14:38:00 +0100744 // Create array interface entries to populate once we can load system classes.
745 object_array_class->SetIfTable(AllocIfTable(self, 2));
746 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
747
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700748 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100749 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
750 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
751 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
752 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
753 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
754 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
755 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
756 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
757 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700758
Vladimir Marko70e2a762019-07-12 16:49:00 +0100759 // Allocate the primitive array classes. We need only the native pointer
760 // array at this point (int[] or long[], depending on architecture) but
761 // we shall perform the same setup steps for all primitive array classes.
762 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
763 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
764 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
765 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
766 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
767 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
768 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
769 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700770
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700771 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700772
Ian Rogers52813c92012-10-11 11:50:38 -0700773 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700774 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700775 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100776 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100777 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700778 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000779 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700780
Alex Lightd6251582016-10-31 11:12:30 -0700781
782 // Setup dalvik.system.ClassExt
783 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
784 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100785 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000786 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700787
Mathieu Chartier66f19252012-09-18 08:57:04 -0700788 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700789 Handle<mirror::Class> object_array_string(hs.NewHandle(
790 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700791 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700792 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100793 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700794
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000795 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700796 // Create runtime resolution and imt conflict methods.
797 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000798 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
799 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700800
Ian Rogers23435d02012-09-24 11:23:12 -0700801 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
802 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
803 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800804 if (boot_class_path.empty()) {
805 *error_msg = "Boot classpath is empty.";
806 return false;
807 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800808 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800809 if (dex_file.get() == nullptr) {
810 *error_msg = "Null dex file.";
811 return false;
812 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700813 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800814 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700815 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700816
817 // now we can use FindSystemClass
818
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700819 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
820 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700821 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800822 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700823 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700824 quick_resolution_trampoline_ = GetQuickResolutionStub();
825 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
826 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700827 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700828
Alex Lightd6251582016-10-31 11:12:30 -0700829 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000830 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800831 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700832 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000833 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800834 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000835 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800836 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700837 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000838 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700839 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
840 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700841
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800842 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
843 // in class_table_.
844 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700845
Vladimir Marko70e2a762019-07-12 16:49:00 +0100846 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
847 // arrays - can't be done until Object has a vtable and component classes are loaded.
848 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
849 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
850 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
851 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
852 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
853 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
854 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
855 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
856 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
857 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
858 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700859
Ian Rogers23435d02012-09-24 11:23:12 -0700860 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700861 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800862 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700863 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800864 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700865 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
866 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100867 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
868 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700869
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700870 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
871 // suspension.
872 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000873 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700874 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000875 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700876 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000877 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700878 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000879 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700880
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700881 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100882 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700883
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800884 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700885
Ian Rogers23435d02012-09-24 11:23:12 -0700886 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100887 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
888 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700889
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700890 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100891 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700892 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100893 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700894
895 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700896 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
897 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100898 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700899
900 // Create java.lang.reflect.Constructor.class root and array root.
901 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
902 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100903 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700904 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
905 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100906 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700907
908 // Create java.lang.reflect.Method.class root and array root.
909 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
910 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100911 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700912 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
913 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100914 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700915
Orion Hodson005ac512017-10-24 15:43:43 +0100916 // Create java.lang.invoke.CallSite.class root
917 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
918 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100919 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100920
Narayan Kamathafa48272016-08-03 12:46:58 +0100921 // Create java.lang.invoke.MethodType.class root
922 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
923 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100924 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100925
926 // Create java.lang.invoke.MethodHandleImpl.class root
927 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
928 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100929 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100930 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100931
Orion Hodsonc069a302017-01-18 09:23:12 +0000932 // Create java.lang.invoke.MethodHandles.Lookup.class root
933 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
934 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100935 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000936
Orion Hodson005ac512017-10-24 15:43:43 +0100937 // Create java.lang.invoke.VarHandle.class root
938 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000939 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100940 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100941
942 // Create java.lang.invoke.FieldVarHandle.class root
943 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
944 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100945 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100946
947 // Create java.lang.invoke.ArrayElementVarHandle.class root
948 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
949 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100950 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100951
952 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
953 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
954 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100955 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100956
957 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
958 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
959 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100960 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000961
Narayan Kamath000e1882016-10-24 17:14:25 +0100962 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
963 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100964 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100965
Brian Carlstrom1f870082011-08-23 16:02:11 -0700966 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700967 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000968 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800969 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700970 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700971 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
972 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700973 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700974 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700975 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700976 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700977 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700978 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700979 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700980 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700981 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700982 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
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::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700985
Ian Rogers23435d02012-09-24 11:23:12 -0700986 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700987 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700988 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700989 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100990 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700991
jeffhao8cd6dda2012-02-22 10:15:34 -0800992 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700993 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100994 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100995 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700996 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100997 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
998 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
999 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001000 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001001 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1002 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001003
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001004 // Create conflict tables that depend on the class linker.
1005 runtime->FixupConflictTables();
1006
Ian Rogers98379392014-02-24 16:53:16 -08001007 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001008
Brian Carlstroma004aa92012-02-08 18:05:09 -08001009 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001010
1011 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001012}
1013
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001014static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1015 REQUIRES_SHARED(Locks::mutator_lock_) {
1016 // Find String.<init> -> StringFactory bindings.
1017 ObjPtr<mirror::Class> string_factory_class =
1018 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1019 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001020 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001021 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1022 // Update the primordial thread.
1023 self->InitStringEntryPoints();
1024}
1025
Ian Rogers98379392014-02-24 16:53:16 -08001026void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001027 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001028
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001029 CreateStringInitBindings(self, this);
1030
Brian Carlstrom16192862011-09-12 17:50:06 -07001031 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001032 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001033 // as the types of the field can't be resolved prior to the runtime being
1034 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001035 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001036 Handle<mirror::Class> java_lang_ref_Reference =
1037 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001038 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1039 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001040
Mathieu Chartierc7853442015-03-27 14:35:38 -07001041 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001042 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1043 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001044
Mathieu Chartierc7853442015-03-27 14:35:38 -07001045 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001046 CHECK_STREQ(queue->GetName(), "queue");
1047 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001048
Mathieu Chartierc7853442015-03-27 14:35:38 -07001049 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001050 CHECK_STREQ(queueNext->GetName(), "queueNext");
1051 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001052
Mathieu Chartierc7853442015-03-27 14:35:38 -07001053 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001054 CHECK_STREQ(referent->GetName(), "referent");
1055 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001056
Mathieu Chartierc7853442015-03-27 14:35:38 -07001057 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001058 CHECK_STREQ(zombie->GetName(), "zombie");
1059 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001060
Brian Carlstroma663ea52011-08-19 23:33:41 -07001061 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001062 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001063 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001064 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001065 CHECK(klass != nullptr);
1066 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001067 // note SetClassRoot does additional validation.
1068 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001069 }
1070
Vladimir Marko02610552018-06-04 14:38:00 +01001071 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001072
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001073 // disable the slow paths in FindClass and CreatePrimitiveClass now
1074 // that Object, Class, and Object[] are setup
1075 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001076
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001077 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1078 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1079 // ensure that the class will be initialized.
1080 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001081 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001082
1083 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1084 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1085 // Strange, but don't crash.
1086 LOG(WARNING) << "Could not prepare StackOverflowError.";
1087 self->ClearException();
1088 }
1089 }
1090
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001091 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001092}
1093
Vladimir Markodcfcce42018-06-27 10:00:28 +00001094void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001095 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1096 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001097 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001098 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001099 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -07001100 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001101 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +00001102 } else {
1103 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001104 }
1105 }
1106}
1107
Jeff Haodcdc85b2015-12-04 14:06:18 -08001108struct TrampolineCheckData {
1109 const void* quick_resolution_trampoline;
1110 const void* quick_imt_conflict_trampoline;
1111 const void* quick_generic_jni_trampoline;
1112 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001113 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001114 ArtMethod* m;
1115 bool error;
1116};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001118bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1119 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001120 CHECK(!init_done_);
1121
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001122 Runtime* const runtime = Runtime::Current();
1123 Thread* const self = Thread::Current();
1124 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001125 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1126 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001127 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1128 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001129 if (!ValidPointerSize(pointer_size_unchecked)) {
1130 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001131 return false;
1132 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001133 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001134 if (!runtime->IsAotCompiler()) {
1135 // Only the Aot compiler supports having an image with a different pointer size than the
1136 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1137 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001138 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001139 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001140 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001141 sizeof(void*));
1142 return false;
1143 }
1144 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001145 DCHECK(!runtime->HasResolutionMethod());
1146 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1147 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1148 runtime->SetImtUnimplementedMethod(
1149 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1150 runtime->SetCalleeSaveMethod(
1151 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1152 CalleeSaveType::kSaveAllCalleeSaves);
1153 runtime->SetCalleeSaveMethod(
1154 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1155 CalleeSaveType::kSaveRefsOnly);
1156 runtime->SetCalleeSaveMethod(
1157 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1158 CalleeSaveType::kSaveRefsAndArgs);
1159 runtime->SetCalleeSaveMethod(
1160 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1161 CalleeSaveType::kSaveEverything);
1162 runtime->SetCalleeSaveMethod(
1163 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1164 CalleeSaveType::kSaveEverythingForClinit);
1165 runtime->SetCalleeSaveMethod(
1166 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1167 CalleeSaveType::kSaveEverythingForSuspendCheck);
1168
Jeff Haodcdc85b2015-12-04 14:06:18 -08001169 std::vector<const OatFile*> oat_files =
1170 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1171 DCHECK(!oat_files.empty());
1172 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001173 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1174 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1175 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1176 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1177 if (kIsDebugBuild) {
1178 // Check that the other images use the same trampoline.
1179 for (size_t i = 1; i < oat_files.size(); ++i) {
1180 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1181 const void* ith_quick_resolution_trampoline =
1182 ith_oat_header.GetQuickResolutionTrampoline();
1183 const void* ith_quick_imt_conflict_trampoline =
1184 ith_oat_header.GetQuickImtConflictTrampoline();
1185 const void* ith_quick_generic_jni_trampoline =
1186 ith_oat_header.GetQuickGenericJniTrampoline();
1187 const void* ith_quick_to_interpreter_bridge_trampoline =
1188 ith_oat_header.GetQuickToInterpreterBridge();
1189 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1190 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1191 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1192 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1193 // Make sure that all methods in this image do not contain those trampolines as
1194 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1195 TrampolineCheckData data;
1196 data.error = false;
1197 data.pointer_size = GetImagePointerSize();
1198 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1199 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1200 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1201 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1202 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001203 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1204 if (obj->IsClass()) {
1205 ObjPtr<mirror::Class> klass = obj->AsClass();
1206 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1207 const void* entrypoint =
1208 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1209 if (entrypoint == data.quick_resolution_trampoline ||
1210 entrypoint == data.quick_imt_conflict_trampoline ||
1211 entrypoint == data.quick_generic_jni_trampoline ||
1212 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1213 data.m = &m;
1214 data.error = true;
1215 return;
1216 }
1217 }
1218 }
1219 };
1220 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001221 if (data.error) {
1222 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001223 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001224 *error_msg = "Found an ArtMethod with a bad entrypoint";
1225 return false;
1226 }
1227 }
1228 }
1229 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001230
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001231 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001232 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001233 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001234 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001235
Vladimir Marko024d69f2019-06-13 10:52:32 +01001236 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1237 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1238 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1239 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1240 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1241 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001242
Vladimir Marko4433c432018-12-04 14:57:47 +00001243 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1244 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001245 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001246 // Boot class loader, use a null handle.
1247 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001248 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001249 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001250 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001251 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001252 /*out*/&dex_files,
1253 error_msg)) {
1254 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001255 }
David Brazdil3e8aae02019-03-26 18:48:02 +00001256 // Assert that if absolute boot classpath locations were provided, they were
1257 // assigned to the loaded dex files.
1258 if (kIsDebugBuild && IsAbsoluteLocation(boot_class_path_locations[i])) {
1259 for (const auto& dex_file : dex_files) {
1260 DCHECK_EQ(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1261 boot_class_path_locations[i]);
1262 }
1263 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001264 // Append opened dex files at the end.
1265 boot_dex_files_.insert(boot_dex_files_.end(),
1266 std::make_move_iterator(dex_files.begin()),
1267 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001268 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001269 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1270 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1271 }
Ian Rogers98379392014-02-24 16:53:16 -08001272 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001273
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001274 VLOG(startup) << __FUNCTION__ << " exiting";
1275 return true;
1276}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001277
Vladimir Marko4433c432018-12-04 14:57:47 +00001278void ClassLinker::AddExtraBootDexFiles(
1279 Thread* self,
1280 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1281 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1282 AppendToBootClassPath(self, *dex_file);
1283 boot_dex_files_.push_back(std::move(dex_file));
1284 }
1285}
1286
Jeff Hao5872d7c2016-04-27 11:07:41 -07001287bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001288 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001289 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001290 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1291 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001292}
1293
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001294static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1295 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001296 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001297 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001298 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001299 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001300 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001301 DCHECK(dex_file_field != nullptr);
1302 DCHECK(dex_file_name_field != nullptr);
1303 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001304 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001305 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001306 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001307 // Null dex file means it was probably a jar with no dex files, return a null string.
1308 *out_name = nullptr;
1309 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001310 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001311 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001312 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001313 *out_name = name_object->AsString();
1314 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001315 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001316 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001317}
1318
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001319static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1320 ObjPtr<mirror::ClassLoader> class_loader,
1321 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1322 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001323 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001324 StackHandleScope<1> hs(soa.Self());
1325 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001326 // Get element names. Sets error to true on failure.
1327 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1328 REQUIRES_SHARED(Locks::mutator_lock_) {
1329 if (element == nullptr) {
1330 *error_msg = "Null dex element";
1331 *error = true; // Null element is a critical error.
1332 return false; // Had an error, stop the visit.
1333 }
1334 ObjPtr<mirror::String> name;
1335 if (!GetDexPathListElementName(element, &name)) {
1336 *error_msg = "Invalid dex path list element";
1337 *error = true; // Invalid element, make it a critical error.
1338 return false; // Stop the visit.
1339 }
1340 if (name != nullptr) {
1341 dex_files->push_front(name);
1342 }
1343 return true; // Continue with the next Element.
1344 };
1345 bool error = VisitClassLoaderDexElements(soa,
1346 handle,
1347 add_element_names,
1348 /*defaultReturn=*/ false);
1349 return !error;
1350}
1351
1352static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1353 ObjPtr<mirror::ClassLoader> image_class_loader,
1354 ObjPtr<mirror::ClassLoader> class_loader,
1355 std::string* error_msg)
1356 REQUIRES_SHARED(Locks::mutator_lock_) {
1357 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1358 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1359 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001360 return false;
1361 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001362 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1363 *error_msg = "Hierarchies don't match";
1364 return false;
1365 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1366 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1367 image_class_loader->PrettyTypeOf().c_str(),
1368 class_loader->PrettyTypeOf().c_str());
1369 return false;
1370 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1371 class_loader->GetClass()) {
1372 *error_msg = StringPrintf("Unknown class loader type %s",
1373 class_loader->PrettyTypeOf().c_str());
1374 // Unsupported class loader.
1375 return false;
1376 }
1377 return true;
1378}
1379
1380static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1381 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1382 std::string* error_msg)
1383 REQUIRES_SHARED(Locks::mutator_lock_) {
1384 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1385 std::equal(image_dex_files.begin(),
1386 image_dex_files.end(),
1387 loader_dex_files.begin(),
1388 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1389 REQUIRES_SHARED(Locks::mutator_lock_) {
1390 return lhs->Equals(rhs);
1391 });
1392 if (!equal) {
1393 VLOG(image) << "Image dex files " << image_dex_files.size();
1394 for (ObjPtr<mirror::String> name : image_dex_files) {
1395 VLOG(image) << name->ToModifiedUtf8();
1396 }
1397 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1398 for (ObjPtr<mirror::String> name : loader_dex_files) {
1399 VLOG(image) << name->ToModifiedUtf8();
1400 }
1401 *error_msg = "Mismatch in dex files";
1402 }
1403 return equal;
1404}
1405
1406static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1407 ObjPtr<mirror::ClassLoader> image_class_loader,
1408 ObjPtr<mirror::ClassLoader> class_loader,
1409 bool check_dex_file_names,
1410 std::string* error_msg)
1411 REQUIRES_SHARED(Locks::mutator_lock_) {
1412 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1413 return false;
1414 }
1415
1416 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1417 // No need to check further.
1418 return true;
1419 }
1420
1421 if (check_dex_file_names) {
1422 std::list<ObjPtr<mirror::String>> image_dex_files;
1423 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001424 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001425 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001426
1427 std::list<ObjPtr<mirror::String>> loader_dex_files;
1428 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1429 return false;
1430 }
1431
1432 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1433 return false;
1434 }
1435 }
1436
1437 ArtField* field =
1438 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1439 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1440 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1441 if (shared_libraries_image_loader == nullptr) {
1442 if (shared_libraries_loader != nullptr) {
1443 *error_msg = "Mismatch in shared libraries";
1444 return false;
1445 }
1446 } else if (shared_libraries_loader == nullptr) {
1447 *error_msg = "Mismatch in shared libraries";
1448 return false;
1449 } else {
1450 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1451 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1452 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1453 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1454 if (array1->GetLength() != array2->GetLength()) {
1455 *error_msg = "Mismatch in number of shared libraries";
1456 return false;
1457 }
1458
1459 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1460 // Do a full comparison of the class loaders, including comparing their dex files.
1461 if (!CompareClassLoaders(soa,
1462 array1->Get(i),
1463 array2->Get(i),
1464 /*check_dex_file_names=*/ true,
1465 error_msg)) {
1466 return false;
1467 }
1468 }
1469 }
1470
1471 // Do a full comparison of the class loaders, including comparing their dex files.
1472 if (!CompareClassLoaders(soa,
1473 image_class_loader->GetParent(),
1474 class_loader->GetParent(),
1475 /*check_dex_file_names=*/ true,
1476 error_msg)) {
1477 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001478 }
1479 return true;
1480}
1481
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001482class CHAOnDeleteUpdateClassVisitor {
1483 public:
1484 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1485 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1486 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1487 self_(Thread::Current()) {}
1488
1489 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1490 // This class is going to be unloaded. Tell CHA about it.
1491 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1492 return true;
1493 }
1494 private:
1495 const LinearAlloc* allocator_;
1496 const ClassHierarchyAnalysis* cha_;
1497 const PointerSize pointer_size_;
1498 const Thread* self_;
1499};
1500
Chris Wailes0c61be42018-09-26 17:27:34 -07001501/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001502 * A class used to ensure that all references to strings interned in an AppImage have been
1503 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001504 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001505class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001506 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001507 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1508 const InternTable::UnorderedSet& image_interns)
1509 : space_(space),
1510 image_interns_(image_interns),
1511 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001512
Chris Wailes0c61be42018-09-26 17:27:34 -07001513 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001514 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001515 if (referred_obj != nullptr &&
1516 space_.HasAddress(referred_obj.Ptr()) &&
1517 referred_obj->IsString()) {
1518 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001519 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1520 if (it != image_interns_.end() && it->Read() == referred_str) {
1521 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001522 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001523 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001524 }
1525
Chris Wailes0c61be42018-09-26 17:27:34 -07001526 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001527 mirror::CompressedReference<mirror::Object>* root) const
1528 REQUIRES_SHARED(Locks::mutator_lock_) {
1529 if (!root->IsNull()) {
1530 VisitRoot(root);
1531 }
1532 }
1533
Chris Wailes0c61be42018-09-26 17:27:34 -07001534 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001535 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001536 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001537 }
1538
1539 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001540 void operator()(ObjPtr<mirror::Object> obj,
1541 MemberOffset offset,
1542 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001543 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001544 // References within image or across images don't need a read barrier.
1545 ObjPtr<mirror::Object> referred_obj =
1546 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1547 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001548 }
1549
1550 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1551 ObjPtr<mirror::Reference> ref) const
1552 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001553 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001554 }
1555
Vladimir Marko8e05f092019-06-10 11:10:38 +01001556 size_t GetCount() const {
1557 return count_;
1558 }
1559
1560 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001561 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001562 const InternTable::UnorderedSet& image_interns_;
1563 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001564};
1565
Chris Wailes0c61be42018-09-26 17:27:34 -07001566/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001567 * This function counts references to strings interned in the AppImage.
1568 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001569 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001570size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1571 const InternTable::UnorderedSet& image_interns)
1572 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001573 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1574 const ImageHeader& image_header = space.GetImageHeader();
1575 const uint8_t* target_base = space.GetMemMap()->Begin();
1576 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001577
1578 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1579 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001580
Vladimir Marko8e05f092019-06-10 11:10:38 +01001581 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001582 bitmap->VisitMarkedRange(objects_begin,
1583 objects_end,
1584 [&space, &visitor](mirror::Object* obj)
1585 REQUIRES_SHARED(Locks::mutator_lock_) {
1586 if (space.HasAddress(obj)) {
1587 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001588 obj->VisitReferences</* kVisitNativeRoots= */ true,
1589 kVerifyNone,
1590 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001591 } else {
1592 // Don't visit native roots for non-dex-cache as they can't contain
1593 // native references to strings. This is verified during compilation
1594 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001595 obj->VisitReferences</* kVisitNativeRoots= */ false,
1596 kVerifyNone,
1597 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001598 }
1599 }
1600 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001601 return visitor.GetCount();
1602}
1603
1604template <typename Visitor>
1605static void VisitInternedStringReferences(
1606 gc::space::ImageSpace* space,
1607 bool use_preresolved_strings,
1608 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1609 const uint8_t* target_base = space->Begin();
1610 const ImageSection& sro_section =
1611 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1612 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1613
1614 VLOG(image)
1615 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1616 << num_string_offsets;
1617
1618 const auto* sro_base =
1619 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1620
1621 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1622 uint32_t base_offset = sro_base[offset_index].first;
1623
1624 if (HasDexCacheStringNativeRefTag(base_offset)) {
1625 base_offset = ClearDexCacheNativeRefTags(base_offset);
1626 DCHECK_ALIGNED(base_offset, 2);
1627
1628 ObjPtr<mirror::DexCache> dex_cache =
1629 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1630 uint32_t string_slot_index = sro_base[offset_index].second;
1631
1632 mirror::StringDexCachePair source =
1633 dex_cache->GetStrings()[string_slot_index].load(std::memory_order_relaxed);
1634 ObjPtr<mirror::String> referred_string = source.object.Read();
1635 DCHECK(referred_string != nullptr);
1636
1637 ObjPtr<mirror::String> visited = visitor(referred_string);
1638 if (visited != referred_string) {
1639 // Because we are not using a helper function we need to mark the GC card manually.
1640 WriteBarrier::ForEveryFieldWrite(dex_cache);
1641 dex_cache->GetStrings()[string_slot_index].store(
1642 mirror::StringDexCachePair(visited, source.index), std::memory_order_relaxed);
1643 }
1644 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1645 if (use_preresolved_strings) {
1646 base_offset = ClearDexCacheNativeRefTags(base_offset);
1647 DCHECK_ALIGNED(base_offset, 2);
1648
1649 ObjPtr<mirror::DexCache> dex_cache =
1650 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1651 uint32_t string_index = sro_base[offset_index].second;
1652
Mathieu Chartier77f84fc2019-06-14 12:49:54 -07001653 GcRoot<mirror::String>* preresolved_strings =
1654 dex_cache->GetPreResolvedStrings();
1655 // Handle calls to ClearPreResolvedStrings that might occur concurrently by the profile
1656 // saver that runs shortly after startup. In case the strings are cleared, there is nothing
1657 // to fix up.
1658 if (preresolved_strings != nullptr) {
1659 ObjPtr<mirror::String> referred_string =
1660 preresolved_strings[string_index].Read();
1661 if (referred_string != nullptr) {
1662 ObjPtr<mirror::String> visited = visitor(referred_string);
1663 if (visited != referred_string) {
1664 // Because we are not using a helper function we need to mark the GC card manually.
1665 WriteBarrier::ForEveryFieldWrite(dex_cache);
1666 preresolved_strings[string_index] = GcRoot<mirror::String>(visited);
1667 }
1668 }
Vladimir Marko8e05f092019-06-10 11:10:38 +01001669 }
1670 }
1671 } else {
1672 uint32_t raw_member_offset = sro_base[offset_index].second;
1673 DCHECK_ALIGNED(base_offset, 2);
1674 DCHECK_ALIGNED(raw_member_offset, 2);
1675
1676 ObjPtr<mirror::Object> obj_ptr =
1677 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1678 MemberOffset member_offset(raw_member_offset);
1679 ObjPtr<mirror::String> referred_string =
1680 obj_ptr->GetFieldObject<mirror::String,
1681 kVerifyNone,
1682 kWithoutReadBarrier,
1683 /* kIsVolatile= */ false>(member_offset);
1684 DCHECK(referred_string != nullptr);
1685
1686 ObjPtr<mirror::String> visited = visitor(referred_string);
1687 if (visited != referred_string) {
1688 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1689 /* kCheckTransaction= */ false,
1690 kVerifyNone,
1691 /* kIsVolatile= */ false>(member_offset, visited);
1692 }
1693 }
1694 }
1695}
1696
1697static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1698 REQUIRES_SHARED(Locks::mutator_lock_) {
1699 InternTable::UnorderedSet image_interns;
1700 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1701 if (section.Size() > 0) {
1702 size_t read_count;
1703 const uint8_t* data = space->Begin() + section.Offset();
1704 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1705 image_set.swap(image_interns);
1706 }
1707 size_t num_recorded_refs = 0u;
1708 VisitInternedStringReferences(
1709 space,
1710 /*use_preresolved_strings=*/ true,
1711 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1712 REQUIRES_SHARED(Locks::mutator_lock_) {
1713 auto it = image_interns.find(GcRoot<mirror::String>(str));
1714 CHECK(it != image_interns.end());
1715 CHECK(it->Read() == str);
1716 ++num_recorded_refs;
1717 return str;
1718 });
1719 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1720 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001721}
1722
Andreas Gampe2af99022017-04-25 08:32:59 -07001723// new_class_set is the set of classes that were read from the class table section in the image.
1724// If there was no class table section, it is null.
1725// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001726class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001727 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001728 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001729 ClassLinker* class_linker,
1730 gc::space::ImageSpace* space,
1731 Handle<mirror::ClassLoader> class_loader,
1732 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001733 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001734 REQUIRES(!Locks::dex_lock_)
1735 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001736
Chris Wailesfbeef462018-10-19 14:16:35 -07001737 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001738 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001739};
1740
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001741void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001742 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001743 gc::space::ImageSpace* space,
1744 Handle<mirror::ClassLoader> class_loader,
1745 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001746 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001747 REQUIRES(!Locks::dex_lock_)
1748 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001749 ScopedTrace app_image_timing("AppImage:Updating");
1750
Vladimir Marko8e05f092019-06-10 11:10:38 +01001751 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1752 // In debug build, verify the string references before applying
1753 // the Runtime::LoadAppImageStartupCache() option.
1754 VerifyInternedStringReferences(space);
1755 }
1756
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001757 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001758 Runtime* const runtime = Runtime::Current();
1759 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001760 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001761 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001762 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001763 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001764 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001765 const size_t num_dex_caches = dex_caches->GetLength();
1766 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001767 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001768 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001769 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001770 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001771 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1772 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001773 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001774
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001775 if (!load_app_image_startup_cache) {
1776 dex_cache->ClearPreResolvedStrings();
1777 }
1778
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001779 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001780 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001781 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001782 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001783 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001784 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001785 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001786
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001787 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001788 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001789 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001790 DCHECK(it != new_class_set->end());
1791 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001792 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001793
Vladimir Marko1a1de672016-10-13 12:53:15 +01001794 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001795 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001796 DCHECK(it2 != new_class_set->end());
1797 DCHECK_EQ(it2->Read(), super_class);
1798 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001799
Vladimir Marko1a1de672016-10-13 12:53:15 +01001800 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1801 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001802 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1803 if (!class_linker->IsQuickResolutionStub(code) &&
1804 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001805 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001806 !m.IsNative()) {
1807 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001808 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001809 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001810
Vladimir Marko1a1de672016-10-13 12:53:15 +01001811 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1812 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001813 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1814 if (!class_linker->IsQuickResolutionStub(code) &&
1815 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001816 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001817 !m.IsNative()) {
1818 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001819 }
1820 }
1821 }
1822 }
1823 }
1824 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001825 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001826
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001827 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001828 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001829 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001830
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001831 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001832 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001833 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001834 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1835 header.VisitPackedArtMethods([&](ArtMethod& method)
1836 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1837 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1838 if (klass != nullptr) {
1839 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1840 }
1841 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001842 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001843}
1844
Chris Wailesfbeef462018-10-19 14:16:35 -07001845void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001846 // Iterate over the string reference offsets stored in the image and intern
1847 // the strings they point to.
1848 ScopedTrace timing("AppImage:InternString");
1849
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001850 Runtime* const runtime = Runtime::Current();
1851 InternTable* const intern_table = runtime->GetInternTable();
1852
1853 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001854
1855 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1856 // for faster lookup.
1857 // TODO: Optimize with a bitmap or bloom filter
1858 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001859 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001860 REQUIRES_SHARED(Locks::mutator_lock_)
1861 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001862 const size_t non_boot_image_strings = intern_table->CountInterns(
1863 /*visit_boot_images=*/false,
1864 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001865 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001866 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1867 // Visit the smaller of the two sets to compute the intersection.
1868 if (interns.size() < non_boot_image_strings) {
1869 for (auto it = interns.begin(); it != interns.end(); ) {
1870 ObjPtr<mirror::String> string = it->Read();
1871 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1872 if (existing == nullptr) {
1873 existing = intern_table->LookupStrongLocked(string);
1874 }
1875 if (existing != nullptr) {
1876 intern_remap.Put(string.Ptr(), existing.Ptr());
1877 it = interns.erase(it);
1878 } else {
1879 ++it;
1880 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001881 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001882 } else {
1883 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1884 REQUIRES_SHARED(Locks::mutator_lock_)
1885 REQUIRES(Locks::intern_table_lock_) {
1886 auto it = interns.find(root);
1887 if (it != interns.end()) {
1888 ObjPtr<mirror::String> existing = root.Read();
1889 intern_remap.Put(it->Read(), existing.Ptr());
1890 it = interns.erase(it);
1891 }
1892 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1893 }
1894 // Sanity check to ensure correctness.
1895 if (kIsDebugBuild) {
1896 for (GcRoot<mirror::String>& root : interns) {
1897 ObjPtr<mirror::String> string = root.Read();
1898 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1899 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001900 }
1901 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001902 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001903 intern_table->AddImageStringsToTable(space, func);
1904 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001905 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001906 VisitInternedStringReferences(
1907 space,
1908 load_startup_cache,
1909 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1910 auto it = intern_remap.find(str.Ptr());
1911 if (it != intern_remap.end()) {
1912 return ObjPtr<mirror::String>(it->second);
1913 }
1914 return str;
1915 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001916 }
1917}
1918
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001919static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1920 const char* location,
1921 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001922 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001923 DCHECK(error_msg != nullptr);
1924 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001925 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001926 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001927 return std::unique_ptr<const DexFile>();
1928 }
1929 std::string inner_error_msg;
1930 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1931 if (dex_file == nullptr) {
1932 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1933 location,
1934 oat_file->GetLocation().c_str(),
1935 inner_error_msg.c_str());
1936 return std::unique_ptr<const DexFile>();
1937 }
1938
1939 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1940 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1941 location,
1942 dex_file->GetLocationChecksum(),
1943 oat_dex_file->GetDexFileLocationChecksum());
1944 return std::unique_ptr<const DexFile>();
1945 }
1946 return dex_file;
1947}
1948
1949bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1950 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1951 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001952 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001953 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001954 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001955 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001956 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001957 dex_caches_object->AsObjectArray<mirror::DexCache>();
1958 const OatFile* oat_file = space->GetOatFile();
Vladimir Marko4617d582019-03-28 13:48:31 +00001959 for (int32_t i = 0, length = dex_caches->GetLength(); i != length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001960 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001961 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1962 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1963 dex_file_location.c_str(),
1964 error_msg);
1965 if (dex_file == nullptr) {
1966 return false;
1967 }
1968 dex_cache->SetDexFile(dex_file.get());
1969 out_dex_files->push_back(std::move(dex_file));
1970 }
1971 return true;
1972}
1973
Andreas Gampe0793bec2016-12-01 11:37:33 -08001974// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1975// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001976class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001977 public:
1978 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1979 REQUIRES_SHARED(Locks::mutator_lock_) {
1980 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001981 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1982 DCHECK(obj != nullptr);
1983 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1984 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1985 if (obj->IsClass()) {
1986 auto klass = obj->AsClass();
1987 for (ArtField& field : klass->GetIFields()) {
1988 CHECK_EQ(field.GetDeclaringClass(), klass);
1989 }
1990 for (ArtField& field : klass->GetSFields()) {
1991 CHECK_EQ(field.GetDeclaringClass(), klass);
1992 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001993 const PointerSize pointer_size = isc.pointer_size_;
1994 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001995 isc.SanityCheckArtMethod(&m, klass);
1996 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001997 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001998 if (vtable != nullptr) {
1999 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
2000 }
2001 if (klass->ShouldHaveImt()) {
2002 ImTable* imt = klass->GetImt(pointer_size);
2003 for (size_t i = 0; i < ImTable::kSize; ++i) {
2004 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
2005 }
2006 }
2007 if (klass->ShouldHaveEmbeddedVTable()) {
2008 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
2009 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
2010 }
2011 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002012 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07002013 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2014 if (iftable->GetMethodArrayCount(i) > 0) {
2015 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
2016 }
2017 }
2018 }
2019 };
2020 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08002021 }
2022
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002023 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
2024 ClassLinker* class_linker,
2025 mirror::MethodDexCacheType* arr,
2026 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08002027 REQUIRES_SHARED(Locks::mutator_lock_) {
2028 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002029 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08002030 }
2031
Andreas Gampe0793bec2016-12-01 11:37:33 -08002032 private:
2033 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
2034 : spaces_(heap->GetBootImageSpaces()),
2035 pointer_size_(class_linker->GetImagePointerSize()) {
2036 space_begin_.reserve(spaces_.size());
2037 method_sections_.reserve(spaces_.size());
2038 runtime_method_sections_.reserve(spaces_.size());
2039 for (gc::space::ImageSpace* space : spaces_) {
2040 space_begin_.push_back(space->Begin());
2041 auto& header = space->GetImageHeader();
2042 method_sections_.push_back(&header.GetMethodsSection());
2043 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
2044 }
2045 }
2046
2047 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
2048 REQUIRES_SHARED(Locks::mutator_lock_) {
2049 if (m->IsRuntimeMethod()) {
2050 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
2051 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
2052 } else if (m->IsCopied()) {
2053 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
2054 } else if (expected_class != nullptr) {
2055 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
2056 }
2057 if (!spaces_.empty()) {
2058 bool contains = false;
2059 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
2060 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
2061 contains = method_sections_[i]->Contains(offset) ||
2062 runtime_method_sections_[i]->Contains(offset);
2063 }
2064 CHECK(contains) << m << " not found";
2065 }
2066 }
2067
2068 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
2069 ObjPtr<mirror::Class> expected_class)
2070 REQUIRES_SHARED(Locks::mutator_lock_) {
2071 CHECK(arr != nullptr);
2072 for (int32_t j = 0; j < arr->GetLength(); ++j) {
2073 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
2074 // expected_class == null means we are a dex cache.
2075 if (expected_class != nullptr) {
2076 CHECK(method != nullptr);
2077 }
2078 if (method != nullptr) {
2079 SanityCheckArtMethod(method, expected_class);
2080 }
2081 }
2082 }
2083
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002084 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08002085 REQUIRES_SHARED(Locks::mutator_lock_) {
2086 CHECK_EQ(arr != nullptr, size != 0u);
2087 if (arr != nullptr) {
2088 bool contains = false;
2089 for (auto space : spaces_) {
2090 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002091 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002092 contains = true;
2093 break;
2094 }
2095 }
2096 CHECK(contains);
2097 }
2098 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002099 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
2100 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08002101 // expected_class == null means we are a dex cache.
2102 if (method != nullptr) {
2103 SanityCheckArtMethod(method, nullptr);
2104 }
2105 }
2106 }
2107
2108 const std::vector<gc::space::ImageSpace*>& spaces_;
2109 const PointerSize pointer_size_;
2110
2111 // Cached sections from the spaces.
2112 std::vector<const uint8_t*> space_begin_;
2113 std::vector<const ImageSection*> method_sections_;
2114 std::vector<const ImageSection*> runtime_method_sections_;
2115};
2116
Andreas Gampebe7af222017-07-25 09:57:28 -07002117static void VerifyAppImage(const ImageHeader& header,
2118 const Handle<mirror::ClassLoader>& class_loader,
2119 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
2120 ClassTable* class_table, gc::space::ImageSpace* space)
2121 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002122 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2123 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
2124 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2125 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
2126 << mirror::Class::PrettyClass(klass);
2127 }
2128 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07002129 {
2130 // Verify that all direct interfaces of classes in the class table are also resolved.
2131 std::vector<ObjPtr<mirror::Class>> classes;
2132 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
2133 REQUIRES_SHARED(Locks::mutator_lock_) {
2134 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
2135 classes.push_back(klass);
2136 }
2137 return true;
2138 };
2139 class_table->Visit(verify_direct_interfaces_in_table);
2140 Thread* self = Thread::Current();
2141 for (ObjPtr<mirror::Class> klass : classes) {
2142 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
2143 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
2144 << klass->PrettyDescriptor() << " iface #" << i;
2145 }
2146 }
2147 }
2148 // Check that all non-primitive classes in dex caches are also in the class table.
2149 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2150 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2151 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
2152 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
2153 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
2154 if (klass != nullptr && !klass->IsPrimitive()) {
2155 CHECK(class_table->Contains(klass))
2156 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
2157 }
2158 }
2159 }
2160}
2161
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002162bool ClassLinker::AddImageSpace(
2163 gc::space::ImageSpace* space,
2164 Handle<mirror::ClassLoader> class_loader,
2165 jobjectArray dex_elements,
2166 const char* dex_location,
2167 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
2168 std::string* error_msg) {
2169 DCHECK(out_dex_files != nullptr);
2170 DCHECK(error_msg != nullptr);
2171 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002172 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002173 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002174 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002175 DCHECK(dex_caches_object != nullptr);
2176 Runtime* const runtime = Runtime::Current();
2177 gc::Heap* const heap = runtime->GetHeap();
2178 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002179 // Check that the image is what we are expecting.
2180 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
2181 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
2182 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
2183 image_pointer_size_);
2184 return false;
2185 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002186 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
2187 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
2188 *error_msg = StringPrintf("Expected %zu image roots but got %d",
2189 expected_image_roots,
2190 header.GetImageRoots()->GetLength());
2191 return false;
2192 }
2193 StackHandleScope<3> hs(self);
2194 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
2195 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2196 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2197 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002198 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002199 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2200 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002201 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002202 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002203 *error_msg = StringPrintf("Expected %d class roots but got %d",
2204 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002205 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002206 return false;
2207 }
2208 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002209 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2210 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2211 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002212 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2213 return false;
2214 }
2215 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002216 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002217 if (oat_file->GetOatHeader().GetDexFileCount() !=
2218 static_cast<uint32_t>(dex_caches->GetLength())) {
2219 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2220 "image";
2221 return false;
2222 }
2223
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002224 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002225 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
David Brazdil3e8aae02019-03-26 18:48:02 +00002226 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Andreas Gamped5d807b2019-04-18 14:46:51 -07002227 if (class_loader == nullptr) {
2228 // For app images, we'll see the relative location. b/130666977.
2229 DCHECK_EQ(dex_location, DexFileLoader::GetBaseLocation(dex_file_location));
2230 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002231 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2232 dex_file_location.c_str(),
2233 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002234 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002235 return false;
2236 }
2237
2238 if (app_image) {
2239 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2240 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002241 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002242 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002243 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002244 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002245 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002246 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002247 }
2248 }
2249 } else {
2250 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002251 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2252 this,
2253 dex_cache->GetResolvedMethods(),
2254 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002255 }
2256 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002257 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002258 }
2259 out_dex_files->push_back(std::move(dex_file));
2260 }
2261
2262 if (app_image) {
2263 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002264 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002265 // Check that the class loader resolves the same way as the ones in the image.
2266 // Image class loader [A][B][C][image dex files]
2267 // Class loader = [???][dex_elements][image dex files]
2268 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002269 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002270 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2271 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2272 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002273 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2274 *error_msg = "Unexpected BootClassLoader in app image";
2275 return false;
2276 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002277 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2278 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2279 // special case the comparison of dex files of the two class loaders, but then do full
2280 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002281 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002282 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002283 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2284 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2285 if (element != nullptr) {
2286 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002287 ObjPtr<mirror::String> name;
2288 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2289 loader_dex_file_names.push_back(name);
2290 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002291 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002292 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002293 std::string temp_error_msg;
2294 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2295 bool success = GetDexFileNames(
2296 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2297 if (success) {
2298 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2299 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2300 static_cast<size_t>(dex_caches->GetLength()));
2301 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2302 image_dex_file_names.resize(image_count);
2303 success = success && CompareDexFiles(image_dex_file_names,
2304 loader_dex_file_names,
2305 &temp_error_msg);
2306 success = success && CompareClassLoaders(soa,
2307 image_class_loader.Get(),
2308 class_loader.Get(),
2309 /*check_dex_file_names=*/ false,
2310 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002311 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002312 if (!success) {
2313 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2314 temp_error_msg.c_str());
2315 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002316 }
2317 }
2318
2319 if (kSanityCheckObjects) {
2320 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002321 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002322 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2323 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2324 if (field != nullptr) {
2325 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2326 }
2327 }
2328 }
2329 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002330 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002331 }
2332 }
2333
2334 // Set entry point to interpreter if in InterpretOnly mode.
2335 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002336 // Set image methods' entry point to interpreter.
2337 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2338 if (!method.IsRuntimeMethod()) {
2339 DCHECK(method.GetDeclaringClass() != nullptr);
2340 if (!method.IsNative() && !method.IsResolutionMethod()) {
2341 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2342 image_pointer_size_);
2343 }
2344 }
2345 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002346 }
2347
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002348 ClassTable* class_table = nullptr;
2349 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002350 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002351 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002352 }
2353 // If we have a class table section, read it and use it for verification in
2354 // UpdateAppImageClassLoadersAndDexCaches.
2355 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002356 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002357 const bool added_class_table = class_table_section.Size() > 0u;
2358 if (added_class_table) {
2359 const uint64_t start_time2 = NanoTime();
2360 size_t read_count = 0;
2361 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2362 /*make copy*/false,
2363 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002364 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002365 }
2366 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002367 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002368
2369 {
2370 ScopedTrace trace("AppImage:UpdateClassLoaders");
2371 // Update class loader and resolved strings. If added_class_table is false, the resolved
2372 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002373 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002374 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002375 // Note: We probably don't need the read barrier unless we copy the app image objects into
2376 // the region space.
2377 ObjPtr<mirror::Class> klass(root.Read());
2378 // Do not update class loader for boot image classes where the app image
2379 // class loader is only the initiating loader but not the defining loader.
2380 // Avoid read barrier since we are comparing against null.
2381 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2382 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2383 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002384 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002385 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002386
Vladimir Marko305c38b2018-02-14 11:50:07 +00002387 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002388 // Every class in the app image has initially SubtypeCheckInfo in the
2389 // Uninitialized state.
2390 //
2391 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2392 // after class initialization is complete. The app image ClassStatus as-is
2393 // are almost all ClassStatus::Initialized, and being in the
2394 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2395 //
2396 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2397 //
2398 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002399 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002400 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2401 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002402 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002403 }
2404 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002405 }
2406 if (!oat_file->GetBssGcRoots().empty()) {
2407 // Insert oat file to class table for visiting .bss GC roots.
2408 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002409 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002410
Mathieu Chartier69731002016-03-02 16:08:31 -08002411 if (added_class_table) {
2412 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2413 class_table->AddClassSet(std::move(temp_set));
2414 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002415
Mathieu Chartier69731002016-03-02 16:08:31 -08002416 if (kIsDebugBuild && app_image) {
2417 // This verification needs to happen after the classes have been added to the class loader.
2418 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002419 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002420 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002421 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002422
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002423 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002424 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002425}
2426
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002427bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002428 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2429 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002430}
2431
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002432void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002433 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2434 // enabling tracing requires the mutator lock, there are no race conditions here.
2435 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002436 Thread* const self = Thread::Current();
2437 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002438 if (kUseReadBarrier) {
2439 // We do not track new roots for CC.
2440 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2441 kVisitRootFlagClearRootLog |
2442 kVisitRootFlagStartLoggingNewRoots |
2443 kVisitRootFlagStopLoggingNewRoots));
2444 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002445 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002446 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2447 // There is 3 GC cases to handle:
2448 // Non moving concurrent:
2449 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002450 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002451 //
2452 // Moving non-concurrent:
2453 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2454 // To prevent missing roots, this case needs to ensure that there is no
2455 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2456 // class which is in the class table.
2457 //
2458 // Moving concurrent:
2459 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2460 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002461 //
2462 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2463 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2464 // these objects.
2465 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002466 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002467 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002468 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002469 for (const ClassLoaderData& data : class_loaders_) {
2470 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2471 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2472 }
2473 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002474 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002475 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002476 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002477 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002478 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002479 // Concurrent moving GC marked new roots through the to-space invariant.
2480 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002481 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002482 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2483 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2484 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2485 if (old_ref != nullptr) {
2486 DCHECK(old_ref->IsClass());
2487 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2488 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2489 // Concurrent moving GC marked new roots through the to-space invariant.
2490 CHECK_EQ(new_ref, old_ref);
2491 }
2492 }
2493 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002494 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002495 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002496 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002497 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002498 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002499 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002500 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002501 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002502 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002503 }
2504 // We deliberately ignore the class roots in the image since we
2505 // handle image roots by using the MS/CMS rescanning of dirty cards.
2506}
2507
Brian Carlstroma663ea52011-08-19 23:33:41 -07002508// Keep in sync with InitCallback. Anything we visit, we need to
2509// reinit references to when reinitializing a ClassLinker from a
2510// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002511void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002512 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002513 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002514 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2515 // unloading if we are marking roots.
2516 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002517}
2518
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002519class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2520 public:
2521 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2522 : visitor_(visitor),
2523 done_(false) {}
2524
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002525 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002526 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002527 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002528 if (!done_ && class_table != nullptr) {
2529 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2530 if (!class_table->Visit(visitor)) {
2531 // If the visitor ClassTable returns false it means that we don't need to continue.
2532 done_ = true;
2533 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002534 }
2535 }
2536
2537 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002538 // Class visitor that limits the class visits from a ClassTable to the classes with
2539 // the provided defining class loader. This filter is used to avoid multiple visits
2540 // of the same class which can be recorded for multiple initiating class loaders.
2541 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2542 public:
2543 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2544 ClassVisitor* visitor)
2545 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2546
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002547 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002548 if (klass->GetClassLoader() != defining_class_loader_) {
2549 return true;
2550 }
2551 return (*visitor_)(klass);
2552 }
2553
Vladimir Marko0984e482019-03-27 16:41:41 +00002554 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002555 ClassVisitor* const visitor_;
2556 };
2557
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002558 ClassVisitor* const visitor_;
2559 // If done is true then we don't need to do any more visiting.
2560 bool done_;
2561};
2562
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002563void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002564 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002565 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2566 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002567 }
2568}
2569
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002570void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002571 Thread* const self = Thread::Current();
2572 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2573 // Not safe to have thread suspension when we are holding a lock.
2574 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002575 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002576 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002577 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002578 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002579 }
2580}
2581
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002582class GetClassesInToVector : public ClassVisitor {
2583 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002584 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002585 classes_.push_back(klass);
2586 return true;
2587 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002588 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002589};
2590
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002591class GetClassInToObjectArray : public ClassVisitor {
2592 public:
2593 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2594 : arr_(arr), index_(0) {}
2595
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002596 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002597 ++index_;
2598 if (index_ <= arr_->GetLength()) {
2599 arr_->Set(index_ - 1, klass);
2600 return true;
2601 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002602 return false;
2603 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002604
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002605 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002606 return index_ <= arr_->GetLength();
2607 }
2608
2609 private:
2610 mirror::ObjectArray<mirror::Class>* const arr_;
2611 int32_t index_;
2612};
2613
2614void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002615 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2616 // is avoiding duplicates.
2617 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002618 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002619 GetClassesInToVector accumulator;
2620 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002621 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002622 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002623 return;
2624 }
2625 }
2626 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002627 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002628 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002629 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002630 // We size the array assuming classes won't be added to the class table during the visit.
2631 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002632 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002633 size_t class_table_size;
2634 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002635 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002636 // Add 100 in case new classes get loaded when we are filling in the object array.
2637 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002638 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002639 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002640 classes.Assign(
2641 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002642 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002643 GetClassInToObjectArray accumulator(classes.Get());
2644 VisitClasses(&accumulator);
2645 if (accumulator.Succeeded()) {
2646 break;
2647 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002648 }
2649 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2650 // If the class table shrank during creation of the clases array we expect null elements. If
2651 // the class table grew then the loop repeats. If classes are created after the loop has
2652 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002653 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002654 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002655 return;
2656 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002657 }
2658 }
2659}
2660
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002661ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002662 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002663 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002664 // CHA unloading analysis is not needed. No negative consequences are expected because
2665 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002666 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002667 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002668 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002669 while (!running_visibly_initialized_callbacks_.empty()) {
2670 std::unique_ptr<VisiblyInitializedCallback> callback(
2671 std::addressof(running_visibly_initialized_callbacks_.front()));
2672 running_visibly_initialized_callbacks_.pop_front();
2673 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002674}
2675
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002676void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002677 Runtime* const runtime = Runtime::Current();
2678 JavaVMExt* const vm = runtime->GetJavaVM();
2679 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002680 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002681 if (runtime->GetJit() != nullptr) {
2682 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2683 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002684 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002685 code_cache->RemoveMethodsIn(self, *data.allocator);
2686 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002687 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002688 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002689 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002690 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002691 // Cleanup references to single implementation ArtMethods that will be deleted.
2692 if (cleanup_cha) {
2693 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2694 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2695 }
2696
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002697 delete data.allocator;
2698 delete data.class_table;
2699}
2700
Vladimir Markobcf17522018-06-01 13:14:32 +01002701ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2702 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002703 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002704 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2705 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002706}
2707
Vladimir Markobcf17522018-06-01 13:14:32 +01002708ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2709 Thread* self,
2710 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002711 StackHandleScope<1> hs(self);
2712 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002713 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002714 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002715 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002716 self->AssertPendingOOMException();
2717 return nullptr;
2718 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002719 // Use InternWeak() so that the location String can be collected when the ClassLoader
2720 // with this DexCache is collected.
2721 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002722 if (location == nullptr) {
2723 self->AssertPendingOOMException();
2724 return nullptr;
2725 }
2726 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002727 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002728}
2729
Vladimir Markobcf17522018-06-01 13:14:32 +01002730ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2731 const DexFile& dex_file,
2732 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002733 ObjPtr<mirror::String> location = nullptr;
2734 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002735 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002736 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002737 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002738 mirror::DexCache::InitializeDexCache(self,
2739 dex_cache,
2740 location,
2741 &dex_file,
2742 linear_alloc,
2743 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002744 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002745 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002746}
2747
Vladimir Marko70e2a762019-07-12 16:49:00 +01002748template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002749ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2750 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002751 uint32_t class_size,
2752 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002753 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002754 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002755 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002756 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2757 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002758 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002759 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002760 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002761 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002762 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002763}
2764
Vladimir Marko70e2a762019-07-12 16:49:00 +01002765template <bool kMovable>
2766ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2767 ObjPtr<mirror::Class> java_lang_Class,
2768 uint32_t class_size) {
2769 mirror::Class::InitializeClassVisitor visitor(class_size);
2770 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2771}
2772
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002773ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002774 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002775}
2776
Vladimir Marko70e2a762019-07-12 16:49:00 +01002777void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2778 ClassRoot primitive_root,
2779 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002780 // We make this class non-movable for the unlikely case where it were to be
2781 // moved by a sticky-bit (minor) collection when using the Generational
2782 // Concurrent Copying (CC) collector, potentially creating a stale reference
2783 // in the `klass_` field of one of its instances allocated in the Large-Object
2784 // Space (LOS) -- see the comment about the dirty card scanning logic in
2785 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002786 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2787 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2788 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2789 DCHECK(component_type->IsPrimitive());
2790 array_class->SetComponentType(component_type);
2791 SetClassRoot(array_root, array_class);
2792}
2793
2794void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2795 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2796 array_class->SetSuperClass(java_lang_Object);
2797 array_class->SetVTable(java_lang_Object->GetVTable());
2798 array_class->SetPrimitiveType(Primitive::kPrimNot);
2799 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2800 array_class->SetClassFlags(component_type->IsPrimitive()
2801 ? mirror::kClassFlagNoReferenceFields
2802 : mirror::kClassFlagObjectArray);
2803 array_class->SetClassLoader(component_type->GetClassLoader());
2804 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2805 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2806 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2807 array_class->SetImt(object_imt, image_pointer_size_);
2808 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2809 // the kAccVerificationAttempted flag is added below, and there are no
2810 // methods that need the kAccSkipAccessChecks flag.
2811 DCHECK_EQ(array_class->NumMethods(), 0u);
2812
2813 // don't need to set new_class->SetObjectSize(..)
2814 // because Object::SizeOf delegates to Array::SizeOf
2815
2816 // All arrays have java/lang/Cloneable and java/io/Serializable as
2817 // interfaces. We need to set that up here, so that stuff like
2818 // "instanceof" works right.
2819
2820 // Use the single, global copies of "interfaces" and "iftable"
2821 // (remember not to free them for arrays).
2822 {
2823 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2824 CHECK(array_iftable != nullptr);
2825 array_class->SetIfTable(array_iftable);
2826 }
2827
2828 // Inherit access flags from the component type.
2829 int access_flags = component_type->GetAccessFlags();
2830 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2831 access_flags &= kAccJavaFlagsMask;
2832 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2833 // and remove "interface".
2834 access_flags |= kAccAbstract | kAccFinal;
2835 access_flags &= ~kAccInterface;
2836 // Arrays are access-checks-clean and preverified.
2837 access_flags |= kAccVerificationAttempted;
2838
2839 array_class->SetAccessFlags(access_flags);
2840
Vladimir Markobf121912019-06-04 13:49:05 +01002841 // Array classes are fully initialized either during single threaded startup,
2842 // or from a pre-fence visitor, so visibly initialized.
2843 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002844}
2845
2846void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2847 // Do not hold lock on the array class object, the initialization of
2848 // core array classes is done while the process is still single threaded.
2849 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2850 FinishArrayClassSetup(array_class);
2851
2852 std::string temp;
2853 const char* descriptor = array_class->GetDescriptor(&temp);
2854 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2855 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2856 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002857}
2858
Vladimir Markobcf17522018-06-01 13:14:32 +01002859ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002860 Thread* self,
2861 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002862 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002863 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002864}
2865
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002866ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2867 const char* descriptor,
2868 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002869 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002870 if (kIsDebugBuild) {
2871 StackHandleScope<1> hs(self);
2872 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2873 Thread::PoisonObjectPointersIfDebug();
2874 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002875
2876 // For temporary classes we must wait for them to be retired.
2877 if (init_done_ && klass->IsTemp()) {
2878 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002879 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002880 ThrowEarlierClassFailure(klass);
2881 return nullptr;
2882 }
2883 StackHandleScope<1> hs(self);
2884 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2885 ObjectLock<mirror::Class> lock(self, h_class);
2886 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002887 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002888 lock.WaitIgnoringInterrupts();
2889 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002890 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002891 ThrowEarlierClassFailure(h_class.Get());
2892 return nullptr;
2893 }
2894 CHECK(h_class->IsRetired());
2895 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002896 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002897 }
2898
Brian Carlstromaded5f72011-10-07 17:15:04 -07002899 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002900 size_t index = 0;
2901 // Maximum number of yield iterations until we start sleeping.
2902 static const size_t kNumYieldIterations = 1000;
2903 // How long each sleep is in us.
2904 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002905 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002906 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002907 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002908 {
2909 ObjectTryLock<mirror::Class> lock(self, h_class);
2910 // Can not use a monitor wait here since it may block when returning and deadlock if another
2911 // thread has locked klass.
2912 if (lock.Acquired()) {
2913 // Check for circular dependencies between classes, the lock is required for SetStatus.
2914 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2915 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002916 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002917 return nullptr;
2918 }
2919 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002920 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002921 {
2922 // Handle wrapper deals with klass moving.
2923 ScopedThreadSuspension sts(self, kSuspended);
2924 if (index < kNumYieldIterations) {
2925 sched_yield();
2926 } else {
2927 usleep(kSleepDurationUS);
2928 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002929 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002930 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002931 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002932
Vladimir Marko72ab6842017-01-20 19:32:50 +00002933 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002934 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002935 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002936 }
2937 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002938 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002939 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002940 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002941}
2942
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002943using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002944
2945// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002946ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002947 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002948 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002949 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002950 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002951 return ClassPathEntry(dex_file, dex_class_def);
2952 }
2953 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002954 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002955}
2956
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002957bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2958 Thread* self,
2959 const char* descriptor,
2960 size_t hash,
2961 Handle<mirror::ClassLoader> class_loader,
2962 /*out*/ ObjPtr<mirror::Class>* result) {
2963 ArtField* field =
2964 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2965 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2966 if (raw_shared_libraries == nullptr) {
2967 return true;
2968 }
2969
2970 StackHandleScope<2> hs(self);
2971 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2972 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2973 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2974 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2975 temp_loader.Assign(shared_libraries->Get(i));
2976 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2977 return false; // One of the shared libraries is not supported.
2978 }
2979 if (*result != nullptr) {
2980 return true; // Found the class up the chain.
2981 }
2982 }
2983 return true;
2984}
2985
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002986bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2987 Thread* self,
2988 const char* descriptor,
2989 size_t hash,
2990 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002991 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002992 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002993 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002994 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002995 return true;
2996 }
2997
David Brazdil05909d82018-12-06 16:25:16 +00002998 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002999 // For regular path or dex class loader the search order is:
3000 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003001 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07003002 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07003003
Calin Juravlecdd49122017-07-05 20:09:53 -07003004 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
3005 StackHandleScope<1> hs(self);
3006 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
3007 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
3008 return false; // One of the parents is not supported.
3009 }
3010 if (*result != nullptr) {
3011 return true; // Found the class up the chain.
3012 }
Andreas Gampef865ea92015-04-13 22:14:19 -07003013
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003014 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
3015 return false; // One of the shared library loader is not supported.
3016 }
3017 if (*result != nullptr) {
3018 return true; // Found the class in a shared library.
3019 }
3020
Calin Juravlecdd49122017-07-05 20:09:53 -07003021 // Search the current class loader classpath.
3022 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00003023 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07003024 }
3025
Calin Juravlecdd49122017-07-05 20:09:53 -07003026 if (IsDelegateLastClassLoader(soa, class_loader)) {
3027 // For delegate last, the search order is:
3028 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003029 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07003030 // - class loader dex files
3031 // - parent
3032 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
3033 if (*result != nullptr) {
3034 return true; // The class is part of the boot class path.
3035 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003036 if (self->IsExceptionPending()) {
3037 // Pending exception means there was an error other than ClassNotFound that must be returned
3038 // to the caller.
3039 return false;
3040 }
Calin Juravlecdd49122017-07-05 20:09:53 -07003041
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003042 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
3043 return false; // One of the shared library loader is not supported.
3044 }
3045 if (*result != nullptr) {
3046 return true; // Found the class in a shared library.
3047 }
3048
Calin Juravlecdd49122017-07-05 20:09:53 -07003049 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
3050 if (*result != nullptr) {
3051 return true; // Found the class in the current class loader
3052 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003053 if (self->IsExceptionPending()) {
3054 // Pending exception means there was an error other than ClassNotFound that must be returned
3055 // to the caller.
3056 return false;
3057 }
Calin Juravlecdd49122017-07-05 20:09:53 -07003058
3059 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
3060 StackHandleScope<1> hs(self);
3061 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
3062 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
3063 }
3064
3065 // Unsupported class loader.
3066 *result = nullptr;
3067 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07003068}
3069
Andreas Gampe501c3b02019-04-17 21:54:27 +00003070namespace {
3071
3072// Matches exceptions caught in DexFile.defineClass.
3073ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
3074 ClassLinker* class_linker)
3075 REQUIRES_SHARED(Locks::mutator_lock_) {
3076 return
3077 // ClassNotFoundException.
3078 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
3079 class_linker))
3080 ||
3081 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
3082 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
3083}
3084
3085// Clear exceptions caught in DexFile.defineClass.
3086ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
3087 REQUIRES_SHARED(Locks::mutator_lock_) {
3088 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
3089 self->ClearException();
3090 }
3091}
3092
3093} // namespace
3094
Calin Juravle415dc3d2017-06-28 11:03:12 -07003095// Finds the class in the boot class loader.
3096// If the class is found the method returns the resolved class. Otherwise it returns null.
3097ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
3098 const char* descriptor,
3099 size_t hash) {
3100 ObjPtr<mirror::Class> result = nullptr;
3101 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
3102 if (pair.second != nullptr) {
3103 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
3104 if (klass != nullptr) {
3105 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003106 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07003107 result = DefineClass(self,
3108 descriptor,
3109 hash,
3110 ScopedNullHandle<mirror::ClassLoader>(),
3111 *pair.first,
3112 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003113 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07003114 if (result == nullptr) {
3115 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003116 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07003117 }
3118 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07003119 return result;
3120}
Andreas Gampef865ea92015-04-13 22:14:19 -07003121
Calin Juravle415dc3d2017-06-28 11:03:12 -07003122ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
3123 ScopedObjectAccessAlreadyRunnable& soa,
3124 const char* descriptor,
3125 size_t hash,
3126 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00003127 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
3128 IsInMemoryDexClassLoader(soa, class_loader) ||
3129 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07003130 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07003131
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003132 ObjPtr<mirror::Class> ret;
3133 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003134 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003135 if (dex_class_def != nullptr) {
3136 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
3137 descriptor,
3138 hash,
3139 class_loader,
3140 *cp_dex_file,
3141 *dex_class_def);
3142 if (klass == nullptr) {
3143 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003144 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003145 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00003146 } else {
3147 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003148 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003149 ret = klass;
3150 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003151 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003152 return true; // Continue with the next DexFile.
3153 };
3154
3155 VisitClassLoaderDexFiles(soa, class_loader, define_class);
3156 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003157}
3158
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003159ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
3160 const char* descriptor,
3161 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08003162 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08003163 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003164 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07003165 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003166 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003167 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
3168 // for primitive classes that aren't backed by dex files.
3169 return FindPrimitiveClass(descriptor[0]);
3170 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003171 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003172 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003173 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07003174 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003175 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003176 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003177 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003178 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003179 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003180 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07003181 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003182 return DefineClass(self,
3183 descriptor,
3184 hash,
3185 ScopedNullHandle<mirror::ClassLoader>(),
3186 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07003187 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07003188 } else {
3189 // The boot class loader is searched ahead of the application class loader, failures are
3190 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
3191 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003192 ObjPtr<mirror::Throwable> pre_allocated =
3193 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003194 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07003195 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05003196 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003197 }
3198 ObjPtr<mirror::Class> result_ptr;
3199 bool descriptor_equals;
3200 if (descriptor[0] == '[') {
3201 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
3202 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
3203 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
3204 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05003205 } else {
Ian Rogers98379392014-02-24 16:53:16 -08003206 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003207 bool known_hierarchy =
3208 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
3209 if (result_ptr != nullptr) {
3210 // The chain was understood and we found the class. We still need to add the class to
3211 // the class table to protect from racy programs that can try and redefine the path list
3212 // which would change the Class<?> returned for subsequent evaluation of const-class.
3213 DCHECK(known_hierarchy);
3214 DCHECK(result_ptr->DescriptorEquals(descriptor));
3215 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003216 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003217 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00003218 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
3219 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003220 //
3221 // If the chain was understood but we did not find the class, let the Java-side
3222 // rediscover all this and throw the exception with the right stack trace. Note that
3223 // the Java-side could still succeed for racy programs if another thread is actively
3224 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07003225
Alex Light185a4612018-10-04 15:54:25 -07003226 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07003227 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00003228 // Oops, we can't call into java so we can't run actual class-loader code.
3229 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003230 ObjPtr<mirror::Throwable> pre_allocated =
3231 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3232 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003233 return nullptr;
3234 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003235
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003236 // Inlined DescriptorToDot(descriptor) with extra validation.
3237 //
3238 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
3239 // the DescriptorEquals() check below and give a confusing error message. For example,
3240 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
3241 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
3242 // "class loader [...] returned class java.lang.String instead of java.lang.String".
3243 size_t descriptor_length = strlen(descriptor);
3244 if (UNLIKELY(descriptor[0] != 'L') ||
3245 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
3246 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
3247 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
3248 return nullptr;
3249 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003250
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003251 std::string class_name_string(descriptor + 1, descriptor_length - 2);
3252 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00003253 if (known_hierarchy &&
3254 fast_class_not_found_exceptions_ &&
3255 !Runtime::Current()->IsJavaDebuggable()) {
3256 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
3257 // debuggable, optimize this path by throwing directly here without going back to Java
3258 // language. This reduces how many ClassNotFoundExceptions happen.
3259 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
3260 "%s",
3261 class_name_string.c_str());
3262 } else {
3263 ScopedLocalRef<jobject> class_loader_object(
3264 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
3265 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
3266 {
3267 ScopedThreadStateChange tsc(self, kNative);
3268 ScopedLocalRef<jobject> class_name_object(
3269 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
3270 if (class_name_object.get() == nullptr) {
3271 DCHECK(self->IsExceptionPending()); // OOME.
3272 return nullptr;
3273 }
3274 CHECK(class_loader_object.get() != nullptr);
3275 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
3276 WellKnownClasses::java_lang_ClassLoader_loadClass,
3277 class_name_object.get()));
3278 }
3279 if (result.get() == nullptr && !self->IsExceptionPending()) {
3280 // broken loader - throw NPE to be compatible with Dalvik
3281 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
3282 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003283 return nullptr;
3284 }
Andreas Gampe87658f32019-04-18 18:39:02 +00003285 result_ptr = soa.Decode<mirror::Class>(result.get());
3286 // Check the name of the returned class.
3287 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003288 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003289 } else {
3290 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003291 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003292 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003293
3294 if (self->IsExceptionPending()) {
3295 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3296 // However, to comply with the RI behavior, first check if another thread succeeded.
3297 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3298 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3299 self->ClearException();
3300 return EnsureResolved(self, descriptor, result_ptr);
3301 }
3302 return nullptr;
3303 }
3304
3305 // Try to insert the class to the class table, checking for mismatch.
3306 ObjPtr<mirror::Class> old;
3307 {
3308 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3309 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3310 old = class_table->Lookup(descriptor, hash);
3311 if (old == nullptr) {
3312 old = result_ptr; // For the comparison below, after releasing the lock.
3313 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003314 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003315 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003316 } // else throw below, after releasing the lock.
3317 }
3318 }
3319 if (UNLIKELY(old != result_ptr)) {
3320 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3321 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003322 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003323 const char* loader_class_name =
3324 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3325 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3326 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3327 << DescriptorToDot(descriptor) << "\").";
3328 return EnsureResolved(self, descriptor, old);
3329 }
3330 if (UNLIKELY(!descriptor_equals)) {
3331 std::string result_storage;
3332 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3333 std::string loader_storage;
3334 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3335 ThrowNoClassDefFoundError(
3336 "Initiating class loader of type %s returned class %s instead of %s.",
3337 DescriptorToDot(loader_class_name).c_str(),
3338 DescriptorToDot(result_name).c_str(),
3339 DescriptorToDot(descriptor).c_str());
3340 return nullptr;
3341 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003342 // Success.
3343 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003344}
3345
Vladimir Markob9c29f62019-03-20 14:22:51 +00003346static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3347 std::string_view descriptor_sv(descriptor);
Vladimir Marko29885b32019-04-03 10:09:26 +01003348 return
3349 // Reserved conscrypt packages (includes sub-packages under these paths).
3350 StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3351 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/") ||
3352 // Reserved updatable-media package (includes sub-packages under this path).
3353 StartsWith(descriptor_sv, "Landroid/media/");
Vladimir Markob9c29f62019-03-20 14:22:51 +00003354}
3355
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003356ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3357 const char* descriptor,
3358 size_t hash,
3359 Handle<mirror::ClassLoader> class_loader,
3360 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003361 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003362 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003363 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003364
Brian Carlstromaded5f72011-10-07 17:15:04 -07003365 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003366 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003367 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003368 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003369 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003370 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003371 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003372 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003373 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003374 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003375 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003376 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003377 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003378 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003379 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003380 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003381 }
3382
Vladimir Markob9c29f62019-03-20 14:22:51 +00003383 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3384 // some runtime modules. Prevent definition of classes in app class loader that could clash
3385 // with these modules as these classes could be resolved differently during execution.
3386 if (class_loader != nullptr &&
3387 Runtime::Current()->IsAotCompiler() &&
3388 IsReservedBootClassPathDescriptor(descriptor)) {
3389 ObjPtr<mirror::Throwable> pre_allocated =
3390 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3391 self->SetException(pre_allocated);
3392 return nullptr;
3393 }
3394
Alex Lighte9f61032018-09-24 16:04:51 -07003395 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3396 // code to be executed. We put it up here so we can avoid all the allocations associated with
3397 // creating the class. This can happen with (eg) jit threads.
3398 if (!self->CanLoadClasses()) {
3399 // Make sure we don't try to load anything, potentially causing an infinite loop.
3400 ObjPtr<mirror::Throwable> pre_allocated =
3401 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3402 self->SetException(pre_allocated);
3403 return nullptr;
3404 }
3405
Andreas Gampefa4333d2017-02-14 11:10:34 -08003406 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003407 // Allocate a class with the status of not ready.
3408 // Interface object should get the right size here. Regular class will
3409 // figure out the right size later and be replaced with one of the right
3410 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003411 if (CanAllocClass()) {
3412 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3413 } else {
3414 return nullptr;
3415 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003416 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003417 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003418 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003419 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003420 }
Alex Lightb0f11922017-01-23 14:25:17 -08003421 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3422 // nothing.
3423 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003424 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003425 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3426 // will only be called once.
3427 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3428 klass,
3429 class_loader,
3430 dex_file,
3431 dex_class_def,
3432 &new_dex_file,
3433 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003434 // Check to see if an exception happened during runtime callbacks. Return if so.
3435 if (self->IsExceptionPending()) {
3436 return nullptr;
3437 }
Alex Lightb0f11922017-01-23 14:25:17 -08003438 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003439 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003440 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003441 return nullptr;
3442 }
3443 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003444 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003445
Jeff Hao848f70a2014-01-15 13:49:50 -08003446 // Mark the string class by setting its access flag.
3447 if (UNLIKELY(!init_done_)) {
3448 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3449 klass->SetStringClass();
3450 }
3451 }
3452
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003453 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003454 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003455 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003456 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003457
Mathieu Chartier590fee92013-09-13 13:46:47 -07003458 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003459 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003460 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003461 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3462 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003463 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003464 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003465
Mathieu Chartierc7853442015-03-27 14:35:38 -07003466 // Load the fields and other things after we are inserted in the table. This is so that we don't
3467 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3468 // other reason is that the field roots are only visited from the class table. So we need to be
3469 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003470 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003471 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003472 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003473 // An exception occured during load, set status to erroneous while holding klass' lock in case
3474 // notification is necessary.
3475 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003476 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003477 }
3478 return nullptr;
3479 }
3480
Brian Carlstromaded5f72011-10-07 17:15:04 -07003481 // Finish loading (if necessary) by finding parents
3482 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003483 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003484 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003485 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003486 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003487 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003488 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003489 }
3490 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003491
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003492 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003493 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003494 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003495
Brian Carlstromaded5f72011-10-07 17:15:04 -07003496 // Link the class (if necessary)
3497 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003498 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003499 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003500
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003501 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003502 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003503 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003504 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003505 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003506 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003507 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003508 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003509 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003510 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003511 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003512
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003513 // Instrumentation may have updated entrypoints for all methods of all
3514 // classes. However it could not update methods of this class while we
3515 // were loading it. Now the class is resolved, we can update entrypoints
3516 // as required by instrumentation.
3517 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3518 // We must be in the kRunnable state to prevent instrumentation from
3519 // suspending all threads to update entrypoints while we are doing it
3520 // for this class.
3521 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003522 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003523 }
3524
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003525 /*
3526 * We send CLASS_PREPARE events to the debugger from here. The
3527 * definition of "preparation" is creating the static fields for a
3528 * class and initializing them to the standard default values, but not
3529 * executing any code (that comes later, during "initialization").
3530 *
3531 * We did the static preparation in LinkClass.
3532 *
3533 * The class has been prepared and resolved but possibly not yet verified
3534 * at this point.
3535 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003536 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003537
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003538 // Notify native debugger of the new class and its layout.
3539 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3540
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003541 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003542}
3543
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003544uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003545 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003546 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003547 size_t num_8 = 0;
3548 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003549 size_t num_32 = 0;
3550 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003551 ClassAccessor accessor(dex_file, dex_class_def);
3552 // We allow duplicate definitions of the same field in a class_data_item
3553 // but ignore the repeated indexes here, b/21868015.
3554 uint32_t last_field_idx = dex::kDexNoIndex;
3555 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3556 uint32_t field_idx = field.GetIndex();
3557 // Ordering enforced by DexFileVerifier.
3558 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3559 if (UNLIKELY(field_idx == last_field_idx)) {
3560 continue;
3561 }
3562 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003563 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003564 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3565 char c = descriptor[0];
3566 switch (c) {
3567 case 'L':
3568 case '[':
3569 num_ref++;
3570 break;
3571 case 'J':
3572 case 'D':
3573 num_64++;
3574 break;
3575 case 'I':
3576 case 'F':
3577 num_32++;
3578 break;
3579 case 'S':
3580 case 'C':
3581 num_16++;
3582 break;
3583 case 'B':
3584 case 'Z':
3585 num_8++;
3586 break;
3587 default:
3588 LOG(FATAL) << "Unknown descriptor: " << c;
3589 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003590 }
3591 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003592 return mirror::Class::ComputeClassSize(false,
3593 0,
3594 num_8,
3595 num_16,
3596 num_32,
3597 num_64,
3598 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003599 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003600}
3601
Alex Lightfc49fec2018-01-16 22:28:36 +00003602// Special case to get oat code without overwriting a trampoline.
3603const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003604 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003605 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003606 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003607 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003608 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003609 if (code != nullptr) {
3610 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003611 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003612
3613 jit::Jit* jit = Runtime::Current()->GetJit();
3614 if (jit != nullptr) {
3615 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3616 if (code != nullptr) {
3617 return code;
3618 }
3619 }
3620
Alex Lightfc49fec2018-01-16 22:28:36 +00003621 if (method->IsNative()) {
3622 // No code and native? Use generic trampoline.
3623 return GetQuickGenericJniStub();
3624 }
3625 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003626}
3627
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003628bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003629 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003630 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3631 return false;
3632 }
3633
Elliott Hughes956af0f2014-12-11 14:34:28 -08003634 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003635 return true;
3636 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003637
3638 Runtime* runtime = Runtime::Current();
3639 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3640 if (instr->InterpretOnly()) {
3641 return true;
3642 }
3643
3644 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3645 // Doing this check avoids doing compiled/interpreter transitions.
3646 return true;
3647 }
3648
Alex Light3dacdd62019-03-12 15:45:47 +00003649 if (Thread::Current()->IsForceInterpreter() ||
3650 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003651 // Force the use of interpreter when it is required by the debugger.
3652 return true;
3653 }
3654
Alex Light8f34aba2017-10-09 13:46:32 -07003655 if (Thread::Current()->IsAsyncExceptionPending()) {
3656 // Force use of interpreter to handle async-exceptions
3657 return true;
3658 }
3659
Alex Light2d441b12018-06-08 15:33:21 -07003660 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3661 const void* instr_target = instr->GetCodeForInvoke(method);
3662 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3663 return ShouldUseInterpreterEntrypoint(method, instr_target);
3664 }
3665
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003666 if (runtime->IsJavaDebuggable()) {
3667 // For simplicity, we ignore precompiled code and go to the interpreter
3668 // assuming we don't already have jitted code.
3669 // We could look at the oat file where `quick_code` is being defined,
3670 // and check whether it's been compiled debuggable, but we decided to
3671 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003672 jit::Jit* jit = Runtime::Current()->GetJit();
3673 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3674 }
3675
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003676 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003677 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003678 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003679 // since we want to JIT it (at first use) with extra stackmaps for native
3680 // debugging. We keep however all AOT code from the boot image,
3681 // since the JIT-at-first-use is blocking and would result in non-negligible
3682 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003683 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003684 }
3685
3686 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003687}
3688
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003689void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003690 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003691 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003692 if (klass->NumDirectMethods() == 0) {
3693 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003694 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003695 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003696 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003697 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003698 return; // OAT file unavailable.
3699 }
Ian Rogers19846512012-02-24 11:42:47 -08003700 }
Alex Light64ad14d2014-08-19 14:23:13 -07003701
Mathieu Chartierf8322842014-05-16 10:59:25 -07003702 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003703 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3704 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3705 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003706 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003707 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003708 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003709 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3710 klass->GetDexClassDefIndex(),
3711 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003712 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003713 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003714 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003715 if (!method->IsStatic()) {
3716 // Only update static methods.
3717 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003718 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003719 const void* quick_code = nullptr;
3720 if (has_oat_class) {
3721 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003722 quick_code = oat_method.GetQuickCode();
3723 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003724 // Check if we have JIT compiled code for it.
Nicolas Geoffray32384402019-07-17 20:06:44 +01003725 jit::Jit* jit = Runtime::Current()->GetJit();
3726 if (quick_code == nullptr && jit != nullptr) {
3727 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003728 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003729 // Check whether the method is native, in which case it's generic JNI.
3730 if (quick_code == nullptr && method->IsNative()) {
3731 quick_code = GetQuickGenericJniStub();
3732 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003733 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003734 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003735 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003736 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003737 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003738 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003739}
3740
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003741// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3742// method. Should only be called on non-invokable methods.
3743inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003744 DCHECK(method != nullptr);
3745 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003746 method->SetEntryPointFromQuickCompiledCodePtrSize(
3747 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3748 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003749}
3750
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003751static void LinkCode(ClassLinker* class_linker,
3752 ArtMethod* method,
3753 const OatFile::OatClass* oat_class,
3754 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003755 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003756 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003757 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003758 // The following code only applies to a non-compiler runtime.
3759 return;
3760 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003761 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003762 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003763 if (oat_class != nullptr) {
3764 // Every kind of method should at least get an invoke stub from the oat_method.
3765 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003766 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003767 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003768 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003769
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003770 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003771 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003772 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003773
Alex Light9139e002015-10-09 15:59:48 -07003774 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003775 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003776 return;
3777 }
Ian Rogers19846512012-02-24 11:42:47 -08003778
3779 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003780 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003781 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3782 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003783 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003784 } else if (quick_code == nullptr && method->IsNative()) {
3785 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003786 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003787 // Set entry point from compiled code if there's no code or in interpreter only mode.
3788 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003789 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003790
Ian Rogers62d6c772013-02-27 08:32:07 -08003791 if (method->IsNative()) {
3792 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003793 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003794
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003795 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003796 // We have a native method here without code. Then it should have either the generic JNI
3797 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3798 // TODO: this doesn't handle all the cases where trampolines may be installed.
3799 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003800 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3801 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003802 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003803 }
3804}
3805
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003806void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003807 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003808 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003809 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003810 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003811 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003812 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003813 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003814 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003815
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003816 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003817 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003818 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003819 klass->SetAccessFlags(access_flags);
3820 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003821 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003822 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003823
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003824 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003825 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003826}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003827
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003828LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3829 LinearAlloc* allocator,
3830 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003831 if (length == 0) {
3832 return nullptr;
3833 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003834 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3835 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3836 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003837 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003838 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003839 CHECK(ret != nullptr);
3840 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3841 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003842}
3843
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003844LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3845 LinearAlloc* allocator,
3846 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003847 if (length == 0) {
3848 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003849 }
Vladimir Marko14632852015-08-17 12:07:23 +01003850 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3851 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003852 const size_t storage_size =
3853 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003854 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003855 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003856 CHECK(ret != nullptr);
3857 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003858 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003859 }
3860 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003861}
3862
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003863LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003864 if (class_loader == nullptr) {
3865 return Runtime::Current()->GetLinearAlloc();
3866 }
3867 LinearAlloc* allocator = class_loader->GetAllocator();
3868 DCHECK(allocator != nullptr);
3869 return allocator;
3870}
3871
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003872LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003873 if (class_loader == nullptr) {
3874 return Runtime::Current()->GetLinearAlloc();
3875 }
3876 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3877 LinearAlloc* allocator = class_loader->GetAllocator();
3878 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003879 RegisterClassLoader(class_loader);
3880 allocator = class_loader->GetAllocator();
3881 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003882 }
3883 return allocator;
3884}
3885
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003886void ClassLinker::LoadClass(Thread* self,
3887 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003888 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003889 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003890 ClassAccessor accessor(dex_file,
3891 dex_class_def,
3892 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003893 if (!accessor.HasClassData()) {
3894 return;
3895 }
3896 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003897 {
3898 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3899 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003900 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003901 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003902 // We allow duplicate definitions of the same field in a class_data_item
3903 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003904 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003905 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3906 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003907 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003908 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3909 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003910 accessor.NumInstanceFields());
3911 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003912 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003913 uint32_t last_static_field_idx = 0u;
3914 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003915
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003916 // Methods
3917 bool has_oat_class = false;
3918 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3919 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3920 : OatFile::OatClass::Invalid();
3921 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3922 klass->SetMethodsPtr(
3923 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3924 accessor.NumDirectMethods(),
3925 accessor.NumVirtualMethods());
3926 size_t class_def_method_index = 0;
3927 uint32_t last_dex_method_index = dex::kDexNoIndex;
3928 size_t last_class_def_method_index = 0;
3929
3930 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3931 // methods needs to decode all of the fields.
3932 accessor.VisitFieldsAndMethods([&](
3933 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3934 uint32_t field_idx = field.GetIndex();
3935 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3936 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3937 LoadField(field, klass, &sfields->At(num_sfields));
3938 ++num_sfields;
3939 last_static_field_idx = field_idx;
3940 }
3941 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3942 uint32_t field_idx = field.GetIndex();
3943 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3944 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3945 LoadField(field, klass, &ifields->At(num_ifields));
3946 ++num_ifields;
3947 last_instance_field_idx = field_idx;
3948 }
3949 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3950 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3951 image_pointer_size_);
3952 LoadMethod(dex_file, method, klass, art_method);
3953 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3954 uint32_t it_method_index = method.GetIndex();
3955 if (last_dex_method_index == it_method_index) {
3956 // duplicate case
3957 art_method->SetMethodIndex(last_class_def_method_index);
3958 } else {
3959 art_method->SetMethodIndex(class_def_method_index);
3960 last_dex_method_index = it_method_index;
3961 last_class_def_method_index = class_def_method_index;
3962 }
3963 ++class_def_method_index;
3964 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3965 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3966 class_def_method_index - accessor.NumDirectMethods(),
3967 image_pointer_size_);
3968 LoadMethod(dex_file, method, klass, art_method);
3969 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3970 ++class_def_method_index;
3971 });
3972
3973 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003974 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003975 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3976 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3977 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003978 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3979 if (sfields != nullptr) {
3980 sfields->SetSize(num_sfields);
3981 }
3982 if (ifields != nullptr) {
3983 ifields->SetSize(num_ifields);
3984 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003985 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003986 // Set the field arrays.
3987 klass->SetSFieldsPtr(sfields);
3988 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003989 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003990 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003991 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003992 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003993 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003994 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003995}
3996
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003997void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003998 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003999 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004000 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004001 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004002 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00004003
David Brazdil85865692018-10-30 17:26:20 +00004004 // Get access flags from the DexFile and set hiddenapi runtime access flags.
4005 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07004006}
4007
Mathieu Chartier268764d2016-09-13 12:09:38 -07004008void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004009 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004010 Handle<mirror::Class> klass,
4011 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004012 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004013 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07004014 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07004015
Mathieu Chartier268764d2016-09-13 12:09:38 -07004016 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07004017 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004018 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004019 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07004020
David Brazdil85865692018-10-30 17:26:20 +00004021 // Get access flags from the DexFile and set hiddenapi runtime access flags.
4022 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00004023
Ian Rogersdfb325e2013-10-30 01:00:44 -07004024 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07004025 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004026 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
4027 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004028 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004029 klass->SetFinalizable();
4030 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004031 std::string temp;
4032 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07004033 // The Enum class declares a "final" finalize() method to prevent subclasses from
4034 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
4035 // subclasses, so we exclude it here.
4036 // We also want to avoid setting the flag on Object, where we know that finalize() is
4037 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07004038 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
4039 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07004040 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07004041 }
4042 }
4043 }
4044 } else if (method_name[0] == '<') {
4045 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004046 bool is_init = (strcmp("<init>", method_name) == 0);
4047 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07004048 if (UNLIKELY(!is_init && !is_clinit)) {
4049 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
4050 } else {
4051 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
4052 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07004053 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07004054 access_flags |= kAccConstructor;
4055 }
4056 }
4057 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01004058 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
4059 // Check if the native method is annotated with @FastNative or @CriticalNative.
4060 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
4061 dex_file, dst->GetClassDef(), dex_method_idx);
4062 }
Ian Rogers241b5de2013-10-09 17:58:57 -07004063 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00004064 // Must be done after SetAccessFlags since IsAbstract depends on it.
4065 if (klass->IsInterface() && dst->IsAbstract()) {
4066 dst->CalculateAndSetImtIndex();
4067 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07004068}
4069
Ian Rogers7b078e82014-09-10 14:44:24 -07004070void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004071 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004072 self,
4073 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004074 Runtime::Current()->GetLinearAlloc());
4075 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07004076 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07004077}
4078
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004079void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004080 ObjPtr<mirror::DexCache> dex_cache) {
4081 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004082 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07004083 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004084 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004085}
4086
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004087void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004088 ObjPtr<mirror::DexCache> dex_cache,
4089 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004090 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08004091 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00004092 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004093 // For app images, the dex cache location may be a suffix of the dex file location since the
4094 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08004095 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
4096 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004097 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
4098 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00004099 // The following paths checks don't work on preopt when using boot dex files, where the dex
4100 // cache location is the one on device, and the dex_file's location is the one on host.
4101 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
4102 CHECK_GE(dex_file_location.length(), dex_cache_length)
4103 << dex_cache_location << " " << dex_file.GetLocation();
4104 const std::string dex_file_suffix = dex_file_location.substr(
4105 dex_file_location.length() - dex_cache_length,
4106 dex_cache_length);
4107 // Example dex_cache location is SettingsProvider.apk and
4108 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
4109 CHECK_EQ(dex_cache_location, dex_file_suffix);
4110 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004111 const OatFile* oat_file =
4112 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00004113 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
4114 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
4115 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
4116 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08004117 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004118 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
4119 DexCacheData data = *it;
4120 if (self->IsJWeakCleared(data.weak_root)) {
4121 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004122 it = dex_caches_.erase(it);
4123 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00004124 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004125 it->dex_file->GetOatDexFile() != nullptr &&
4126 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00004127 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004128 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004129 ++it;
4130 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004131 }
Vladimir Markob066d432018-01-03 13:14:37 +00004132 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00004133 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004134 }
David Brazdila5c3a802019-03-08 14:59:41 +00004135 // Let hiddenapi assign a domain to the newly registered dex file.
4136 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
4137
Vladimir Markocd556b02017-02-03 11:47:34 +00004138 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004139 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004140 DexCacheData data;
4141 data.weak_root = dex_cache_jweak;
4142 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00004143 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00004144 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00004145 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004146 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
4147 // path dex caches without an image.
4148 data.class_table->InsertStrongRoot(dex_cache);
4149 if (class_loader != nullptr) {
4150 // Since we added a strong root to the class table, do the write barrier as required for
4151 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004152 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004153 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004154 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004155}
4156
Vladimir Markocd556b02017-02-03 11:47:34 +00004157ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
4158 return data.IsValid()
4159 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
4160 : nullptr;
4161}
4162
4163ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
4164 Thread* self,
4165 ObjPtr<mirror::DexCache> dex_cache,
4166 const DexCacheData& data,
4167 ObjPtr<mirror::ClassLoader> class_loader) {
4168 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
4169 if (data.class_table != ClassTableForClassLoader(class_loader)) {
4170 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
4171 "Attempt to register dex file %s with multiple class loaders",
4172 data.dex_file->GetLocation().c_str());
4173 return nullptr;
4174 }
4175 return dex_cache;
4176}
4177
Alex Light07f06212017-06-01 14:01:43 -07004178void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
4179 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004180 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07004181 Thread* self = Thread::Current();
4182 StackHandleScope<2> hs(self);
4183 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
4184 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
4185 const DexFile* dex_file = dex_cache->GetDexFile();
4186 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
4187 if (kIsDebugBuild) {
4188 DexCacheData old_data;
4189 {
4190 ReaderMutexLock mu(self, *Locks::dex_lock_);
4191 old_data = FindDexCacheDataLocked(*dex_file);
4192 }
4193 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
4194 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
4195 << "been registered on dex file " << dex_file->GetLocation();
4196 }
4197 ClassTable* table;
4198 {
4199 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4200 table = InsertClassTableForClassLoader(h_class_loader.Get());
4201 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004202 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4203 // a thread holding the dex lock and blocking on a condition variable regarding
4204 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004205 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07004206 WriterMutexLock mu(self, *Locks::dex_lock_);
4207 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
4208 table->InsertStrongRoot(h_dex_cache.Get());
4209 if (h_class_loader.Get() != nullptr) {
4210 // Since we added a strong root to the class table, do the write barrier as required for
4211 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004212 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004213 }
4214}
4215
Vladimir Markocd556b02017-02-03 11:47:34 +00004216ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4217 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004218 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00004219 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004220 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004221 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004222 old_data = FindDexCacheDataLocked(dex_file);
4223 }
4224 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
4225 if (old_dex_cache != nullptr) {
4226 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07004227 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004228 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004229 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4230 DCHECK(linear_alloc != nullptr);
4231 ClassTable* table;
4232 {
4233 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4234 table = InsertClassTableForClassLoader(class_loader);
4235 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004236 // Don't alloc while holding the lock, since allocation may need to
4237 // suspend all threads and another thread may need the dex_lock_ to
4238 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004239 StackHandleScope<3> hs(self);
4240 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004241 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07004242 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
4243 self,
4244 dex_file)));
4245 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004246 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004247 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4248 // a thread holding the dex lock and blocking on a condition variable regarding
4249 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004250 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004251 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004252 old_data = FindDexCacheDataLocked(dex_file);
4253 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004254 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004255 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
4256 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
4257 // that the arrays are null.
4258 mirror::DexCache::InitializeDexCache(self,
4259 h_dex_cache.Get(),
4260 h_location.Get(),
4261 &dex_file,
4262 linear_alloc,
4263 image_pointer_size_);
4264 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004265 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004266 }
4267 if (old_dex_cache != nullptr) {
4268 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4269 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004270 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00004271 self->ClearException();
4272 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
4273 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
4274 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004275 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004276 self->AssertPendingOOMException();
4277 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004278 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004279 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004280 if (h_class_loader.Get() != nullptr) {
4281 // Since we added a strong root to the class table, do the write barrier as required for
4282 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004283 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004284 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004285 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004286}
4287
Vladimir Markocd556b02017-02-03 11:47:34 +00004288bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004289 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004290 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004291}
4292
Vladimir Markocd556b02017-02-03 11:47:34 +00004293ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4294 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004295 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
4296 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004297 if (dex_cache != nullptr) {
4298 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004299 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004300 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004301 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004302 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004303 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004304 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004305 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004306 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
4307 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004308 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004309}
4310
Vladimir Markocd556b02017-02-03 11:47:34 +00004311ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4312 const DexFile* dex_file = dex_cache->GetDexFile();
4313 DCHECK(dex_file != nullptr);
4314 ReaderMutexLock mu(self, *Locks::dex_lock_);
4315 // Search assuming unique-ness of dex file.
4316 for (const DexCacheData& data : dex_caches_) {
4317 // Avoid decoding (and read barriers) other unrelated dex caches.
4318 if (data.dex_file == dex_file) {
4319 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
4320 if (registered_dex_cache != nullptr) {
4321 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4322 return data.class_table;
4323 }
4324 }
4325 }
4326 return nullptr;
4327}
4328
4329ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
4330 // Search assuming unique-ness of dex file.
4331 for (const DexCacheData& data : dex_caches_) {
4332 // Avoid decoding (and read barriers) other unrelated dex caches.
4333 if (data.dex_file == &dex_file) {
4334 return data;
4335 }
4336 }
4337 return DexCacheData();
4338}
4339
Vladimir Marko70e2a762019-07-12 16:49:00 +01004340void ClassLinker::CreatePrimitiveClass(Thread* self,
4341 Primitive::Type type,
4342 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004343 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004344 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004345 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4346 // Do not hold lock on the primitive class object, the initialization of
4347 // primitive classes is done while the process is still single threaded.
4348 primitive_class->SetAccessFlags(
4349 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4350 primitive_class->SetPrimitiveType(type);
4351 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4352 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4353 // the kAccVerificationAttempted flag was added above, and there are no
4354 // methods that need the kAccSkipAccessChecks flag.
4355 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004356 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4357 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004358 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004359 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004360 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004361 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004362 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004363 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004364}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004365
Vladimir Marko02610552018-06-04 14:38:00 +01004366inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4367 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4368}
4369
Brian Carlstrombe977852011-07-19 14:54:54 -07004370// Create an array class (i.e. the class object for the array, not the
4371// array itself). "descriptor" looks like "[C" or "[[[[B" or
4372// "[Ljava/lang/String;".
4373//
4374// If "descriptor" refers to an array of primitives, look up the
4375// primitive type's internally-generated class object.
4376//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004377// "class_loader" is the class loader of the class that's referring to
4378// us. It's used to ensure that we're looking for the element type in
4379// the right context. It does NOT become the class loader for the
4380// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004381//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004382// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004383ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4384 const char* descriptor,
4385 size_t hash,
4386 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004387 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004388 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004389 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004390
4391 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4392 // code to be executed. We put it up here so we can avoid all the allocations associated with
4393 // creating the class. This can happen with (eg) jit threads.
4394 if (!self->CanLoadClasses()) {
4395 // Make sure we don't try to load anything, potentially causing an infinite loop.
4396 ObjPtr<mirror::Throwable> pre_allocated =
4397 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4398 self->SetException(pre_allocated);
4399 return nullptr;
4400 }
4401
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004402 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4403 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004404 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004405 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004406 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004407 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4408 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004409 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004410 DCHECK(self->IsExceptionPending());
4411 return nullptr;
4412 } else {
4413 self->ClearException();
4414 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004415 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004416 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4417 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4418 return nullptr;
4419 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004420 // See if the component type is already loaded. Array classes are
4421 // always associated with the class loader of their underlying
4422 // element type -- an array of Strings goes with the loader for
4423 // java/lang/String -- so we need to look for it there. (The
4424 // caller should have checked for the existence of the class
4425 // before calling here, but they did so with *their* class loader,
4426 // not the component type's loader.)
4427 //
4428 // If we find it, the caller adds "loader" to the class' initiating
4429 // loader list, which should prevent us from going through this again.
4430 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004431 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004432 // are the same, because our caller (FindClass) just did the
4433 // lookup. (Even if we get this wrong we still have correct behavior,
4434 // because we effectively do this lookup again when we add the new
4435 // class to the hash table --- necessary because of possible races with
4436 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004437 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004438 ObjPtr<mirror::Class> new_class =
4439 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004440 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004441 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004442 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004443 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004444 // Core array classes, i.e. Object[], Class[], String[] and primitive
4445 // arrays, have special initialization and they should be found above.
4446 DCHECK(!component_type->IsObjectClass() ||
4447 // Guard from false positives for errors before setting superclass.
4448 component_type->IsErroneousUnresolved());
4449 DCHECK(!component_type->IsStringClass());
4450 DCHECK(!component_type->IsClassClass());
4451 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004452
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004453 // Fill out the fields in the Class.
4454 //
4455 // It is possible to execute some methods against arrays, because
4456 // all arrays are subclasses of java_lang_Object_, so we need to set
4457 // up a vtable. We can just point at the one in java_lang_Object_.
4458 //
4459 // Array classes are simple enough that we don't need to do a full
4460 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004461 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4462 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4463 size_t usable_size)
4464 REQUIRES_SHARED(Locks::mutator_lock_) {
4465 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4466 init_class(obj, usable_size);
4467 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4468 klass->SetComponentType(component_type.Get());
4469 // Do not hold lock for initialization, the fence issued after the visitor
4470 // returns ensures memory visibility together with the implicit consume
4471 // semantics (for all supported architectures) for any thread that loads
4472 // the array class reference from any memory locations afterwards.
4473 FinishArrayClassSetup(klass);
4474 };
4475 auto new_class = hs.NewHandle<mirror::Class>(
4476 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004477 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004478 self->AssertPendingOOMException();
4479 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004480 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004481
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004482 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004483 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004484 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4485 // duplicate events in case of races. Array classes don't really follow dedicated
4486 // load and prepare, anyways.
4487 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4488 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4489
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004490 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004491 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004492 }
4493 // Another thread must have loaded the class after we
4494 // started but before we finished. Abandon what we've
4495 // done.
4496 //
4497 // (Yes, this happens.)
4498
Vladimir Markobcf17522018-06-01 13:14:32 +01004499 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004500}
4501
Vladimir Marko9186b182018-11-06 14:55:54 +00004502ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4503 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004504 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004505 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4506 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4507 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4508 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4509 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4510 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4511 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4512 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4513 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004514 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004515 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004516 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004517 return GetClassRoot(class_root, this);
4518}
4519
4520ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4521 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4522 if (UNLIKELY(result == nullptr)) {
4523 std::string printable_type(PrintableChar(type));
4524 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4525 }
4526 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004527}
4528
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004529ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4530 ObjPtr<mirror::Class> klass,
4531 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004532 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004533 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004534 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004535 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004536 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004537 source += " from ";
4538 source += dex_cache->GetLocation()->ToModifiedUtf8();
4539 }
4540 LOG(INFO) << "Loaded class " << descriptor << source;
4541 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004542 {
4543 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004544 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004545 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004546 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004547 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004548 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004549 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004550 VerifyObject(klass);
4551 class_table->InsertWithHash(klass, hash);
4552 if (class_loader != nullptr) {
4553 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004554 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004555 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004556 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004557 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004558 }
4559 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004560 if (kIsDebugBuild) {
4561 // Test that copied methods correctly can find their holder.
4562 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4563 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4564 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004565 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004566 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004567}
4568
Vladimir Marko1998cd02017-01-13 13:02:58 +00004569void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004570 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4571 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4572 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4573 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004574 }
4575}
4576
Alex Lighte64300b2015-12-15 15:02:47 -08004577// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004578void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004579 LengthPrefixedArray<ArtMethod>* new_methods) {
4580 klass->SetMethodsPtrUnchecked(new_methods,
4581 klass->NumDirectMethods(),
4582 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004583 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004584 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004585}
4586
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004587ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4588 const char* descriptor,
4589 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004590 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4591}
4592
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004593ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4594 const char* descriptor,
4595 size_t hash,
4596 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004597 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4598 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4599 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004600 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004601 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004602 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004603 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004604 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004605 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004606}
4607
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004608class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4609 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004610 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004611
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004612 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004613 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004614 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004615 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004616 if (class_table != nullptr) {
4617 class_table->FreezeSnapshot();
4618 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004619 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004620};
4621
4622void ClassLinker::MoveClassTableToPreZygote() {
4623 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004624 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004625 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004626 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004627}
4628
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004629// Look up classes by hash and descriptor and put all matching ones in the result array.
4630class LookupClassesVisitor : public ClassLoaderVisitor {
4631 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004632 LookupClassesVisitor(const char* descriptor,
4633 size_t hash,
4634 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004635 : descriptor_(descriptor),
4636 hash_(hash),
4637 result_(result) {}
4638
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004639 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004640 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004641 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004642 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004643 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4644 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004645 result_->push_back(klass);
4646 }
4647 }
4648
4649 private:
4650 const char* const descriptor_;
4651 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004652 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004653};
4654
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004655void ClassLinker::LookupClasses(const char* descriptor,
4656 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004657 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004658 Thread* const self = Thread::Current();
4659 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004660 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004661 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004662 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004663 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004664 result.push_back(klass);
4665 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004666 LookupClassesVisitor visitor(descriptor, hash, &result);
4667 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004668}
4669
Alex Lightf1f10492015-10-07 16:08:36 -07004670bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4671 Handle<mirror::Class> klass,
4672 Handle<mirror::Class> supertype) {
4673 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004674 DCHECK(klass != nullptr);
4675 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004676
Alex Lightf1f10492015-10-07 16:08:36 -07004677 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4678 VerifyClass(self, supertype);
4679 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004680
4681 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4682 // The supertype is either verified, or we soft failed at AOT time.
4683 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004684 return true;
4685 }
4686 // If we got this far then we have a hard failure.
4687 std::string error_msg =
4688 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004689 klass->PrettyDescriptor().c_str(),
4690 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004691 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004692 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004693 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004694 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004695 // Set during VerifyClass call (if at all).
4696 self->ClearException();
4697 }
4698 // Change into a verify error.
4699 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004700 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004701 self->GetException()->SetCause(cause.Get());
4702 }
4703 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4704 if (Runtime::Current()->IsAotCompiler()) {
4705 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4706 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004707 // Need to grab the lock to change status.
4708 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004709 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004710 return false;
4711}
4712
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004713verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004714 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004715 {
4716 // TODO: assert that the monitor on the Class is held
4717 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004718
Andreas Gampe884f3b82016-03-30 19:52:58 -07004719 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004720 ClassStatus old_status = klass->GetStatus();
4721 while (old_status == ClassStatus::kVerifying ||
4722 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004723 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004724 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4725 // case we may see the same status again. b/62912904. This is why the check is
4726 // greater or equal.
4727 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004728 << "Class '" << klass->PrettyClass()
4729 << "' performed an illegal verification state transition from " << old_status
4730 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004731 old_status = klass->GetStatus();
4732 }
jeffhao98eacac2011-09-14 16:11:53 -07004733
Andreas Gampe884f3b82016-03-30 19:52:58 -07004734 // The class might already be erroneous, for example at compile time if we attempted to verify
4735 // this class as a parent to another.
4736 if (klass->IsErroneous()) {
4737 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004738 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004739 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004740
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004741 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004742 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004743 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004744 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004745 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004746
4747 // For AOT, don't attempt to re-verify if we have already found we should
4748 // verify at runtime.
4749 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004750 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004751 }
jeffhao98eacac2011-09-14 16:11:53 -07004752
Vladimir Marko2c64a832018-01-04 11:31:56 +00004753 if (klass->GetStatus() == ClassStatus::kResolved) {
4754 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004755 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004756 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004757 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004758 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004759 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004760 }
4761
4762 // Skip verification if disabled.
4763 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004764 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004765 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004766 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004767 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004768 }
4769
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004770 VLOG(class_linker) << "Beginning verification for class: "
4771 << klass->PrettyDescriptor()
4772 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4773
Ian Rogers9ffb0392012-09-10 11:56:50 -07004774 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004775 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004776 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4777 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004778 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004779 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004780 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004781 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004782
Alex Lightf1f10492015-10-07 16:08:36 -07004783 // Verify all default super-interfaces.
4784 //
4785 // (1) Don't bother if the superclass has already had a soft verification failure.
4786 //
4787 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4788 // recursive initialization by themselves. This is because when an interface is initialized
4789 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4790 // but choose not to for an optimization. If the interfaces is being verified due to a class
4791 // initialization (which would need all the default interfaces to be verified) the class code
4792 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004793 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004794 && !klass->IsInterface()) { // See (2)
4795 int32_t iftable_count = klass->GetIfTableCount();
4796 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4797 // Loop through all interfaces this class has defined. It doesn't matter the order.
4798 for (int32_t i = 0; i < iftable_count; i++) {
4799 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004800 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004801 // We only care if we have default interfaces and can skip if we are already verified...
4802 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4803 continue;
4804 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4805 // We had a hard failure while verifying this interface. Just return immediately.
4806 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004807 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004808 } else if (UNLIKELY(!iface->IsVerified())) {
4809 // We softly failed to verify the iface. Stop checking and clean up.
4810 // Put the iface into the supertype handle so we know what caused us to fail.
4811 supertype.Assign(iface.Get());
4812 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004813 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004814 }
4815 }
4816
Alex Lightf1f10492015-10-07 16:08:36 -07004817 // At this point if verification failed, then supertype is the "first" supertype that failed
4818 // verification (without a specific order). If verification succeeded, then supertype is either
4819 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004820 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004821 supertype.Get() == klass->GetSuperClass() ||
4822 !supertype->IsVerified());
4823
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004824 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004825 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004826 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004827 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004828
4829 VLOG(class_linker) << "Class preverified status for class "
4830 << klass->PrettyDescriptor()
4831 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4832 << ": "
4833 << preverified;
4834
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004835 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4836 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004837 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4838 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004839
Ian Rogers62d6c772013-02-27 08:32:07 -08004840 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004841 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004842 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004843 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004844 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004845
4846 // Verification is done, grab the lock again.
4847 ObjectLock<mirror::Class> lock(self, klass);
4848
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004849 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4850 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004851 VLOG(class_linker) << "Soft verification failure in class "
4852 << klass->PrettyDescriptor()
4853 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4854 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004855 }
Ian Rogers1f539342012-10-03 21:09:42 -07004856 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004857 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004858 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004859 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004860 // Even though there were no verifier failures we need to respect whether the super-class and
4861 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004862 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004863 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004864 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004865 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4866 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004867 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004868 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004869 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004870 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004871 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004872 // Soft failures at compile time should be retried at runtime. Soft
4873 // failures at runtime will be handled by slow paths in the generated
4874 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004875 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004876 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004877 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004878 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004879 // As this is a fake verified status, make sure the methods are _not_ marked
4880 // kAccSkipAccessChecks later.
4881 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004882 }
4883 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004884 } else {
David Sehr709b0702016-10-13 09:12:37 -07004885 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004886 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4887 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004888 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004889 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004890 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004891 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004892 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004893 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004894 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004895 // method.
4896 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004897 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004898 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004899
4900 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4901 // Never skip access checks if the verification soft fail is forced.
4902 // Mark the class as having a verification attempt to avoid re-running the verifier.
4903 klass->SetVerificationAttempted();
4904 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004905 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004906 }
Andreas Gampe48498592014-09-10 19:48:05 -07004907 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004908 // Done verifying. Notify the compiler about the verification status, in case the class
4909 // was verified implicitly (eg super class of a compiled class).
4910 if (Runtime::Current()->IsAotCompiler()) {
4911 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4912 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4913 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004914 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004915}
4916
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004917verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4918 Handle<mirror::Class> klass,
4919 verifier::HardFailLogMode log_level,
4920 std::string* error_msg) {
4921 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004922 return verifier::ClassVerifier::VerifyClass(self,
4923 klass.Get(),
4924 runtime->GetCompilerCallbacks(),
4925 runtime->IsAotCompiler(),
4926 log_level,
4927 Runtime::Current()->GetTargetSdkVersion(),
4928 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004929}
4930
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004931bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004932 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004933 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004934 // If we're compiling, we can only verify the class using the oat file if
4935 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004936 // the compilation unit (app - dependencies). We will let the compiler callback
4937 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004938 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004939 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004940 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004941 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004942 return false;
4943 }
4944 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004945 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004946 return false;
4947 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004948 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004949
Andreas Gampeb40d3612018-06-26 15:49:42 -07004950 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004951 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004952 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004953 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4954 // For boot classpath classes in the case we're not using a default boot image:
4955 // we don't have the infrastructure yet to query verification data on individual
4956 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4957 // verified. This should be taken into account when measuring boot time and app
4958 // startup compare to the (current) production system where both:
4959 // 1) updatable boot classpath classes, and
4960 // 2) classes in /system referencing updatable classes
4961 // will be verified at runtime.
David Srbecky3db3d372019-04-17 18:19:17 +01004962 if (Runtime::Current()->IsUsingApexBootImageLocation()) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004963 oat_file_class_status = ClassStatus::kVerified;
4964 return true;
4965 }
4966 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004967 return false;
4968 }
4969
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004970 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004971 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004972 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004973 return true;
4974 }
4975 // If we only verified a subset of the classes at compile time, we can end up with classes that
4976 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004977 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004978 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004979 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004980 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004981 // Compile time verification failed with a soft error. Compile time verification can fail
4982 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004983 // class ... {
4984 // Foo x;
4985 // .... () {
4986 // if (...) {
4987 // v1 gets assigned a type of resolved class Foo
4988 // } else {
4989 // v1 gets assigned a type of unresolved class Bar
4990 // }
4991 // iput x = v1
4992 // } }
4993 // when we merge v1 following the if-the-else it results in Conflict
4994 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4995 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4996 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4997 // at compile time).
4998 return false;
4999 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00005000 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07005001 // Compile time verification failed with a hard error. This is caused by invalid instructions
5002 // in the class. These errors are unrecoverable.
5003 return false;
5004 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005005 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08005006 // Status is uninitialized if we couldn't determine the status at compile time, for example,
5007 // not loading the class.
5008 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
5009 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005010 return false;
5011 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07005012 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07005013 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07005014 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07005015 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005016 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005017}
5018
Alex Light5a559862016-01-29 12:24:48 -08005019void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08005020 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08005021 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005022 }
5023}
5024
Alex Light5a559862016-01-29 12:24:48 -08005025void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005026 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00005027 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005028 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005029 return; // native or abstract method
5030 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005031 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005032 return; // nothing to process
5033 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005034 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005035 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005036 for (uint32_t idx = 0; idx < handlers_size; idx++) {
5037 CatchHandlerIterator iterator(handlers_ptr);
5038 for (; iterator.HasNext(); iterator.Next()) {
5039 // Ensure exception types are resolved so that they don't need resolution to be delivered,
5040 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08005041 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005042 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005043 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005044 DCHECK(Thread::Current()->IsExceptionPending());
5045 Thread::Current()->ClearException();
5046 }
5047 }
5048 }
5049 handlers_ptr = iterator.EndDataPointer();
5050 }
5051}
5052
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01005053ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
5054 jstring name,
5055 jobjectArray interfaces,
5056 jobject loader,
5057 jobjectArray methods,
5058 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005059 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07005060
5061 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
5062 // code to be executed. We put it up here so we can avoid all the allocations associated with
5063 // creating the class. This can happen with (eg) jit-threads.
5064 if (!self->CanLoadClasses()) {
5065 // Make sure we don't try to load anything, potentially causing an infinite loop.
5066 ObjPtr<mirror::Throwable> pre_allocated =
5067 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
5068 self->SetException(pre_allocated);
5069 return nullptr;
5070 }
5071
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005072 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005073 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005074 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005075 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005076 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005077 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005078 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005079 DCHECK(temp_klass->GetClass() != nullptr);
5080 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08005081 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
5082 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005083 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
5084 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
5085 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
5086 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005087 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08005088 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005089 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005090 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00005091 std::string storage;
5092 const char* descriptor = temp_klass->GetDescriptor(&storage);
5093 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005094
Mathieu Chartierd57d4542015-10-14 10:55:30 -07005095 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005096 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07005097
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005098 // Insert the class before loading the fields as the field roots
5099 // (ArtField::declaring_class_) are only visited from the class
5100 // table. There can't be any suspend points between inserting the
5101 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00005102 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005103 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08005104
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005105 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07005106 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07005107 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005108 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005109
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005110 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
5111 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005112 ArtField& interfaces_sfield = sfields->At(0);
5113 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005114 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005115 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005116
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005117 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005118 ArtField& throws_sfield = sfields->At(1);
5119 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005120 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005121 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04005122
Ian Rogers466bb252011-10-14 03:29:56 -07005123 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08005124 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04005125
Alex Lighte64300b2015-12-15 15:02:47 -08005126 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07005127 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01005128 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07005129 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005130 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08005131
5132 // Create the methods array.
5133 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
5134 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005135 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
5136 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08005137 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005138 self->AssertPendingOOMException();
5139 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005140 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005141 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005142
5143 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005144 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005145
5146 // Create virtual method using specified prototypes.
5147 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005148 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005149 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005150 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005151 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005152 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5153 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005154 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005155
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005156 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005157 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005158 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005159 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005160 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005161
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005162 // At this point the class is loaded. Publish a ClassLoad event.
5163 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5164 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5165
5166 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005167 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005168 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005169 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005170 // Link the fields and virtual methods, creating vtable and iftables.
5171 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005172 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005173 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005174 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005175 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005176 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005177 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005178 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005179 CHECK(temp_klass->IsRetired());
5180 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005181
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005182 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005183 interfaces_sfield.SetObject<false>(
5184 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005185 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005186 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5187 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005188 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005189 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005190
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005191 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5192
Vladimir Marko305c38b2018-02-14 11:50:07 +00005193 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5194 // See also ClassLinker::EnsureInitialized().
5195 if (kBitstringSubtypeCheckEnabled) {
5196 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5197 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5198 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5199 }
5200
Vladimir Markobf121912019-06-04 13:49:05 +01005201 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005202 {
5203 // Lock on klass is released. Lock new class object.
5204 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005205 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005206 // Conservatively go through the ClassStatus::kInitialized state.
5207 callback = MarkClassInitialized(self, klass);
5208 }
5209 if (callback != nullptr) {
5210 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005211 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005212
5213 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07005214 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005215 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005216 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5217
Ian Rogersc2b44472011-12-14 21:17:17 -08005218 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005219 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
5220 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005221 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08005222 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005223
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005224 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005225 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005226 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005227 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005228 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005229
5230 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005231 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005232 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005233
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005234 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005235 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005236 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005237 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08005238 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005239 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005240}
5241
Mathieu Chartiere401d142015-04-22 13:56:20 -07005242void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5243 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005244 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5245 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005246
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005247 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5248 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005249 ArtMethod* proxy_constructor =
5250 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005251 DCHECK(proxy_constructor != nullptr)
5252 << "Could not find <init> method in java.lang.reflect.Proxy";
5253
Jeff Haodb8a6642014-08-14 17:18:52 -07005254 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5255 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005256 DCHECK(out != nullptr);
5257 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005258 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005259 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005260 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005261 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5262 kAccPublic |
5263 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005264 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005265
5266 // Set the original constructor method.
5267 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005268}
5269
Mathieu Chartiere401d142015-04-22 13:56:20 -07005270void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005271 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005272 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5273 CHECK_STREQ(np->GetName(), "<init>");
5274 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005275 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005276}
5277
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005278void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005279 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005280 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005281 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005282 DCHECK(out != nullptr);
5283 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005284
Alex Lighte9dd04f2016-03-16 16:09:45 -07005285 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005286 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005287 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5288 // preference to the invocation handler.
5289 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5290 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005291 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5292 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005293 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5294
5295 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5296 // method they copy might (if it's a default method).
5297 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005298
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005299 // Set the original interface method.
5300 out->SetDataPtrSize(prototype, image_pointer_size_);
5301
Ian Rogers466bb252011-10-14 03:29:56 -07005302 // At runtime the method looks like a reference and argument saving method, clone the code
5303 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005304 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005305}
Jesse Wilson95caa792011-10-12 18:14:17 -04005306
Mathieu Chartiere401d142015-04-22 13:56:20 -07005307void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005308 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005309 CHECK(!prototype->IsFinal());
5310 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005311 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005312
5313 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5314 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005315 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005316 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005317}
5318
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005319bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005320 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005321 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005322 return true;
5323 }
5324 if (!can_init_statics) {
5325 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005326 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005327 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005328 return false;
5329 }
5330 // Check if there are encoded static values needing initialization.
5331 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005332 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005333 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005334 if (dex_class_def->static_values_off_ != 0) {
5335 return false;
5336 }
5337 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005338 // If we are a class we need to initialize all interfaces with default methods when we are
5339 // initialized. Check all of them.
5340 if (!klass->IsInterface()) {
5341 size_t num_interfaces = klass->GetIfTableCount();
5342 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005343 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005344 if (iface->HasDefaultMethods() &&
5345 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5346 return false;
5347 }
5348 }
5349 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005350 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005351 if (klass->IsInterface() || !klass->HasSuperClass()) {
5352 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005353 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005354 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005355 if (!can_init_parents && !super_class->IsInitialized()) {
5356 return false;
5357 }
5358 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005359}
5360
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005361bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5362 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005363 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5364
5365 // Are we already initialized and therefore done?
5366 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5367 // an initialized class will never change its state.
5368 if (klass->IsInitialized()) {
5369 return true;
5370 }
5371
5372 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005373 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005374 return false;
5375 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005376
Ian Rogers7b078e82014-09-10 14:44:24 -07005377 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005378 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005379 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005380 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005381
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005382 // Re-check under the lock in case another thread initialized ahead of us.
5383 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005384 return true;
5385 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005386
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005387 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005388 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005389 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005390 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005391 return false;
5392 }
5393
Vladimir Marko72ab6842017-01-20 19:32:50 +00005394 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5395 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005396
5397 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005398 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005399 if (!klass->IsVerified()) {
5400 // We failed to verify, expect either the klass to be erroneous or verification failed at
5401 // compile time.
5402 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005403 // The class is erroneous. This may be a verifier error, or another thread attempted
5404 // verification and/or initialization and failed. We can distinguish those cases by
5405 // whether an exception is already pending.
5406 if (self->IsExceptionPending()) {
5407 // Check that it's a VerifyError.
5408 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005409 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005410 } else {
5411 // Check that another thread attempted initialization.
5412 DCHECK_NE(0, klass->GetClinitThreadId());
5413 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5414 // Need to rethrow the previous failure now.
5415 ThrowEarlierClassFailure(klass.Get(), true);
5416 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005417 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005418 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005419 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005420 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005421 self->AssertNoPendingException();
5422 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005423 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005424 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005425 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005426 } else {
5427 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005428 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005429
5430 // A separate thread could have moved us all the way to initialized. A "simple" example
5431 // involves a subclass of the current class being initialized at the same time (which
5432 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005433 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005434 if (klass->IsInitialized()) {
5435 return true;
5436 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005437 }
5438
Vladimir Marko2c64a832018-01-04 11:31:56 +00005439 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005440 // initializing higher up the stack or another thread has beat us
5441 // to initializing and we need to wait. Either way, this
5442 // invocation of InitializeClass will not be responsible for
5443 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005444 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005445 // Could have got an exception during verification.
5446 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005447 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005448 return false;
5449 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005450 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005451 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005452 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005453 return true;
5454 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005455 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005456 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005457 }
5458
Jeff Haoe2e40342017-07-19 10:45:18 -07005459 // Try to get the oat class's status for this class if the oat file is present. The compiler
5460 // tries to validate superclass descriptors, and writes the result into the oat file.
5461 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5462 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5463 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005464 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005465 const Runtime* runtime = Runtime::Current();
5466 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5467 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5468 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005469 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005470 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005471 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005472 return false;
5473 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005474 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005475
Vladimir Marko2c64a832018-01-04 11:31:56 +00005476 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005477 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005478
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005479 // From here out other threads may observe that we're initializing and so changes of state
5480 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005481 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005482 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005483
5484 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005485 }
5486
Andreas Gampeaf864702019-07-23 14:05:35 -07005487 uint64_t t_sub = 0;
5488
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005489 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005490 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005491 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005492 if (!super_class->IsInitialized()) {
5493 CHECK(!super_class->IsInterface());
5494 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005495 StackHandleScope<1> hs(self);
5496 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Andreas Gampeaf864702019-07-23 14:05:35 -07005497 uint64_t super_t0 = NanoTime();
Ian Rogers7b078e82014-09-10 14:44:24 -07005498 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Andreas Gampeaf864702019-07-23 14:05:35 -07005499 uint64_t super_t1 = NanoTime();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005500 if (!super_initialized) {
5501 // The super class was verified ahead of entering initializing, we should only be here if
5502 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005503 // For the case of aot compiler, the super class might also be initializing but we don't
5504 // want to process circular dependencies in pre-compile.
5505 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005506 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005507 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005508 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005509 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005510 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005511 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005512 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005513 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005514 return false;
5515 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005516 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005517 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005518 }
5519
Alex Lighteb7c1442015-08-31 13:17:42 -07005520 if (!klass->IsInterface()) {
5521 // Initialize interfaces with default methods for the JLS.
5522 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005523 // Only setup the (expensive) handle scope if we actually need to.
5524 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005525 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005526 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5527 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005528 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005529 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005530 CHECK(handle_scope_iface->IsInterface());
5531 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5532 // We have already done this for this interface. Skip it.
5533 continue;
5534 }
5535 // We cannot just call initialize class directly because we need to ensure that ALL
5536 // interfaces with default methods are initialized. Non-default interface initialization
5537 // will not affect other non-default super-interfaces.
Andreas Gampeaf864702019-07-23 14:05:35 -07005538 uint64_t inf_t0 = NanoTime(); // This is not very precise, misses all walking.
Alex Light56a40f52015-10-14 11:07:41 -07005539 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5540 handle_scope_iface,
5541 can_init_statics,
5542 can_init_parents);
Andreas Gampeaf864702019-07-23 14:05:35 -07005543 uint64_t inf_t1 = NanoTime();
Alex Light56a40f52015-10-14 11:07:41 -07005544 if (!iface_initialized) {
5545 ObjectLock<mirror::Class> lock(self, klass);
5546 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005547 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005548 return false;
5549 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005550 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005551 }
5552 }
5553 }
5554
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005555 const size_t num_static_fields = klass->NumStaticFields();
5556 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005557 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005558 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005559 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005560 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005561 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005562
5563 // Eagerly fill in static fields so that the we don't have to do as many expensive
5564 // Class::FindStaticField in ResolveField.
5565 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005566 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005567 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005568 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005569 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005570 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005571 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5572 field,
5573 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5574 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005575 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005576 } else {
5577 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005578 }
5579 }
5580
Vladimir Markoe11dd502017-12-08 14:09:45 +00005581 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5582 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005583 this,
5584 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005585 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005586
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005587 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005588 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005589 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005590 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5591 if (!value_it.HasNext()) {
5592 break;
5593 }
5594 ArtField* art_field = ResolveField(field.GetIndex(),
5595 dex_cache,
5596 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005597 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005598 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005599 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005600 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005601 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005602 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005603 if (self->IsExceptionPending()) {
5604 break;
5605 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005606 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005607 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005608 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005609 }
5610 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005611
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005612
Mathieu Chartierda595be2016-08-10 13:57:39 -07005613 if (!self->IsExceptionPending()) {
5614 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5615 if (clinit != nullptr) {
5616 CHECK(can_init_statics);
5617 JValue result;
5618 clinit->Invoke(self, nullptr, 0, &result, "V");
5619 }
5620 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005621 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005622 uint64_t t1 = NanoTime();
5623
Vladimir Markobf121912019-06-04 13:49:05 +01005624 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005625 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005626 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005627 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005628
5629 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005630 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005631 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005632 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005633 } else if (Runtime::Current()->IsTransactionAborted()) {
5634 // The exception thrown when the transaction aborted has been caught and cleared
5635 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005636 VLOG(compiler) << "Return from class initializer of "
5637 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005638 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005639 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005640 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005641 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005642 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005643 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5644 RuntimeStats* thread_stats = self->GetStats();
5645 ++global_stats->class_init_count;
5646 ++thread_stats->class_init_count;
Andreas Gampeaf864702019-07-23 14:05:35 -07005647 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5648 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005649 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005650 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005651 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005652 std::string temp;
5653 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005654 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005655 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005656 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005657 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005658 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005659 }
Vladimir Markobf121912019-06-04 13:49:05 +01005660 if (callback != nullptr) {
5661 callback->MakeVisible(self);
5662 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005663 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005664}
5665
Alex Lighteb7c1442015-08-31 13:17:42 -07005666// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5667// and perform the initialization only on those interfaces that contain default methods.
5668bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5669 Handle<mirror::Class> iface,
5670 bool can_init_statics,
5671 bool can_init_parents) {
5672 CHECK(iface->IsInterface());
5673 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005674 // Only create the (expensive) handle scope if we need it.
5675 if (UNLIKELY(num_direct_ifaces > 0)) {
5676 StackHandleScope<1> hs(self);
5677 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5678 // First we initialize all of iface's super-interfaces recursively.
5679 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005680 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005681 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005682 if (!super_iface->HasBeenRecursivelyInitialized()) {
5683 // Recursive step
5684 handle_super_iface.Assign(super_iface);
5685 if (!InitializeDefaultInterfaceRecursive(self,
5686 handle_super_iface,
5687 can_init_statics,
5688 can_init_parents)) {
5689 return false;
5690 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005691 }
5692 }
5693 }
5694
5695 bool result = true;
5696 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5697 // initialize if we don't have default methods.
5698 if (iface->HasDefaultMethods()) {
5699 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5700 }
5701
5702 // Mark that this interface has undergone recursive default interface initialization so we know we
5703 // can skip it on any later class initializations. We do this even if we are not a default
5704 // interface since we can still avoid the traversal. This is purely a performance optimization.
5705 if (result) {
5706 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005707 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5708 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5709 // initialization is a performance optimization (to avoid another idempotent visit
5710 // for other implementing classes/interfaces), and can be revisited later.
5711 ObjectTryLock<mirror::Class> lock(self, iface);
5712 if (lock.Acquired()) {
5713 iface->SetRecursivelyInitialized();
5714 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005715 }
5716 return result;
5717}
5718
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005719bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5720 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005721 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005722 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005723 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005724 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005725 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005726 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005727
5728 // When we wake up, repeat the test for init-in-progress. If
5729 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005730 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005731 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005732 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005733 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005734 return false;
5735 }
5736 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005737 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005738 continue;
5739 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005740 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005741 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005742 // Compile time initialization failed.
5743 return false;
5744 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005745 if (klass->IsErroneous()) {
5746 // The caller wants an exception, but it was thrown in a
5747 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005748 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005749 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005750 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005751 return false;
5752 }
5753 if (klass->IsInitialized()) {
5754 return true;
5755 }
David Sehr709b0702016-10-13 09:12:37 -07005756 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005757 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005758 }
Ian Rogers07140832014-09-30 15:43:59 -07005759 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005760}
5761
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005762static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5763 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005764 ArtMethod* method,
5765 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005766 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005767 DCHECK(Thread::Current()->IsExceptionPending());
5768 DCHECK(!m->IsProxyMethod());
5769 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005770 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5771 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005772 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005773 std::string return_type = dex_file->PrettyType(return_type_idx);
5774 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005775 ThrowWrappedLinkageError(klass.Get(),
5776 "While checking class %s method %s signature against %s %s: "
5777 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005778 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5779 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005780 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005781 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005782 return_type.c_str(), class_loader.c_str());
5783}
5784
5785static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5786 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005787 ArtMethod* method,
5788 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005789 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005790 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005791 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005792 DCHECK(Thread::Current()->IsExceptionPending());
5793 DCHECK(!m->IsProxyMethod());
5794 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005795 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5796 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005797 ThrowWrappedLinkageError(klass.Get(),
5798 "While checking class %s method %s signature against %s %s: "
5799 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005800 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5801 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005802 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005803 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005804 index, arg_type.c_str(), class_loader.c_str());
5805}
5806
5807static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5808 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005809 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005810 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005811 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005812 ThrowLinkageError(klass.Get(),
5813 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005814 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5815 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005816 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005817 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005818 error_msg.c_str());
5819}
5820
Ian Rogersb5fb2072014-12-02 17:22:02 -08005821static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005822 Handle<mirror::Class> klass,
5823 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005824 ArtMethod* method1,
5825 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005826 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005827 {
5828 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005829 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005830 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005831 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005832 return false;
5833 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005834 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005835 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005836 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005837 return false;
5838 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005839 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005840 ThrowSignatureMismatch(klass, super_klass, method1,
5841 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005842 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005843 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005844 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005845 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005846 return false;
5847 }
5848 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005849 const dex::TypeList* types1 = method1->GetParameterTypeList();
5850 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005851 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005852 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005853 ThrowSignatureMismatch(klass, super_klass, method1,
5854 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005855 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005856 return false;
5857 }
5858 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005859 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005860 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005861 ThrowSignatureMismatch(klass, super_klass, method1,
5862 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005863 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005864 return false;
5865 }
5866 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005867 }
5868 uint32_t num_types = types1->Size();
5869 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005870 ThrowSignatureMismatch(klass, super_klass, method1,
5871 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005872 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005873 return false;
5874 }
5875 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005876 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005877 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005878 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005879 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005880 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005881 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005882 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005883 return false;
5884 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005885 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005886 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005887 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005888 if (UNLIKELY(other_param_type == nullptr)) {
5889 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005890 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005891 return false;
5892 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005893 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005894 ThrowSignatureMismatch(klass, super_klass, method1,
5895 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5896 i,
David Sehr709b0702016-10-13 09:12:37 -07005897 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005898 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005899 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005900 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005901 return false;
5902 }
5903 }
5904 return true;
5905}
5906
5907
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005908bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005909 if (klass->IsInterface()) {
5910 return true;
5911 }
Ian Rogers151f2212014-05-06 11:27:27 -07005912 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005913 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005914 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005915 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005916 if (klass->HasSuperClass() &&
5917 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005918 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005919 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005920 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5921 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5922 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005923 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5924 klass,
5925 super_klass,
5926 m,
5927 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005928 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005929 return false;
5930 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005931 }
5932 }
5933 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005934 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005935 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5936 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5937 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005938 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005939 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5940 j, image_pointer_size_);
5941 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5942 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005943 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5944 klass,
5945 super_klass,
5946 m,
5947 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005948 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005949 return false;
5950 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005951 }
5952 }
5953 }
5954 }
5955 return true;
5956}
5957
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005958bool ClassLinker::EnsureInitialized(Thread* self,
5959 Handle<mirror::Class> c,
5960 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005961 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005962 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005963
Mathieu Chartier524507a2014-08-27 15:28:28 -07005964 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005965 // If we've seen an initialized but not visibly initialized class
5966 // many times, request visible initialization.
5967 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5968 // Thanks to the x86 memory model classes skip the initialized status.
5969 DCHECK(c->IsVisiblyInitialized());
5970 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5971 if (self->IncrementMakeVisiblyInitializedCounter()) {
5972 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5973 }
5974 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005975 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005976 return true;
5977 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005978 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5979 //
5980 // Ensure the bitstring is initialized before any of the class initialization
5981 // logic occurs. Once a class initializer starts running, objects can
5982 // escape into the heap and use the subtype checking code.
5983 //
5984 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5985 // can be used as a source for the IsSubClass check, and that all ancestors
5986 // of the class are Assigned (can be used as a target for IsSubClass check)
5987 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005988 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005989 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005990 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005991 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5992 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005993 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005994 if (!success) {
5995 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005996 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005997 }
5998 } else {
5999 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08006000 }
6001 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07006002}
6003
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006004void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
6005 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006006 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006007 for (ArtField& field : new_class->GetIFields()) {
6008 if (field.GetDeclaringClass() == temp_class) {
6009 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006010 }
6011 }
6012
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006013 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006014 for (ArtField& field : new_class->GetSFields()) {
6015 if (field.GetDeclaringClass() == temp_class) {
6016 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006017 }
6018 }
6019
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006020 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006021 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08006022 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006023 if (method.GetDeclaringClass() == temp_class) {
6024 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006025 }
6026 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006027
6028 // Make sure the remembered set and mod-union tables know that we updated some of the native
6029 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006030 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006031}
6032
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006033void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08006034 CHECK(class_loader->GetAllocator() == nullptr);
6035 CHECK(class_loader->GetClassTable() == nullptr);
6036 Thread* const self = Thread::Current();
6037 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08006038 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08006039 // Create and set the class table.
6040 data.class_table = new ClassTable;
6041 class_loader->SetClassTable(data.class_table);
6042 // Create and set the linear allocator.
6043 data.allocator = Runtime::Current()->CreateLinearAlloc();
6044 class_loader->SetAllocator(data.allocator);
6045 // Add to the list so that we know to free the data later.
6046 class_loaders_.push_back(data);
6047}
6048
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006049ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07006050 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07006051 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006052 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07006053 ClassTable* class_table = class_loader->GetClassTable();
6054 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08006055 RegisterClassLoader(class_loader);
6056 class_table = class_loader->GetClassTable();
6057 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07006058 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006059 return class_table;
6060}
6061
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006062ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07006063 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006064}
6065
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006066static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006067 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006068 while (klass->HasSuperClass()) {
6069 klass = klass->GetSuperClass();
6070 if (klass->ShouldHaveImt()) {
6071 return klass->GetImt(pointer_size);
6072 }
6073 }
6074 return nullptr;
6075}
6076
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006077bool ClassLinker::LinkClass(Thread* self,
6078 const char* descriptor,
6079 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006080 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006081 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006082 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006083
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006084 if (!LinkSuperClass(klass)) {
6085 return false;
6086 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006087 ArtMethod* imt_data[ImTable::kSize];
6088 // If there are any new conflicts compared to super class.
6089 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006090 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006091 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006092 return false;
6093 }
Ian Rogers7b078e82014-09-10 14:44:24 -07006094 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006095 return false;
6096 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006097 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006098 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07006099 return false;
6100 }
6101 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00006102 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006103
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006104 ImTable* imt = nullptr;
6105 if (klass->ShouldHaveImt()) {
6106 // If there are any new conflicts compared to the super class we can not make a copy. There
6107 // can be cases where both will have a conflict method at the same slot without having the same
6108 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
6109 // will possibly create a table that is incorrect for either of the classes.
6110 // Same IMT with new_conflict does not happen very often.
6111 if (!new_conflict) {
6112 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
6113 if (super_imt != nullptr) {
6114 bool imt_equals = true;
6115 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
6116 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
6117 }
6118 if (imt_equals) {
6119 imt = super_imt;
6120 }
6121 }
6122 }
6123 if (imt == nullptr) {
6124 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
6125 imt = reinterpret_cast<ImTable*>(
6126 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
6127 if (imt == nullptr) {
6128 return false;
6129 }
6130 imt->Populate(imt_data, image_pointer_size_);
6131 }
6132 }
6133
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006134 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
6135 // We don't need to retire this class as it has no embedded tables or it was created the
6136 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006137 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006138
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006139 if (klass->ShouldHaveEmbeddedVTable()) {
6140 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006141 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006142 if (klass->ShouldHaveImt()) {
6143 klass->SetImt(imt, image_pointer_size_);
6144 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006145
6146 // Update CHA info based on whether we override methods.
6147 // Have to do this before setting the class as resolved which allows
6148 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006149 if (cha_ != nullptr) {
6150 cha_->UpdateAfterLoadingOf(klass);
6151 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006152
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006153 // This will notify waiters on klass that saw the not yet resolved
6154 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006155 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006156 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006157 } else {
6158 CHECK(!klass->IsResolved());
6159 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006160 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006161 Handle<mirror::Class> h_new_class =
6162 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006163 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6164 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6165 // may not see any references to the target space and clean the card for a class if another
6166 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006167 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006168 klass->SetSFieldsPtrUnchecked(nullptr);
6169 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006170 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006171 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006172 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006173 return false;
6174 }
6175
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006176 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6177 ObjectLock<mirror::Class> lock(self, h_new_class);
6178 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006179
6180 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006181 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006182 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006183 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006184 const ObjPtr<mirror::Class> existing =
6185 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006186 if (class_loader != nullptr) {
6187 // We updated the class in the class table, perform the write barrier so that the GC knows
6188 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006189 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006190 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006191 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006192 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006193 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6194 }
6195 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006196
Mingyao Yang063fc772016-08-02 11:02:54 -07006197 // Update CHA info based on whether we override methods.
6198 // Have to do this before setting the class as resolved which allows
6199 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006200 if (cha_ != nullptr) {
6201 cha_->UpdateAfterLoadingOf(h_new_class);
6202 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006203
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006204 // This will notify waiters on temp class that saw the not yet resolved class in the
6205 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006206 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006207
Vladimir Marko2c64a832018-01-04 11:31:56 +00006208 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006209 // This will notify waiters on new_class that saw the not yet resolved
6210 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006211 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006212 // Return the new class.
6213 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006214 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006215 return true;
6216}
6217
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006218bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006219 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006220 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006221 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6222 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006223 // Check that a class does not inherit from itself directly.
6224 //
6225 // TODO: This is a cheap check to detect the straightforward case
6226 // of a class extending itself (b/28685551), but we should do a
6227 // proper cycle detection on loaded classes, to detect all cases
6228 // of class circularity errors (b/28830038).
6229 if (super_class_idx == class_def.class_idx_) {
6230 ThrowClassCircularityError(klass.Get(),
6231 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006232 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006233 return false;
6234 }
6235
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006236 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006237 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006238 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006239 return false;
6240 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006241 // Verify
6242 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006243 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006244 super_class->PrettyDescriptor().c_str(),
6245 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006246 return false;
6247 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006248 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006249 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006250 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006251 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006252 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006253 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006254 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006255 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006256 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006257 DCHECK(Thread::Current()->IsExceptionPending());
6258 return false;
6259 }
6260 // Verify
6261 if (!klass->CanAccess(interface)) {
6262 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006263 ThrowIllegalAccessError(klass.Get(),
6264 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006265 interface->PrettyDescriptor().c_str(),
6266 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006267 return false;
6268 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006269 }
6270 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006271 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006272 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006273 return true;
6274}
6275
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006276bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006277 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006278 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006279 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6280 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006281 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006282 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006283 return false;
6284 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006285 return true;
6286 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006287 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006288 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006289 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006290 return false;
6291 }
6292 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006293 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006294 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6295 return false;
6296 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006297 if (super->IsFinal()) {
6298 ThrowVerifyError(klass.Get(),
6299 "Superclass %s of %s is declared final",
6300 super->PrettyDescriptor().c_str(),
6301 klass->PrettyDescriptor().c_str());
6302 return false;
6303 }
6304 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006305 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006306 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006307 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006308 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006309 return false;
6310 }
6311 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006312 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006313 super->PrettyDescriptor().c_str(),
6314 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006315 return false;
6316 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006317
Brian Carlstromf3632832014-05-20 15:36:53 -07006318 // Inherit kAccClassIsFinalizable from the superclass in case this
6319 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006320 if (super->IsFinalizable()) {
6321 klass->SetFinalizable();
6322 }
6323
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006324 // Inherit class loader flag form super class.
6325 if (super->IsClassLoaderClass()) {
6326 klass->SetClassLoaderClass();
6327 }
6328
Elliott Hughes2da50362011-10-10 16:57:08 -07006329 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006330 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006331 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006332 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006333 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006334 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006335 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006336 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006337 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006338 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006339 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006340 return false;
6341 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006342
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006343 if (kIsDebugBuild) {
6344 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006345 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006346 CHECK(super->IsResolved());
6347 super = super->GetSuperClass();
6348 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006349 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006350 return true;
6351}
6352
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006353// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006354bool ClassLinker::LinkMethods(Thread* self,
6355 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006356 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006357 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006358 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006359 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006360 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6361 // need to have default methods be in the virtuals array of each class but we don't set that up
6362 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006363 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006364 // Link virtual methods then interface methods.
6365 // We set up the interface lookup table first because we need it to determine if we need to update
6366 // any vtable entries with new default method implementations.
6367 return SetupInterfaceLookupTable(self, klass, interfaces)
6368 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006369 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006370}
6371
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006372// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6373// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6374// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006375class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006376 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006377 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006378 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006379 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6380 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006381 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006382 }
6383
6384 const char* GetName() {
6385 if (name_ == nullptr) {
6386 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6387 }
6388 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006389 }
6390
Mathieu Chartiere401d142015-04-22 13:56:20 -07006391 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006392 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006393 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006394 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006395 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006396 if (dex_file_ == other_dex_file) {
6397 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6398 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006399 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006400 uint32_t other_name_len;
6401 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6402 &other_name_len);
6403 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6404 return false;
6405 }
6406 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6407 }
6408
6409 private:
6410 // Dex file for the method to compare against.
6411 const DexFile* const dex_file_;
6412 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006413 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006414 // Lazily computed name from the dex file's strings.
6415 const char* name_;
6416 // Lazily computed name length.
6417 uint32_t name_len_;
6418};
6419
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006420class LinkVirtualHashTable {
6421 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006422 LinkVirtualHashTable(Handle<mirror::Class> klass,
6423 size_t hash_size,
6424 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006425 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006426 : klass_(klass),
6427 hash_size_(hash_size),
6428 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006429 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006430 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6431 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006432
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006433 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006434 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6435 virtual_method_index, image_pointer_size_);
6436 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006437 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006438 uint32_t index = hash % hash_size_;
6439 // Linear probe until we have an empty slot.
6440 while (hash_table_[index] != invalid_index_) {
6441 if (++index == hash_size_) {
6442 index = 0;
6443 }
6444 }
6445 hash_table_[index] = virtual_method_index;
6446 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006447
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006448 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006449 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006450 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006451 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006452 size_t index = hash % hash_size_;
6453 while (true) {
6454 const uint32_t value = hash_table_[index];
6455 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6456 // the block and can safely assume not found.
6457 if (value == invalid_index_) {
6458 break;
6459 }
6460 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006461 ArtMethod* virtual_method =
6462 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6463 if (comparator->HasSameNameAndSignature(
6464 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006465 hash_table_[index] = removed_index_;
6466 return value;
6467 }
6468 }
6469 if (++index == hash_size_) {
6470 index = 0;
6471 }
6472 }
6473 return GetNotFoundIndex();
6474 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006475
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006476 static uint32_t GetNotFoundIndex() {
6477 return invalid_index_;
6478 }
6479
6480 private:
6481 static const uint32_t invalid_index_;
6482 static const uint32_t removed_index_;
6483
6484 Handle<mirror::Class> klass_;
6485 const size_t hash_size_;
6486 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006487 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006488};
6489
6490const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6491const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6492
Stephen Hines1ddd9132017-02-08 01:51:18 -08006493bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006494 Thread* self,
6495 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006496 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006497 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006498 if (klass->IsInterface()) {
6499 // No vtable.
6500 if (!IsUint<16>(num_virtual_methods)) {
6501 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6502 return false;
6503 }
6504 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006505 // Assign each method an IMT index and set the default flag.
6506 for (size_t i = 0; i < num_virtual_methods; ++i) {
6507 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6508 m->SetMethodIndex(i);
6509 if (!m->IsAbstract()) {
6510 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6511 has_defaults = true;
6512 }
6513 }
6514 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6515 // during initialization. This is a performance optimization. We could simply traverse the
6516 // virtual_methods_ array again during initialization.
6517 if (has_defaults) {
6518 klass->SetHasDefaultMethods();
6519 }
6520 return true;
6521 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006522 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6523 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006524 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006525 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006526 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006527 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006528 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006529 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006530 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006531 return false;
6532 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006533 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006534 vtable->SetElementPtrSize(
6535 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006536 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006537 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6538 // might give us new default methods). If no new interfaces then we can skip the rest since
6539 // the class cannot override any of the super-class's methods. This is required for
6540 // correctness since without it we might not update overridden default method vtable entries
6541 // correctly.
6542 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006543 klass->SetVTable(vtable.Get());
6544 return true;
6545 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006546 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006547 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006548 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006549 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006550 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6551 // might give us new default methods). See comment above.
6552 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006553 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006554 return true;
6555 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006556 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6557 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006558 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006559 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006560 return false;
6561 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006562 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006563 // How the algorithm works:
6564 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6565 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6566 // method which has not been matched to a vtable method, and j if the virtual method at the
6567 // index overrode the super virtual method at index j.
6568 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6569 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6570 // the need for the initial vtable which we later shrink back down).
6571 // 3. Add non overridden methods to the end of the vtable.
6572 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006573 // + 1 so that even if we only have new default methods we will still be able to use this hash
6574 // table (i.e. it will never have 0 size).
6575 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006576 uint32_t* hash_table_ptr;
6577 std::unique_ptr<uint32_t[]> hash_heap_storage;
6578 if (hash_table_size <= kMaxStackHash) {
6579 hash_table_ptr = reinterpret_cast<uint32_t*>(
6580 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6581 } else {
6582 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6583 hash_table_ptr = hash_heap_storage.get();
6584 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006585 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006586 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006587 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006588 DCHECK(klass->GetVirtualMethodDuringLinking(
6589 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006590 hash_table.Add(i);
6591 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006592 // 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 -07006593 // the hash table.
6594 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006595 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006596 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006597 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6598 super_method->GetAccessFlags())) {
6599 // Continue on to the next method since this one is package private and canot be overridden.
6600 // Before Android 4.1, the package-private method super_method might have been incorrectly
6601 // overridden.
6602 continue;
6603 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006604 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006605 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006606 // We remove the method so that subsequent lookups will be faster by making the hash-map
6607 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006608 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6609 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006610 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6611 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006612 if (super_method->IsFinal()) {
6613 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6614 virtual_method->PrettyMethod().c_str(),
6615 super_method->GetDeclaringClassDescriptor());
6616 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006617 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006618 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6619 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006620 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006621 // We didn't directly override this method but we might through default methods...
6622 // Check for default method update.
6623 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006624 switch (FindDefaultMethodImplementation(self,
6625 super_method,
6626 klass,
6627 /*out*/&default_method)) {
6628 case DefaultMethodSearchResult::kDefaultConflict: {
6629 // A conflict was found looking for default methods. Note this (assuming it wasn't
6630 // pre-existing) in the translations map.
6631 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6632 // Don't generate another conflict method to reduce memory use as an optimization.
6633 default_translations->insert(
6634 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6635 }
6636 break;
6637 }
6638 case DefaultMethodSearchResult::kAbstractFound: {
6639 // No conflict but method is abstract.
6640 // We note that this vtable entry must be made abstract.
6641 if (UNLIKELY(!super_method->IsAbstract())) {
6642 default_translations->insert(
6643 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6644 }
6645 break;
6646 }
6647 case DefaultMethodSearchResult::kDefaultFound: {
6648 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6649 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6650 // Found a default method implementation that is new.
6651 // TODO Refactor this add default methods to virtuals here and not in
6652 // LinkInterfaceMethods maybe.
6653 // The problem is default methods might override previously present
6654 // default-method or miranda-method vtable entries from the superclass.
6655 // Unfortunately we need these to be entries in this class's virtuals. We do not
6656 // give these entries there until LinkInterfaceMethods so we pass this map around
6657 // to let it know which vtable entries need to be updated.
6658 // Make a note that vtable entry j must be updated, store what it needs to be updated
6659 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6660 // then.
6661 default_translations->insert(
6662 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006663 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6664 << " overridden by default "
6665 << default_method->PrettyMethod()
6666 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006667 }
6668 break;
6669 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006670 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006671 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006672 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006673 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006674 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006675 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006676 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006677 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6678 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006679 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006680 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006681 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006682 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006683 local_method->SetMethodIndex(actual_count);
6684 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006685 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006686 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006687 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006688 return false;
6689 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006690 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006691 CHECK_LE(actual_count, max_count);
6692 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006693 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6694 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006695 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006696 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006697 return false;
6698 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006699 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006700 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006701 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006702 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006703 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006704 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6705 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006706 return false;
6707 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006708 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006709 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006710 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006711 return false;
6712 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006713 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006714 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6715 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006716 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006717 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006718 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006719 }
6720 return true;
6721}
6722
Alex Light9139e002015-10-09 15:59:48 -07006723// Determine if the given iface has any subinterface in the given list that declares the method
6724// specified by 'target'.
6725//
6726// Arguments
6727// - self: The thread we are running on
6728// - target: A comparator that will match any method that overrides the method we are checking for
6729// - iftable: The iftable we are searching for an overriding method on.
6730// - ifstart: The index of the interface we are checking to see if anything overrides
6731// - iface: The interface we are checking to see if anything overrides.
6732// - image_pointer_size:
6733// The image pointer size.
6734//
6735// Returns
6736// - True: There is some method that matches the target comparator defined in an interface that
6737// is a subtype of iface.
6738// - False: There is no method that matches the target comparator in any interface that is a subtype
6739// of iface.
6740static bool ContainsOverridingMethodOf(Thread* self,
6741 MethodNameAndSignatureComparator& target,
6742 Handle<mirror::IfTable> iftable,
6743 size_t ifstart,
6744 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006745 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006746 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006747 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006748 DCHECK(iface != nullptr);
6749 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006750 DCHECK_GE(ifstart, 0u);
6751 DCHECK_LT(ifstart, iftable->Count());
6752 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6753 DCHECK(iface->IsInterface());
6754
6755 size_t iftable_count = iftable->Count();
6756 StackHandleScope<1> hs(self);
6757 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6758 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6759 // Skip ifstart since our current interface obviously cannot override itself.
6760 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006761 // Iterate through every method on this interface. The order does not matter.
6762 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006763 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006764 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006765 // Check if the i'th interface is a subtype of this one.
6766 if (iface->IsAssignableFrom(current_iface.Get())) {
6767 return true;
6768 }
6769 break;
6770 }
6771 }
6772 }
6773 return false;
6774}
6775
Alex Lighteb7c1442015-08-31 13:17:42 -07006776// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006777// out_default_method and returns kDefaultFound on success. If no default method was found return
6778// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6779// default_method conflict) it will return kDefaultConflict.
6780ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6781 Thread* self,
6782 ArtMethod* target_method,
6783 Handle<mirror::Class> klass,
6784 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006785 DCHECK(self != nullptr);
6786 DCHECK(target_method != nullptr);
6787 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006788
6789 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006790
6791 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6792 // table. This lets us walk the table backwards when searching for default methods. The first one
6793 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6794 // track of it and then continue checking all other interfaces, since we need to throw an error if
6795 // we encounter conflicting default method implementations (one is not a subtype of the other).
6796 //
6797 // The order of unrelated interfaces does not matter and is not defined.
6798 size_t iftable_count = klass->GetIfTableCount();
6799 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006800 // No interfaces. We have already reset out to null so just return kAbstractFound.
6801 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006802 }
6803
Alex Light9139e002015-10-09 15:59:48 -07006804 StackHandleScope<3> hs(self);
6805 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006806 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006807 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006808 MethodNameAndSignatureComparator target_name_comparator(
6809 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6810 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006811 for (size_t k = iftable_count; k != 0; ) {
6812 --k;
6813
Alex Lighteb7c1442015-08-31 13:17:42 -07006814 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006815
6816 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006817 // Iterate through every declared method on this interface. The order does not matter.
6818 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6819 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006820 // Skip abstract methods and methods with different names.
6821 if (current_method->IsAbstract() ||
6822 !target_name_comparator.HasSameNameAndSignature(
6823 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6824 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006825 } else if (!current_method->IsPublic()) {
6826 // The verifier should have caught the non-public method for dex version 37. Just warn and
6827 // skip it since this is from before default-methods so we don't really need to care that it
6828 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006829 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6830 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006831 << "This will be a fatal error in subsequent versions of android. "
6832 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006833 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006834 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006835 // We have multiple default impls of the same method. This is a potential default conflict.
6836 // We need to check if this possibly conflicting method is either a superclass of the chosen
6837 // default implementation or is overridden by a non-default interface method. In either case
6838 // there is no conflict.
6839 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6840 !ContainsOverridingMethodOf(self,
6841 target_name_comparator,
6842 iftable,
6843 k,
6844 iface,
6845 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006846 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006847 << current_method->PrettyMethod() << " and "
6848 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6849 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006850 *out_default_method = nullptr;
6851 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006852 } else {
6853 break; // Continue checking at the next interface.
6854 }
6855 } else {
Alex Light9139e002015-10-09 15:59:48 -07006856 // chosen_iface == null
6857 if (!ContainsOverridingMethodOf(self,
6858 target_name_comparator,
6859 iftable,
6860 k,
6861 iface,
6862 image_pointer_size_)) {
6863 // Don't set this as the chosen interface if something else is overriding it (because that
6864 // other interface would be potentially chosen instead if it was default). If the other
6865 // interface was abstract then we wouldn't select this interface as chosen anyway since
6866 // the abstract method masks it.
6867 *out_default_method = current_method;
6868 chosen_iface.Assign(iface.Get());
6869 // We should now finish traversing the graph to find if we have default methods that
6870 // conflict.
6871 } else {
David Sehr709b0702016-10-13 09:12:37 -07006872 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6873 << "' was "
6874 << "skipped because it was overridden by an abstract method in a "
6875 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006876 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006877 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006878 break;
6879 }
6880 }
Alex Light9139e002015-10-09 15:59:48 -07006881 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006882 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6883 << "' selected "
6884 << "as the implementation for '" << target_method->PrettyMethod()
6885 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006886 return DefaultMethodSearchResult::kDefaultFound;
6887 } else {
6888 return DefaultMethodSearchResult::kAbstractFound;
6889 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006890}
6891
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006892ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006893 ArtMethod* conflict_method,
6894 ArtMethod* interface_method,
6895 ArtMethod* method,
6896 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006897 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006898 Runtime* const runtime = Runtime::Current();
6899 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6900 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6901
6902 // Create a new entry if the existing one is the shared conflict method.
6903 ArtMethod* new_conflict_method = new_entry
6904 ? runtime->CreateImtConflictMethod(linear_alloc)
6905 : conflict_method;
6906
6907 // Allocate a new table. Note that we will leak this table at the next conflict,
6908 // but that's a tradeoff compared to making the table fixed size.
6909 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006910 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6911 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006912 if (data == nullptr) {
6913 LOG(ERROR) << "Failed to allocate conflict table";
6914 return conflict_method;
6915 }
6916 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6917 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006918 method,
6919 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006920
6921 // Do a fence to ensure threads see the data in the table before it is assigned
6922 // to the conflict method.
6923 // Note that there is a race in the presence of multiple threads and we may leak
6924 // memory from the LinearAlloc, but that's a tradeoff compared to using
6925 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006926 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006927 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006928 return new_conflict_method;
6929}
6930
Vladimir Marko921094a2017-01-12 18:37:06 +00006931bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6932 Handle<mirror::Class> klass,
6933 Handle<mirror::IfTable> iftable) {
6934 DCHECK(!klass->IsInterface());
6935 const bool has_superclass = klass->HasSuperClass();
6936 const bool extend_super_iftable = has_superclass;
6937 const size_t ifcount = klass->GetIfTableCount();
6938 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6939 for (size_t i = 0; i < ifcount; ++i) {
6940 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6941 if (num_methods > 0) {
6942 const bool is_super = i < super_ifcount;
6943 // This is an interface implemented by a super-class. Therefore we can just copy the method
6944 // array from the superclass.
6945 const bool super_interface = is_super && extend_super_iftable;
6946 ObjPtr<mirror::PointerArray> method_array;
6947 if (super_interface) {
6948 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6949 DCHECK(if_table != nullptr);
6950 DCHECK(if_table->GetMethodArray(i) != nullptr);
6951 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006952 StackHandleScope<1u> hs(self);
6953 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6954 method_array =
6955 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006956 } else {
6957 method_array = AllocPointerArray(self, num_methods);
6958 }
6959 if (UNLIKELY(method_array == nullptr)) {
6960 self->AssertPendingOOMException();
6961 return false;
6962 }
6963 iftable->SetMethodArray(i, method_array);
6964 }
6965 }
6966 return true;
6967}
6968
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006969void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6970 ArtMethod* imt_conflict_method,
6971 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006972 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006973 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006974 // Place method in imt if entry is empty, place conflict otherwise.
6975 if (*imt_ref == unimplemented_method) {
6976 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006977 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006978 // If we are not a conflict and we have the same signature and name as the imt
6979 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006980 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6981 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006982 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006983 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006984 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006985 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006986 *imt_ref = current_method;
6987 } else {
Alex Light9139e002015-10-09 15:59:48 -07006988 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006989 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006990 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006991 } else {
6992 // Place the default conflict method. Note that there may be an existing conflict
6993 // method in the IMT, but it could be one tailored to the super class, with a
6994 // specific ImtConflictTable.
6995 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006996 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006997 }
6998}
6999
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007000void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07007001 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
7002 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007003 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007004 Runtime* const runtime = Runtime::Current();
7005 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
7006 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007007 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007008 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007009 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007010 FillIMTFromIfTable(klass->GetIfTable(),
7011 unimplemented_method,
7012 conflict_method,
7013 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007014 /*create_conflict_tables=*/true,
7015 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007016 &new_conflict,
7017 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007018 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007019 if (!klass->ShouldHaveImt()) {
7020 return;
7021 }
7022 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
7023 // we can just use the same pointer.
7024 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007025 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007026 if (super_class != nullptr && super_class->ShouldHaveImt()) {
7027 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7028 bool same = true;
7029 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
7030 ArtMethod* method = imt_data[i];
7031 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
7032 if (method != super_method) {
7033 bool is_conflict_table = method->IsRuntimeMethod() &&
7034 method != unimplemented_method &&
7035 method != conflict_method;
7036 // Verify conflict contents.
7037 bool super_conflict_table = super_method->IsRuntimeMethod() &&
7038 super_method != unimplemented_method &&
7039 super_method != conflict_method;
7040 if (!is_conflict_table || !super_conflict_table) {
7041 same = false;
7042 } else {
7043 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
7044 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
7045 same = same && table1->Equals(table2, image_pointer_size_);
7046 }
7047 }
7048 }
7049 if (same) {
7050 imt = super_imt;
7051 }
7052 }
7053 if (imt == nullptr) {
7054 imt = klass->GetImt(image_pointer_size_);
7055 DCHECK(imt != nullptr);
7056 imt->Populate(imt_data, image_pointer_size_);
7057 } else {
7058 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007059 }
7060}
7061
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007062ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
7063 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07007064 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007065 void* data = linear_alloc->Alloc(Thread::Current(),
7066 ImtConflictTable::ComputeSize(count,
7067 image_pointer_size));
7068 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
7069}
7070
7071ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
7072 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
7073}
7074
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007075void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007076 ArtMethod* unimplemented_method,
7077 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007078 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007079 bool create_conflict_tables,
7080 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007081 /*out*/bool* new_conflict,
7082 /*out*/ArtMethod** imt) {
7083 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007084 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007085 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007086 const size_t num_virtuals = interface->NumVirtualMethods();
7087 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7088 // Virtual methods can be larger than the if table methods if there are default methods.
7089 DCHECK_GE(num_virtuals, method_array_count);
7090 if (kIsDebugBuild) {
7091 if (klass->IsInterface()) {
7092 DCHECK_EQ(method_array_count, 0u);
7093 } else {
7094 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
7095 }
7096 }
7097 if (method_array_count == 0) {
7098 continue;
7099 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007100 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007101 for (size_t j = 0; j < method_array_count; ++j) {
7102 ArtMethod* implementation_method =
7103 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7104 if (ignore_copied_methods && implementation_method->IsCopied()) {
7105 continue;
7106 }
7107 DCHECK(implementation_method != nullptr);
7108 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7109 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7110 // or interface methods in the IMT here they will not create extra conflicts since we compare
7111 // names and signatures in SetIMTRef.
7112 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007113 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007114
7115 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7116 // the same implementation method, keep track of this to avoid creating a conflict table in
7117 // this case.
7118
7119 // Conflict table size for each IMT slot.
7120 ++conflict_counts[imt_index];
7121
7122 SetIMTRef(unimplemented_method,
7123 imt_conflict_method,
7124 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007125 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007126 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007127 }
7128 }
7129
7130 if (create_conflict_tables) {
7131 // Create the conflict tables.
7132 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007133 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007134 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007135 if (imt[i] == imt_conflict_method) {
7136 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7137 if (new_table != nullptr) {
7138 ArtMethod* new_conflict_method =
7139 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7140 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7141 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007142 } else {
7143 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007144 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007145 }
7146 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007147 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007148 }
7149 }
7150
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007151 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007152 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007153 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7154 // Virtual methods can be larger than the if table methods if there are default methods.
7155 if (method_array_count == 0) {
7156 continue;
7157 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007158 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007159 for (size_t j = 0; j < method_array_count; ++j) {
7160 ArtMethod* implementation_method =
7161 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7162 if (ignore_copied_methods && implementation_method->IsCopied()) {
7163 continue;
7164 }
7165 DCHECK(implementation_method != nullptr);
7166 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007167 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007168 if (!imt[imt_index]->IsRuntimeMethod() ||
7169 imt[imt_index] == unimplemented_method ||
7170 imt[imt_index] == imt_conflict_method) {
7171 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007172 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007173 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7174 const size_t num_entries = table->NumEntries(image_pointer_size_);
7175 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7176 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007177 }
7178 }
7179 }
7180}
7181
Alex Lighteb7c1442015-08-31 13:17:42 -07007182// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7183// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007184static bool NotSubinterfaceOfAny(
7185 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
7186 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007187 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007188 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007189 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007190 for (ObjPtr<mirror::Class> c : classes) {
7191 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007192 return false;
7193 }
7194 }
7195 return true;
7196}
7197
7198// Fills in and flattens the interface inheritance hierarchy.
7199//
7200// By the end of this function all interfaces in the transitive closure of to_process are added to
7201// the iftable and every interface precedes all of its sub-interfaces in this list.
7202//
7203// all I, J: Interface | I <: J implies J precedes I
7204//
7205// (note A <: B means that A is a subtype of B)
7206//
7207// This returns the total number of items in the iftable. The iftable might be resized down after
7208// this call.
7209//
7210// We order this backwards so that we do not need to reorder superclass interfaces when new
7211// interfaces are added in subclass's interface tables.
7212//
7213// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7214// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7215// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7216// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007217static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007218 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07007219 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07007220 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007221 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007222 // This is the set of all class's already in the iftable. Used to make checking if a class has
7223 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007224 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07007225 // The first super_ifcount elements are from the superclass. We note that they are already added.
7226 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007227 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007228 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
7229 classes_in_iftable.insert(iface);
7230 }
7231 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007232 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007233 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7234 // At this point in the loop current-iface-list has the invariant that:
7235 // for every pair of interfaces I,J within it:
7236 // if index_of(I) < index_of(J) then I is not a subtype of J
7237
7238 // If we have already seen this element then all of its super-interfaces must already be in the
7239 // current-iface-list so we can skip adding it.
7240 if (!ContainsElement(classes_in_iftable, interface)) {
7241 // We haven't seen this interface so add all of its super-interfaces onto the
7242 // current-iface-list, skipping those already on it.
7243 int32_t ifcount = interface->GetIfTableCount();
7244 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007245 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007246 if (!ContainsElement(classes_in_iftable, super_interface)) {
7247 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
7248 classes_in_iftable.insert(super_interface);
7249 iftable->SetInterface(filled_ifcount, super_interface);
7250 filled_ifcount++;
7251 }
7252 }
7253 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7254 // Place this interface onto the current-iface-list after all of its super-interfaces.
7255 classes_in_iftable.insert(interface);
7256 iftable->SetInterface(filled_ifcount, interface);
7257 filled_ifcount++;
7258 } else if (kIsDebugBuild) {
7259 // Check all super-interfaces are already in the list.
7260 int32_t ifcount = interface->GetIfTableCount();
7261 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007262 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007263 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007264 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7265 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007266 }
7267 }
7268 }
7269 if (kIsDebugBuild) {
7270 // Check that the iftable is ordered correctly.
7271 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007272 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007273 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007274 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007275 // !(if_a <: if_b)
7276 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007277 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7278 << ") extends "
7279 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007280 << "interface list.";
7281 }
7282 }
7283 }
7284 return filled_ifcount;
7285}
7286
7287bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
7288 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7289 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007290 const bool has_superclass = klass->HasSuperClass();
7291 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007292 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007293 const size_t num_interfaces =
7294 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007295 if (num_interfaces == 0) {
7296 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007297 if (LIKELY(has_superclass)) {
7298 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7299 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007300 // Class implements no interfaces.
7301 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007302 return true;
7303 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007304 // Class implements same interfaces as parent, are any of these not marker interfaces?
7305 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007306 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007307 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007308 if (super_iftable->GetMethodArrayCount(i) > 0) {
7309 has_non_marker_interface = true;
7310 break;
7311 }
7312 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007313 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007314 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007315 klass->SetIfTable(super_iftable);
7316 return true;
7317 }
7318 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007319 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007320 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007321 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007322 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007323 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007324 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007325 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007326 if (UNLIKELY(!interface->IsInterface())) {
7327 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007328 ThrowIncompatibleClassChangeError(klass.Get(),
7329 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007330 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007331 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7332 return false;
7333 }
7334 ifcount += interface->GetIfTableCount();
7335 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007336 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007337 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007338 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007339 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007340 return false;
7341 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007342 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007343 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007344 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007345 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007346 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007347 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007348 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007349 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007350
7351 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7352 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7353 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007354 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007355
7356 size_t new_ifcount;
7357 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007358 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007359 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007360 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007361 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007362 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007363 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007364 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007365
7366 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007367 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007368
Ian Rogers7b078e82014-09-10 14:44:24 -07007369 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007370
Ian Rogersb52b01a2012-01-12 17:01:38 -08007371 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007372 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007373 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007374 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007375 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007376 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007377 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007378 return false;
7379 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007380 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007381 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007382 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007383 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007384 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007385 return true;
7386}
7387
Alex Light1f3925d2016-09-07 12:04:20 -07007388// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7389// of methods must be unique.
7390static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7391 return nullptr;
7392}
7393
7394template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007395static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007396 const ScopedArenaVector<ArtMethod*>& list,
7397 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007398 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007399 for (ArtMethod* method : list) {
7400 if (cmp.HasSameNameAndSignature(method)) {
7401 return method;
7402 }
7403 }
Alex Light1f3925d2016-09-07 12:04:20 -07007404 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007405}
7406
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007407namespace {
7408
Alex Light1f3925d2016-09-07 12:04:20 -07007409// Check that all vtable entries are present in this class's virtuals or are the same as a
7410// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007411void CheckClassOwnsVTableEntries(Thread* self,
7412 Handle<mirror::Class> klass,
7413 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007414 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007415 StackHandleScope<2> hs(self);
7416 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007417 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007418 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007419 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007420 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7421 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7422 CHECK(m != nullptr);
7423
Alex Lighta41a30782017-03-29 11:33:19 -07007424 if (m->GetMethodIndexDuringLinking() != i) {
7425 LOG(WARNING) << m->PrettyMethod()
7426 << " has an unexpected method index for its spot in the vtable for class"
7427 << klass->PrettyClass();
7428 }
Alex Lighte64300b2015-12-15 15:02:47 -08007429 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7430 auto is_same_method = [m] (const ArtMethod& meth) {
7431 return &meth == m;
7432 };
Alex Light3f980532017-03-17 15:10:32 -07007433 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7434 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7435 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7436 << klass->PrettyClass() << " or any of its superclasses!";
7437 }
Alex Lighte64300b2015-12-15 15:02:47 -08007438 }
7439}
7440
Alex Light1f3925d2016-09-07 12:04:20 -07007441// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7442// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007443template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007444void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007445 REQUIRES_SHARED(Locks::mutator_lock_) {
7446 StackHandleScope<1> hs(self);
7447 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7448 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007449
7450 // Observations:
7451 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7452 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7453 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7454 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7455 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7456 // * The single-pass algorithm will trade memory for speed, but that is OK.
7457
7458 CHECK_GT(num_entries, 0);
7459
7460 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7461 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7462 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7463 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7464 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7465 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7466 << m2->PrettyMethod() << " (0x" << std::hex
7467 << reinterpret_cast<uintptr_t>(m2) << ")";
7468 };
7469 struct BaseHashType {
7470 static size_t HashCombine(size_t seed, size_t val) {
7471 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7472 }
7473 };
7474
7475 // Check assuming all entries come from the same dex file.
7476 {
7477 // Find the first interesting method and its dex file.
7478 int32_t start = 0;
7479 for (; start < num_entries; ++start) {
7480 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7481 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7482 // maybe).
7483 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7484 vtable_entry->GetAccessFlags())) {
7485 continue;
7486 }
7487 break;
7488 }
7489 if (start == num_entries) {
7490 return;
7491 }
7492 const DexFile* dex_file =
7493 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7494 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7495
7496 // Helper function to avoid logging if we have to run the cross-file checks.
7497 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7498 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7499 using PairType = std::pair<uint32_t, uint16_t>;
7500 struct PairHash : BaseHashType {
7501 size_t operator()(const PairType& key) const {
7502 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7503 }
7504 };
7505 std::unordered_map<PairType, int32_t, PairHash> seen;
7506 seen.reserve(2 * num_entries);
7507 bool need_slow_path = false;
7508 bool found_dup = false;
7509 for (int i = start; i < num_entries; ++i) {
7510 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7511 // wrt/ kPointerSize.
7512 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7513 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7514 vtable_entry->GetAccessFlags())) {
7515 continue;
7516 }
7517 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7518 if (dex_file != m->GetDexFile()) {
7519 need_slow_path = true;
7520 break;
7521 }
7522 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7523 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7524 auto it = seen.find(pair);
7525 if (it != seen.end()) {
7526 found_dup = true;
7527 if (log_warn) {
7528 log_fn(it->second, i);
7529 }
7530 } else {
7531 seen.emplace(pair, i);
7532 }
7533 }
7534 return std::make_pair(need_slow_path, found_dup);
7535 };
7536 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7537 if (!result.first) {
7538 if (result.second) {
7539 check_fn(/* log_warn= */ true);
7540 }
7541 return;
7542 }
7543 }
7544
7545 // Need to check across dex files.
7546 struct Entry {
7547 size_t cached_hash = 0;
7548 const char* name = nullptr;
7549 Signature signature = Signature::NoSignature();
7550 uint32_t name_len = 0;
7551
7552 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7553 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7554 signature(dex_file->GetMethodSignature(mid)) {
7555 }
7556
7557 bool operator==(const Entry& other) const {
7558 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7559 return false;
7560 }
7561 return signature == other.signature;
7562 }
7563 };
7564 struct EntryHash {
7565 size_t operator()(const Entry& key) const {
7566 return key.cached_hash;
7567 }
7568 };
7569 std::unordered_map<Entry, int32_t, EntryHash> map;
7570 for (int32_t i = 0; i < num_entries; ++i) {
7571 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7572 // wrt/ kPointerSize.
7573 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7574 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7575 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007576 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7577 vtable_entry->GetAccessFlags())) {
7578 continue;
7579 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007580 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7581 const DexFile* dex_file = m->GetDexFile();
7582 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7583
7584 Entry e(dex_file, mid);
7585
7586 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7587 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7588 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7589 sig_hash);
7590
7591 auto it = map.find(e);
7592 if (it != map.end()) {
7593 log_fn(it->second, i);
7594 } else {
7595 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007596 }
7597 }
7598}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007599
7600void CheckVTableHasNoDuplicates(Thread* self,
7601 Handle<mirror::Class> klass,
7602 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007603 REQUIRES_SHARED(Locks::mutator_lock_) {
7604 switch (pointer_size) {
7605 case PointerSize::k64:
7606 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7607 break;
7608 case PointerSize::k32:
7609 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7610 break;
7611 }
7612}
Alex Light1f3925d2016-09-07 12:04:20 -07007613
7614static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7615 REQUIRES_SHARED(Locks::mutator_lock_) {
7616 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7617 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7618}
7619
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007620} // namespace
7621
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007622void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7623 ArtMethod* unimplemented_method,
7624 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007625 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007626 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007627 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007628 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007629 if (super_class->ShouldHaveImt()) {
7630 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7631 for (size_t i = 0; i < ImTable::kSize; ++i) {
7632 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007633 }
7634 } else {
7635 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007636 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007637 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007638 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007639 FillIMTFromIfTable(if_table,
7640 unimplemented_method,
7641 imt_conflict_method,
7642 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007643 /*create_conflict_tables=*/false,
7644 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007645 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007646 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007647 }
7648 }
7649}
7650
Vladimir Marko921094a2017-01-12 18:37:06 +00007651class ClassLinker::LinkInterfaceMethodsHelper {
7652 public:
7653 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7654 Handle<mirror::Class> klass,
7655 Thread* self,
7656 Runtime* runtime)
7657 : class_linker_(class_linker),
7658 klass_(klass),
7659 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7660 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7661 self_(self),
7662 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7663 allocator_(&stack_),
7664 default_conflict_methods_(allocator_.Adapter()),
7665 overriding_default_conflict_methods_(allocator_.Adapter()),
7666 miranda_methods_(allocator_.Adapter()),
7667 default_methods_(allocator_.Adapter()),
7668 overriding_default_methods_(allocator_.Adapter()),
7669 move_table_(allocator_.Adapter()) {
7670 }
7671
7672 ArtMethod* FindMethod(ArtMethod* interface_method,
7673 MethodNameAndSignatureComparator& interface_name_comparator,
7674 ArtMethod* vtable_impl)
7675 REQUIRES_SHARED(Locks::mutator_lock_);
7676
7677 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7678 MethodNameAndSignatureComparator& interface_name_comparator)
7679 REQUIRES_SHARED(Locks::mutator_lock_);
7680
7681 bool HasNewVirtuals() const {
7682 return !(miranda_methods_.empty() &&
7683 default_methods_.empty() &&
7684 overriding_default_methods_.empty() &&
7685 overriding_default_conflict_methods_.empty() &&
7686 default_conflict_methods_.empty());
7687 }
7688
7689 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7690
7691 ObjPtr<mirror::PointerArray> UpdateVtable(
7692 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007693 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007694
7695 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7696
7697 void UpdateIMT(ArtMethod** out_imt);
7698
7699 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7700 if (kIsDebugBuild) {
7701 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7702 // Check that there are no stale methods are in the dex cache array.
7703 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7704 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007705 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7706 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007707 CHECK(move_table_.find(m) == move_table_.end() ||
7708 // The original versions of copied methods will still be present so allow those too.
7709 // Note that if the first check passes this might fail to GetDeclaringClass().
7710 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7711 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7712 [m] (ArtMethod& meth) {
7713 return &meth == m;
7714 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7715 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7716 }
7717 }
7718 }
7719
7720 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7721 LengthPrefixedArray<ArtMethod>* methods) {
7722 if (kIsDebugBuild) {
7723 CHECK(methods != nullptr);
7724 // Put some random garbage in old methods to help find stale pointers.
7725 if (methods != old_methods && old_methods != nullptr) {
7726 // Need to make sure the GC is not running since it could be scanning the methods we are
7727 // about to overwrite.
7728 ScopedThreadStateChange tsc(self_, kSuspended);
7729 gc::ScopedGCCriticalSection gcs(self_,
7730 gc::kGcCauseClassLinker,
7731 gc::kCollectorTypeClassLinker);
7732 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7733 method_size_,
7734 method_alignment_);
7735 memset(old_methods, 0xFEu, old_size);
7736 }
7737 }
7738 }
7739
7740 private:
7741 size_t NumberOfNewVirtuals() const {
7742 return miranda_methods_.size() +
7743 default_methods_.size() +
7744 overriding_default_conflict_methods_.size() +
7745 overriding_default_methods_.size() +
7746 default_conflict_methods_.size();
7747 }
7748
7749 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7750 return !klass_->IsInterface();
7751 }
7752
7753 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7754 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7755 << "Interfaces should only have default-conflict methods appended to them.";
7756 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7757 << miranda_methods_.size()
7758 << " default_methods=" << default_methods_.size()
7759 << " overriding_default_methods=" << overriding_default_methods_.size()
7760 << " default_conflict_methods=" << default_conflict_methods_.size()
7761 << " overriding_default_conflict_methods="
7762 << overriding_default_conflict_methods_.size();
7763 }
7764
7765 ClassLinker* class_linker_;
7766 Handle<mirror::Class> klass_;
7767 size_t method_alignment_;
7768 size_t method_size_;
7769 Thread* const self_;
7770
7771 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7772 // the virtual methods array.
7773 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7774 // during cross compilation.
7775 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7776 ArenaStack stack_;
7777 ScopedArenaAllocator allocator_;
7778
7779 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7780 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7781 ScopedArenaVector<ArtMethod*> miranda_methods_;
7782 ScopedArenaVector<ArtMethod*> default_methods_;
7783 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7784
7785 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7786};
7787
7788ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7789 ArtMethod* interface_method,
7790 MethodNameAndSignatureComparator& interface_name_comparator,
7791 ArtMethod* vtable_impl) {
7792 ArtMethod* current_method = nullptr;
7793 switch (class_linker_->FindDefaultMethodImplementation(self_,
7794 interface_method,
7795 klass_,
7796 /*out*/&current_method)) {
7797 case DefaultMethodSearchResult::kDefaultConflict: {
7798 // Default method conflict.
7799 DCHECK(current_method == nullptr);
7800 ArtMethod* default_conflict_method = nullptr;
7801 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7802 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7803 default_conflict_method = vtable_impl;
7804 } else {
7805 // See if we already have a conflict method for this method.
7806 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7807 interface_name_comparator,
7808 default_conflict_methods_,
7809 overriding_default_conflict_methods_);
7810 if (LIKELY(preexisting_conflict != nullptr)) {
7811 // We already have another conflict we can reuse.
7812 default_conflict_method = preexisting_conflict;
7813 } else {
7814 // Note that we do this even if we are an interface since we need to create this and
7815 // cannot reuse another classes.
7816 // Create a new conflict method for this to use.
7817 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7818 new(default_conflict_method) ArtMethod(interface_method,
7819 class_linker_->GetImagePointerSize());
7820 if (vtable_impl == nullptr) {
7821 // Save the conflict method. We need to add it to the vtable.
7822 default_conflict_methods_.push_back(default_conflict_method);
7823 } else {
7824 // Save the conflict method but it is already in the vtable.
7825 overriding_default_conflict_methods_.push_back(default_conflict_method);
7826 }
7827 }
7828 }
7829 current_method = default_conflict_method;
7830 break;
7831 } // case kDefaultConflict
7832 case DefaultMethodSearchResult::kDefaultFound: {
7833 DCHECK(current_method != nullptr);
7834 // Found a default method.
7835 if (vtable_impl != nullptr &&
7836 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7837 // We found a default method but it was the same one we already have from our
7838 // superclass. Don't bother adding it to our vtable again.
7839 current_method = vtable_impl;
7840 } else if (LIKELY(FillTables())) {
7841 // Interfaces don't need to copy default methods since they don't have vtables.
7842 // Only record this default method if it is new to save space.
7843 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7844 // would make lookup for interface super much faster. (We would only need to scan
7845 // the iftable to find if there is a NSME or AME.)
7846 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7847 default_methods_,
7848 overriding_default_methods_);
7849 if (old == nullptr) {
7850 // We found a default method implementation and there were no conflicts.
7851 if (vtable_impl == nullptr) {
7852 // Save the default method. We need to add it to the vtable.
7853 default_methods_.push_back(current_method);
7854 } else {
7855 // Save the default method but it is already in the vtable.
7856 overriding_default_methods_.push_back(current_method);
7857 }
7858 } else {
7859 CHECK(old == current_method) << "Multiple default implementations selected!";
7860 }
7861 }
7862 break;
7863 } // case kDefaultFound
7864 case DefaultMethodSearchResult::kAbstractFound: {
7865 DCHECK(current_method == nullptr);
7866 // Abstract method masks all defaults.
7867 if (vtable_impl != nullptr &&
7868 vtable_impl->IsAbstract() &&
7869 !vtable_impl->IsDefaultConflicting()) {
7870 // We need to make this an abstract method but the version in the vtable already is so
7871 // don't do anything.
7872 current_method = vtable_impl;
7873 }
7874 break;
7875 } // case kAbstractFound
7876 }
7877 return current_method;
7878}
7879
7880ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7881 ArtMethod* interface_method,
7882 MethodNameAndSignatureComparator& interface_name_comparator) {
7883 // Find out if there is already a miranda method we can use.
7884 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7885 miranda_methods_);
7886 if (miranda_method == nullptr) {
7887 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7888 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7889 CHECK(miranda_method != nullptr);
7890 // Point the interface table at a phantom slot.
7891 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7892 miranda_methods_.push_back(miranda_method);
7893 }
7894 return miranda_method;
7895}
7896
7897void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7898 LogNewVirtuals();
7899
7900 const size_t old_method_count = klass_->NumMethods();
7901 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7902 DCHECK_NE(old_method_count, new_method_count);
7903
7904 // Attempt to realloc to save RAM if possible.
7905 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7906 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7907 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7908 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7909 // CopyFrom has internal read barriers.
7910 //
7911 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7912 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7913 method_size_,
7914 method_alignment_);
7915 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7916 method_size_,
7917 method_alignment_);
7918 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7919 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007920 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007921 self_, old_methods, old_methods_ptr_size, new_size));
7922 CHECK(methods != nullptr); // Native allocation failure aborts.
7923
7924 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7925 if (methods != old_methods) {
7926 // Maps from heap allocated miranda method to linear alloc miranda method.
7927 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7928 // Copy over the old methods.
7929 for (auto& m : klass_->GetMethods(pointer_size)) {
7930 move_table_.emplace(&m, &*out);
7931 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7932 // barriers when it copies.
7933 out->CopyFrom(&m, pointer_size);
7934 ++out;
7935 }
7936 }
7937 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7938 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7939 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007940 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7941 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007942 ArtMethod& new_method = *out;
7943 new_method.CopyFrom(mir_method, pointer_size);
7944 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7945 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7946 << "Miranda method should be abstract!";
7947 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007948 // Update the entry in the method array, as the array will be used for future lookups,
7949 // where thread suspension is allowed.
7950 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7951 // would not see them.
7952 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007953 ++out;
7954 }
7955 // We need to copy the default methods into our own method table since the runtime requires that
7956 // every method on a class's vtable be in that respective class's virtual method table.
7957 // NOTE This means that two classes might have the same implementation of a method from the same
7958 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7959 // default method found on a class with one found on the declaring interface directly and must
7960 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007961 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7962 &overriding_default_methods_}) {
7963 for (size_t i = 0; i < methods_vec->size(); ++i) {
7964 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007965 ArtMethod& new_method = *out;
7966 new_method.CopyFrom(def_method, pointer_size);
7967 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7968 // verified yet it shouldn't have methods that are skipping access checks.
7969 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7970 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007971 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007972 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7973 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7974 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7975 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007976 // Update the entry in the method array, as the array will be used for future lookups,
7977 // where thread suspension is allowed.
7978 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7979 // would not see them.
7980 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007981 ++out;
7982 }
7983 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007984 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7985 &overriding_default_conflict_methods_}) {
7986 for (size_t i = 0; i < methods_vec->size(); ++i) {
7987 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007988 ArtMethod& new_method = *out;
7989 new_method.CopyFrom(conf_method, pointer_size);
7990 // This is a type of default method (there are default method impls, just a conflict) so
7991 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7992 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7993 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007994 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7995 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007996 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007997 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007998 constexpr uint32_t kMaskFlags =
7999 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00008000 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
8001 DCHECK(new_method.IsDefaultConflicting());
8002 // The actual method might or might not be marked abstract since we just copied it from a
8003 // (possibly default) interface method. We need to set it entry point to be the bridge so
8004 // that the compiler will not invoke the implementation of whatever method we copied from.
8005 EnsureThrowsInvocationError(class_linker_, &new_method);
8006 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008007 // Update the entry in the method array, as the array will be used for future lookups,
8008 // where thread suspension is allowed.
8009 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
8010 // would not see them.
8011 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00008012 ++out;
8013 }
8014 }
8015 methods->SetSize(new_method_count);
8016 class_linker_->UpdateClassMethods(klass_.Get(), methods);
8017}
8018
8019ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
8020 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01008021 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008022 // Update the vtable to the new method structures. We can skip this for interfaces since they
8023 // do not have vtables.
8024 const size_t old_vtable_count = old_vtable->GetLength();
8025 const size_t new_vtable_count = old_vtable_count +
8026 miranda_methods_.size() +
8027 default_methods_.size() +
8028 default_conflict_methods_.size();
8029
Vladimir Marko3068d582019-05-28 16:39:29 +01008030 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
8031 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00008032 if (UNLIKELY(vtable == nullptr)) {
8033 self_->AssertPendingOOMException();
8034 return nullptr;
8035 }
8036
8037 size_t vtable_pos = old_vtable_count;
8038 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8039 // Update all the newly copied method's indexes so they denote their placement in the vtable.
8040 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
8041 default_conflict_methods_,
8042 miranda_methods_}) {
8043 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008044 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008045 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
8046 // fields are references into the dex file the method was defined in. Since the ArtMethod
8047 // does not store that information it uses declaring_class_->dex_cache_.
8048 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
8049 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
8050 ++vtable_pos;
8051 }
8052 }
8053 DCHECK_EQ(vtable_pos, new_vtable_count);
8054
8055 // Update old vtable methods. We use the default_translations map to figure out what each
8056 // vtable entry should be updated to, if they need to be at all.
8057 for (size_t i = 0; i < old_vtable_count; ++i) {
8058 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
8059 // Try and find what we need to change this method to.
8060 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008061 if (translation_it != default_translations.end()) {
8062 if (translation_it->second.IsInConflict()) {
8063 // Find which conflict method we are to use for this method.
8064 MethodNameAndSignatureComparator old_method_comparator(
8065 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8066 // We only need to look through overriding_default_conflict_methods since this is an
8067 // overridden method we are fixing up here.
8068 ArtMethod* new_conflict_method = FindSameNameAndSignature(
8069 old_method_comparator, overriding_default_conflict_methods_);
8070 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
8071 translated_method = new_conflict_method;
8072 } else if (translation_it->second.IsAbstract()) {
8073 // Find which miranda method we are to use for this method.
8074 MethodNameAndSignatureComparator old_method_comparator(
8075 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8076 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
8077 miranda_methods_);
8078 DCHECK(miranda_method != nullptr);
8079 translated_method = miranda_method;
8080 } else {
8081 // Normal default method (changed from an older default or abstract interface method).
8082 DCHECK(translation_it->second.IsTranslation());
8083 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008084 auto it = move_table_.find(translated_method);
8085 DCHECK(it != move_table_.end());
8086 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00008087 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008088 } else {
8089 auto it = move_table_.find(translated_method);
8090 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008091 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008092
8093 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008094 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008095 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008096 if (kIsDebugBuild) {
8097 auto* methods = klass_->GetMethodsPtr();
8098 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008099 reinterpret_cast<uintptr_t>(translated_method));
8100 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008101 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8102 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008103 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008104 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008105 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008106 }
8107 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008108 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008109 return vtable;
8110}
8111
8112void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8113 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8114 const size_t ifcount = klass_->GetIfTableCount();
8115 // Go fix up all the stale iftable pointers.
8116 for (size_t i = 0; i < ifcount; ++i) {
8117 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008118 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8119 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008120 DCHECK(m != nullptr) << klass_->PrettyClass();
8121 auto it = move_table_.find(m);
8122 if (it != move_table_.end()) {
8123 auto* new_m = it->second;
8124 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8125 method_array->SetElementPtrSize(j, new_m, pointer_size);
8126 }
8127 }
8128 }
8129}
8130
8131void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8132 // Fix up IMT next.
8133 for (size_t i = 0; i < ImTable::kSize; ++i) {
8134 auto it = move_table_.find(out_imt[i]);
8135 if (it != move_table_.end()) {
8136 out_imt[i] = it->second;
8137 }
8138 }
8139}
8140
Alex Light705ad492015-09-21 11:36:30 -07008141// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008142bool ClassLinker::LinkInterfaceMethods(
8143 Thread* self,
8144 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07008145 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008146 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008147 ArtMethod** out_imt) {
8148 StackHandleScope<3> hs(self);
8149 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008150
8151 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008152 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008153 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008154 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008155 const size_t ifcount = klass->GetIfTableCount();
8156
Vladimir Marko921094a2017-01-12 18:37:06 +00008157 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008158
8159 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8160 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008161 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008162 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008163 const bool extend_super_iftable = has_superclass;
8164 if (has_superclass && fill_tables) {
8165 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008166 unimplemented_method,
8167 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008168 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008169 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008170 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008171 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8172 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008173 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008174 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8175 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008176 }
8177 }
8178
Vladimir Marko921094a2017-01-12 18:37:06 +00008179 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8180
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008181 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008182 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008183 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8184 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8185 // they will already be null. This has the additional benefit that the declarer of a miranda
8186 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008187 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008188 --i;
Alex Light9139e002015-10-09 15:59:48 -07008189 DCHECK_LT(i, ifcount);
8190
Alex Light705ad492015-09-21 11:36:30 -07008191 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008192 if (num_methods > 0) {
8193 StackHandleScope<2> hs2(self);
8194 const bool is_super = i < super_ifcount;
8195 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008196 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8197 // conflict methods. Just set this as nullptr in those cases.
8198 Handle<mirror::PointerArray> method_array(fill_tables
8199 ? hs2.NewHandle(iftable->GetMethodArray(i))
8200 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008201
Alex Lighte64300b2015-12-15 15:02:47 -08008202 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008203 ScopedNullHandle<mirror::PointerArray> null_handle;
8204 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008205 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008206
Alex Light9139e002015-10-09 15:59:48 -07008207 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8208 // and confusing. Default methods should always look through all the superclasses
8209 // because they are the last choice of an implementation. We get around this by looking
8210 // at the super-classes iftable methods (copied into method_array previously) when we are
8211 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008212 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008213 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008214 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008215 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008216 using_virtuals = true;
8217 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
8218 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008219 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008220 // For a new interface, however, we need the whole vtable in case a new
8221 // interface method is implemented in the whole superclass.
8222 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008223 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008224 input_vtable_array = vtable;
8225 input_array_length = input_vtable_array->GetLength();
8226 }
Alex Lighte64300b2015-12-15 15:02:47 -08008227
Alex Lighteb7c1442015-08-31 13:17:42 -07008228 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008229 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008230 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008231 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008232 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008233 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008234 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008235 // For each method listed in the interface's method list, find the
8236 // matching method in our class's method list. We want to favor the
8237 // subclass over the superclass, which just requires walking
8238 // back from the end of the vtable. (This only matters if the
8239 // superclass defines a private method and this class redefines
8240 // it -- otherwise it would use the same vtable slot. In .dex files
8241 // those don't end up in the virtual method table, so it shouldn't
8242 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008243 //
8244 // To find defaults we need to do the same but also go over interfaces.
8245 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008246 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008247 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008248 ArtMethod* vtable_method = using_virtuals ?
8249 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008250 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8251 ArtMethod* vtable_method_for_name_comparison =
8252 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008253 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008254 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008255 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008256 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8257 // allocations.
8258 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008259 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008260 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008261 vtable_method->PrettyMethod().c_str(),
8262 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008263 return false;
Alex Light9139e002015-10-09 15:59:48 -07008264 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008265 // We might have a newer, better, default method for this, so we just skip it. If we
8266 // are still using this we will select it again when scanning for default methods. To
8267 // obviate the need to copy the method again we will make a note that we already found
8268 // a default here.
8269 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008270 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008271 break;
8272 } else {
8273 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008274 if (LIKELY(fill_tables)) {
8275 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8276 // Place method in imt if entry is empty, place conflict otherwise.
8277 SetIMTRef(unimplemented_method,
8278 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008279 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008280 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008281 /*out*/imt_ptr);
8282 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008283 break;
8284 }
8285 }
Alex Light9139e002015-10-09 15:59:48 -07008286 }
8287 // Continue on to the next method if we are done.
8288 if (LIKELY(found_impl)) {
8289 continue;
8290 } else if (LIKELY(super_interface)) {
8291 // Don't look for a default implementation when the super-method is implemented directly
8292 // by the class.
8293 //
8294 // See if we can use the superclasses method and skip searching everything else.
8295 // Note: !found_impl && super_interface
8296 CHECK(extend_super_iftable);
8297 // If this is a super_interface method it is possible we shouldn't override it because a
8298 // superclass could have implemented it directly. We get the method the superclass used
8299 // to implement this to know if we can override it with a default method. Doing this is
8300 // safe since we know that the super_iftable is filled in so we can simply pull it from
8301 // there. We don't bother if this is not a super-classes interface since in that case we
8302 // have scanned the entire vtable anyway and would have found it.
8303 // TODO This is rather dirty but it is faster than searching through the entire vtable
8304 // every time.
8305 ArtMethod* supers_method =
8306 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8307 DCHECK(supers_method != nullptr);
8308 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008309 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008310 // The method is not overridable by a default method (i.e. it is directly implemented
8311 // in some class). Therefore move onto the next interface method.
8312 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008313 } else {
8314 // If the super-classes method is override-able by a default method we need to keep
8315 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8316 // 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 -07008317 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8318 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8319 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008320 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008321 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8322 << " and not 'nullptr' or "
8323 << supers_method->PrettyMethod()
8324 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008325 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008326 }
8327 }
8328 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008329 ArtMethod* current_method = helper.FindMethod(interface_method,
8330 interface_name_comparator,
8331 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008332 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008333 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008334 // We could not find an implementation for this method and since it is a brand new
8335 // interface we searched the entire vtable (and all default methods) for an
8336 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008337 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8338 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008339 }
8340
8341 if (current_method != nullptr) {
8342 // We found a default method implementation. Record it in the iftable and IMT.
8343 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8344 SetIMTRef(unimplemented_method,
8345 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008346 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008347 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008348 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008349 }
8350 }
Alex Light705ad492015-09-21 11:36:30 -07008351 } // For each method in interface end.
8352 } // if (num_methods > 0)
8353 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008354 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008355 if (helper.HasNewVirtuals()) {
8356 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8357 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8358 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8359
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008360 // 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 -07008361 // suspension assert.
8362 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008363
Alex Light705ad492015-09-21 11:36:30 -07008364 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008365 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008366 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008367 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008368 return false;
8369 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008370 helper.UpdateIfTable(iftable);
8371 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008372 }
Alex Light705ad492015-09-21 11:36:30 -07008373
Vladimir Marko921094a2017-01-12 18:37:06 +00008374 helper.CheckNoStaleMethodsInDexCache();
8375 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008376 } else {
8377 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008378 }
Alex Light705ad492015-09-21 11:36:30 -07008379 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008380 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008381 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008382 return true;
8383}
8384
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008385bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008386 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008387 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008388}
8389
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008390bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008391 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008392 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008393}
8394
Brian Carlstromdbc05252011-09-09 01:59:59 -07008395struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008396 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008397 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008398 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008399 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008400 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008401 // 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 -07008402 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8403 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008404 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008405 if (type1 == Primitive::kPrimNot) {
8406 // Reference always goes first.
8407 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008408 }
Vladimir Markod5777482014-11-12 17:02:02 +00008409 if (type2 == Primitive::kPrimNot) {
8410 // Reference always goes first.
8411 return false;
8412 }
8413 size_t size1 = Primitive::ComponentSize(type1);
8414 size_t size2 = Primitive::ComponentSize(type2);
8415 if (size1 != size2) {
8416 // Larger primitive types go first.
8417 return size1 > size2;
8418 }
8419 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8420 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008421 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008422 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8423 // by name and for equal names by type id index.
8424 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8425 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008426 }
8427};
8428
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008429bool ClassLinker::LinkFields(Thread* self,
8430 Handle<mirror::Class> klass,
8431 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008432 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008433 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008434 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008435 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8436 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008437
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008438 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008439 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008440 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008441 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008442 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008443 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008444 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008445 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008446 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008447 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008448 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008449 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008450
David Sehr709b0702016-10-13 09:12:37 -07008451 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008452
Brian Carlstromdbc05252011-09-09 01:59:59 -07008453 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008454 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008455 //
8456 // The overall sort order order is:
8457 // 1) All object reference fields, sorted alphabetically.
8458 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8459 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8460 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8461 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8462 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8463 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8464 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8465 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8466 //
8467 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8468 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008469 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008470 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008471 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008472 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008473 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008474 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008475 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8476 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008477
Fred Shih381e4ca2014-08-25 17:24:27 -07008478 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008479 size_t current_field = 0;
8480 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008481 FieldGaps gaps;
8482
Brian Carlstromdbc05252011-09-09 01:59:59 -07008483 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008484 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008485 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008486 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008487 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008488 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008489 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008490 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8491 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008492 MemberOffset old_offset = field_offset;
8493 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8494 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8495 }
Roland Levillain14d90572015-07-16 10:52:26 +01008496 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008497 grouped_and_sorted_fields.pop_front();
8498 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008499 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008500 field_offset = MemberOffset(field_offset.Uint32Value() +
8501 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008502 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008503 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8504 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008505 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8506 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8507 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8508 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008509 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8510 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008511 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008512
Elliott Hughesadb460d2011-10-05 17:02:34 -07008513 // 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 -07008514 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008515 // We know there are no non-reference fields in the Reference classes, and we know
8516 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008517 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008518 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008519 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008520 --num_reference_fields;
8521 }
8522
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008523 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008524 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008525 if (is_static) {
8526 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008527 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008528 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008529 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008530 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008531 if (num_reference_fields == 0 || super_class == nullptr) {
8532 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008533 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008534 if (super_class == nullptr ||
8535 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8536 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008537 }
8538 }
8539 if (kIsDebugBuild) {
8540 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8541 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008542 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008543 while (cur_super != nullptr) {
8544 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8545 cur_super = cur_super->GetSuperClass();
8546 }
8547 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008548 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008549 } else {
8550 // Check that there is at least num_reference_fields other than Object.class.
8551 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008552 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008553 }
8554 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008555 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008556 std::string temp;
8557 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8558 size_t previous_size = klass->GetObjectSize();
8559 if (previous_size != 0) {
8560 // Make sure that we didn't originally have an incorrect size.
8561 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008562 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008563 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008564 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008565 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008566
8567 if (kIsDebugBuild) {
8568 // Make sure that the fields array is ordered by name but all reference
8569 // offsets are at the beginning as far as alignment allows.
8570 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008571 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008572 : klass->GetFirstReferenceInstanceFieldOffset();
8573 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8574 num_reference_fields *
8575 sizeof(mirror::HeapReference<mirror::Object>));
8576 MemberOffset current_ref_offset = start_ref_offset;
8577 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008578 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008579 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008580 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8581 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008582 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008583 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008584 // NOTE: The field names can be the same. This is not possible in the Java language
8585 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008586 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008587 }
8588 Primitive::Type type = field->GetTypeAsPrimitiveType();
8589 bool is_primitive = type != Primitive::kPrimNot;
8590 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8591 strcmp("referent", field->GetName()) == 0) {
8592 is_primitive = true; // We lied above, so we have to expect a lie here.
8593 }
8594 MemberOffset offset = field->GetOffsetDuringLinking();
8595 if (is_primitive) {
8596 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8597 // Shuffled before references.
8598 size_t type_size = Primitive::ComponentSize(type);
8599 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8600 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8601 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8602 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8603 }
8604 } else {
8605 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8606 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8607 sizeof(mirror::HeapReference<mirror::Object>));
8608 }
8609 }
8610 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8611 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008612 return true;
8613}
8614
Vladimir Marko76649e82014-11-10 18:32:59 +00008615// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008616void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008617 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008618 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008619 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008620 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008621 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008622 // Compute reference offsets unless our superclass overflowed.
8623 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8624 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008625 if (num_reference_fields != 0u) {
8626 // All of the fields that contain object references are guaranteed be grouped in memory
8627 // starting at an appropriately aligned address after super class object data.
8628 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8629 sizeof(mirror::HeapReference<mirror::Object>));
8630 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008631 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008632 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008633 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008634 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008635 reference_offsets |= (0xffffffffu << start_bit) &
8636 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008637 }
8638 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008639 }
8640 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008641 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008642}
8643
Vladimir Marko18090d12018-06-01 16:53:12 +01008644ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8645 ObjPtr<mirror::DexCache> dex_cache) {
8646 StackHandleScope<1> hs(Thread::Current());
8647 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8648 return DoResolveString(string_idx, h_dex_cache);
8649}
8650
8651ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8652 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008653 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008654 uint32_t utf16_length;
8655 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008656 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008657 if (string != nullptr) {
8658 dex_cache->SetResolvedString(string_idx, string);
8659 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008660 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008661}
8662
Vladimir Marko18090d12018-06-01 16:53:12 +01008663ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8664 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008665 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008666 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008667 uint32_t utf16_length;
8668 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008669 ObjPtr<mirror::String> string =
8670 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008671 if (string != nullptr) {
8672 dex_cache->SetResolvedString(string_idx, string);
8673 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008674 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008675}
8676
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008677ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008678 ObjPtr<mirror::Class> referrer) {
8679 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8680}
8681
8682ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008683 ObjPtr<mirror::DexCache> dex_cache,
8684 ObjPtr<mirror::ClassLoader> class_loader) {
8685 const DexFile& dex_file = *dex_cache->GetDexFile();
8686 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8687 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8688 ObjPtr<mirror::Class> type = nullptr;
8689 if (descriptor[1] == '\0') {
8690 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8691 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008692 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008693 } else {
8694 Thread* const self = Thread::Current();
8695 DCHECK(self != nullptr);
8696 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8697 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008698 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008699 }
8700 if (type != nullptr) {
8701 if (type->IsResolved()) {
8702 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008703 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008704 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008705 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008706 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008707 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008708}
8709
Andreas Gampeb0625e02019-05-01 12:43:31 -07008710template <typename RefType>
8711ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008712 StackHandleScope<2> hs(Thread::Current());
8713 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8714 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8715 return DoResolveType(type_idx, dex_cache, class_loader);
8716}
8717
Andreas Gampe4835d212018-11-21 14:55:10 -08008718// Instantiate the above.
8719template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8720 ArtField* referrer);
8721template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8722 ArtMethod* referrer);
8723template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8724 ObjPtr<mirror::Class> referrer);
8725
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008726ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008727 Handle<mirror::DexCache> dex_cache,
8728 Handle<mirror::ClassLoader> class_loader) {
8729 Thread* self = Thread::Current();
8730 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8731 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8732 if (resolved != nullptr) {
8733 // TODO: we used to throw here if resolved's class loader was not the
8734 // boot class loader. This was to permit different classes with the
8735 // same name to be loaded simultaneously by different loaders
8736 dex_cache->SetResolvedType(type_idx, resolved);
8737 } else {
8738 CHECK(self->IsExceptionPending())
8739 << "Expected pending exception for failed resolution of: " << descriptor;
8740 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8741 StackHandleScope<1> hs(self);
8742 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008743 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008744 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8745 self->ClearException();
8746 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8747 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008748 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008749 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008750 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008751 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008752 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008753}
8754
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008755ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8756 ObjPtr<mirror::DexCache> dex_cache,
8757 ObjPtr<mirror::ClassLoader> class_loader,
8758 uint32_t method_idx) {
8759 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8760 // functions can optimize the search if the dex_cache is the same as the DexCache
8761 // of the class, with fall-back to name and signature search otherwise.
8762 ArtMethod* resolved = nullptr;
8763 if (klass->IsInterface()) {
8764 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8765 } else {
8766 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8767 }
8768 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008769 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008770 hiddenapi::ShouldDenyAccessToMember(resolved,
8771 hiddenapi::AccessContext(class_loader, dex_cache),
8772 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008773 resolved = nullptr;
8774 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008775 if (resolved != nullptr) {
8776 // In case of jmvti, the dex file gets verified before being registered, so first
8777 // check if it's registered before checking class tables.
8778 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008779 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8780 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008781 << "DexFile referrer: " << dex_file.GetLocation()
8782 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8783 // Be a good citizen and update the dex cache to speed subsequent calls.
8784 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008785 // Disable the following invariant check as the verifier breaks it. b/73760543
8786 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8787 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8788 // << "Method: " << resolved->PrettyMethod() << ", "
8789 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8790 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008791 }
8792 return resolved;
8793}
8794
David Brazdil4525e0b2018-04-05 16:57:32 +01008795// Returns true if `method` is either null or hidden.
8796// Does not print any warnings if it is hidden.
8797static bool CheckNoSuchMethod(ArtMethod* method,
8798 ObjPtr<mirror::DexCache> dex_cache,
8799 ObjPtr<mirror::ClassLoader> class_loader)
8800 REQUIRES_SHARED(Locks::mutator_lock_) {
8801 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008802 hiddenapi::ShouldDenyAccessToMember(method,
8803 hiddenapi::AccessContext(class_loader, dex_cache),
8804 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008805}
8806
8807ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8808 ObjPtr<mirror::DexCache> dex_cache,
8809 ObjPtr<mirror::ClassLoader> class_loader,
8810 uint32_t method_idx) {
8811 if (klass->IsInterface()) {
8812 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8813 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8814 } else {
8815 // If there was an interface method with the same signature, we would have
8816 // found it in the "copied" methods. Only DCHECK that the interface method
8817 // really does not exist.
8818 if (kIsDebugBuild) {
8819 ArtMethod* method =
8820 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8821 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8822 }
8823 return nullptr;
8824 }
8825}
8826
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008827template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008828ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008829 Handle<mirror::DexCache> dex_cache,
8830 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008831 ArtMethod* referrer,
8832 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008833 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008834 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008835 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008836 PointerSize pointer_size = image_pointer_size_;
8837 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008838 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008839 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8840 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008841 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8842 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008843 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008844 return resolved;
8845 }
Vladimir Marko89011192017-12-11 13:45:05 +00008846 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008847 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008848 ObjPtr<mirror::Class> klass = nullptr;
8849 if (valid_dex_cache_method) {
8850 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8851 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008852 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008853 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008854 // We normaly should not end up here. However the verifier currently doesn't guarantee
8855 // the invariant of having the klass in the class table. b/73760543
8856 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008857 }
Vladimir Markoba118822017-06-12 15:41:56 +01008858 } else {
8859 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008860 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008861 if (klass == nullptr) {
8862 DCHECK(Thread::Current()->IsExceptionPending());
8863 return nullptr;
8864 }
8865 }
8866
8867 // Check if the invoke type matches the class type.
8868 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008869 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008870 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008871 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008872 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008873 }
Vladimir Markoba118822017-06-12 15:41:56 +01008874
8875 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008876 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008877 }
Vladimir Markoba118822017-06-12 15:41:56 +01008878
8879 // Note: We can check for IllegalAccessError only if we have a referrer.
8880 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8881 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8882 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8883 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8884 resolved,
8885 dex_cache.Get(),
8886 method_idx,
8887 type)) {
8888 DCHECK(Thread::Current()->IsExceptionPending());
8889 return nullptr;
8890 }
8891 }
8892
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008893 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008894 if (LIKELY(resolved != nullptr) &&
8895 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8896 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008897 return resolved;
8898 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008899 // If we had a method, or if we can find one with another lookup type,
8900 // it's an incompatible-class-change error.
8901 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008902 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008903 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008904 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008905 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008906 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008907 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008908 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8909 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008910 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008911 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008912 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008913 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008914 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008915}
8916
Vladimir Marko89011192017-12-11 13:45:05 +00008917ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008918 Handle<mirror::DexCache> dex_cache,
8919 Handle<mirror::ClassLoader> class_loader) {
8920 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008921 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008922 if (resolved != nullptr) {
8923 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008924 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8925 return resolved;
8926 }
8927 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008928 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008929 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008930 if (klass == nullptr) {
8931 Thread::Current()->AssertPendingException();
8932 return nullptr;
8933 }
8934 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008935 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8936 } else {
8937 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008938 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008939 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008940 hiddenapi::ShouldDenyAccessToMember(
8941 resolved,
8942 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8943 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008944 resolved = nullptr;
8945 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008946 return resolved;
8947}
8948
Vladimir Markof44d36c2017-03-14 14:18:46 +00008949ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8950 ObjPtr<mirror::DexCache> dex_cache,
8951 ObjPtr<mirror::ClassLoader> class_loader,
8952 bool is_static) {
8953 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008954 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008955 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8956 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008957 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008958 }
8959 if (klass == nullptr) {
8960 // The class has not been resolved yet, so the field is also unresolved.
8961 return nullptr;
8962 }
8963 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008964
David Brazdil1ab0fa82018-05-04 11:28:03 +01008965 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008966}
8967
Vladimir Markoe11dd502017-12-08 14:09:45 +00008968ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008969 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008970 Handle<mirror::ClassLoader> class_loader,
8971 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008972 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008973 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008974 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008975 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008976 return resolved;
8977 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008978 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008979 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008980 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008981 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008982 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008983 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008984 }
8985
David Brazdil1ab0fa82018-05-04 11:28:03 +01008986 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008987 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008988 const char* name = dex_file.GetFieldName(field_id);
8989 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008990 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008991 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008992 return resolved;
8993}
8994
Vladimir Markoe11dd502017-12-08 14:09:45 +00008995ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008996 Handle<mirror::DexCache> dex_cache,
8997 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008998 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008999 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009000 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009001 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009002 return resolved;
9003 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009004 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009005 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009006 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009007 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009008 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009009 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009010 }
9011
David Brazdil1ab0fa82018-05-04 11:28:03 +01009012 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9013 if (resolved == nullptr) {
9014 const char* name = dex_file.GetFieldName(field_id);
9015 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009016 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009017 }
9018 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009019}
9020
David Brazdil1ab0fa82018-05-04 11:28:03 +01009021ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9022 ObjPtr<mirror::DexCache> dex_cache,
9023 ObjPtr<mirror::ClassLoader> class_loader,
9024 uint32_t field_idx,
9025 bool is_static) {
9026 ArtField* resolved = nullptr;
9027 Thread* self = is_static ? Thread::Current() : nullptr;
9028 const DexFile& dex_file = *dex_cache->GetDexFile();
9029
9030 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
9031 : klass->FindInstanceField(dex_cache, field_idx);
9032
9033 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009034 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009035 const char* name = dex_file.GetFieldName(field_id);
9036 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9037 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
9038 : klass->FindInstanceField(name, type);
9039 }
9040
9041 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009042 hiddenapi::ShouldDenyAccessToMember(resolved,
9043 hiddenapi::AccessContext(class_loader, dex_cache),
9044 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009045 resolved = nullptr;
9046 }
9047
9048 if (resolved != nullptr) {
9049 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9050 }
9051
9052 return resolved;
9053}
9054
9055ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9056 ObjPtr<mirror::DexCache> dex_cache,
9057 ObjPtr<mirror::ClassLoader> class_loader,
9058 uint32_t field_idx) {
9059 ArtField* resolved = nullptr;
9060 Thread* self = Thread::Current();
9061 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009062 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009063
9064 const char* name = dex_file.GetFieldName(field_id);
9065 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9066 resolved = mirror::Class::FindField(self, klass, name, type);
9067
9068 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009069 hiddenapi::ShouldDenyAccessToMember(resolved,
9070 hiddenapi::AccessContext(class_loader, dex_cache),
9071 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009072 resolved = nullptr;
9073 }
9074
9075 if (resolved != nullptr) {
9076 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9077 }
9078
9079 return resolved;
9080}
9081
Vladimir Markoaf940202017-12-08 15:01:18 +00009082ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9083 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009084 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009085 Handle<mirror::DexCache> dex_cache,
9086 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009087 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009088 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009089
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009090 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009091 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009092 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009093 }
9094
Narayan Kamath25352fc2016-08-03 12:46:58 +01009095 StackHandleScope<4> hs(self);
9096
9097 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009098 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009099 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009100 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009101 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009102 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009103 DCHECK(self->IsExceptionPending());
9104 return nullptr;
9105 }
9106
9107 // Then resolve the argument types.
9108 //
9109 // TODO: Is there a better way to figure out the number of method arguments
9110 // other than by looking at the shorty ?
9111 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9112
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009113 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009114 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9115 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009116 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009117 DCHECK(self->IsExceptionPending());
9118 return nullptr;
9119 }
9120
9121 DexFileParameterIterator it(dex_file, proto_id);
9122 int32_t i = 0;
9123 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9124 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009125 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009126 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009127 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009128 DCHECK(self->IsExceptionPending());
9129 return nullptr;
9130 }
9131
9132 method_params->Set(i++, param_class.Get());
9133 }
9134
9135 DCHECK(!it.HasNext());
9136
9137 Handle<mirror::MethodType> type = hs.NewHandle(
9138 mirror::MethodType::Create(self, return_type, method_params));
9139 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9140
9141 return type.Get();
9142}
9143
Vladimir Markoaf940202017-12-08 15:01:18 +00009144ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009145 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009146 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009147 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009148 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9149 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009150 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009151}
9152
Vladimir Marko5aead702019-03-27 11:00:36 +00009153ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009154 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009155 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009156 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009157 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009158 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9159 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009160 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009161 bool is_static;
9162 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009163 switch (handle_type) {
9164 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009165 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009166 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009167 is_static = true;
9168 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009169 break;
9170 }
9171 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009172 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009173 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009174 is_static = true;
9175 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009176 break;
9177 }
9178 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009179 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009180 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009181 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009182 num_params = 2;
9183 break;
9184 }
9185 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009186 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009187 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009188 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009189 num_params = 1;
9190 break;
9191 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009192 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009193 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009194 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009195 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009196 case DexFile::MethodHandleType::kInvokeInterface:
9197 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009198 }
9199
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009200 ArtField* target_field =
9201 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9202 if (LIKELY(target_field != nullptr)) {
9203 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9204 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9205 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9206 ThrowIllegalAccessErrorField(referring_class, target_field);
9207 return nullptr;
9208 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009209 if (UNLIKELY(is_put && target_field->IsFinal())) {
9210 ThrowIllegalAccessErrorField(referring_class, target_field);
9211 return nullptr;
9212 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009213 } else {
9214 DCHECK(Thread::Current()->IsExceptionPending());
9215 return nullptr;
9216 }
9217
9218 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009219 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009220 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9221 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009222 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009223 DCHECK(self->IsExceptionPending());
9224 return nullptr;
9225 }
9226
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009227 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009228 Handle<mirror::Class> return_type;
9229 switch (handle_type) {
9230 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009231 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009232 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009233 break;
9234 }
9235 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009236 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009237 break;
9238 }
9239 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009240 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009241 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009242 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009243 break;
9244 }
9245 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009246 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009247 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009248 break;
9249 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009250 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009251 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009252 case DexFile::MethodHandleType::kInvokeConstructor:
9253 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009254 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009255 UNREACHABLE();
9256 }
9257
9258 for (int32_t i = 0; i < num_params; ++i) {
9259 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9260 DCHECK(self->IsExceptionPending());
9261 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009262 }
9263 }
9264
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009265 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009266 DCHECK(self->IsExceptionPending());
9267 return nullptr;
9268 }
9269
9270 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009271 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9272 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009273 DCHECK(self->IsExceptionPending());
9274 return nullptr;
9275 }
Orion Hodson631827d2017-04-10 14:53:47 +01009276
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009277 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9278 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9279}
9280
Vladimir Marko5aead702019-03-27 11:00:36 +00009281ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009282 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009283 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009284 ArtMethod* referrer) {
9285 DexFile::MethodHandleType handle_type =
9286 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9287 mirror::MethodHandle::Kind kind;
9288 uint32_t receiver_count = 0;
9289 ArtMethod* target_method = nullptr;
9290 switch (handle_type) {
9291 case DexFile::MethodHandleType::kStaticPut:
9292 case DexFile::MethodHandleType::kStaticGet:
9293 case DexFile::MethodHandleType::kInstancePut:
9294 case DexFile::MethodHandleType::kInstanceGet:
9295 UNREACHABLE();
9296 case DexFile::MethodHandleType::kInvokeStatic: {
9297 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9298 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009299 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9300 method_handle.field_or_method_idx_,
9301 referrer,
9302 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009303 break;
9304 }
9305 case DexFile::MethodHandleType::kInvokeInstance: {
9306 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9307 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009308 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9309 method_handle.field_or_method_idx_,
9310 referrer,
9311 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009312 break;
9313 }
9314 case DexFile::MethodHandleType::kInvokeConstructor: {
9315 // Constructors are currently implemented as a transform. They
9316 // are special cased later in this method.
9317 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9318 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009319 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9320 method_handle.field_or_method_idx_,
9321 referrer,
9322 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009323 break;
9324 }
9325 case DexFile::MethodHandleType::kInvokeDirect: {
9326 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9327 receiver_count = 1;
9328 StackHandleScope<2> hs(self);
9329 // A constant method handle with type kInvokeDirect can refer to
9330 // a method that is private or to a method in a super class. To
9331 // disambiguate the two options, we resolve the method ignoring
9332 // the invocation type to determine if the method is private. We
9333 // then resolve again specifying the intended invocation type to
9334 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009335 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009336 hs.NewHandle(referrer->GetDexCache()),
9337 hs.NewHandle(referrer->GetClassLoader()));
9338 if (UNLIKELY(target_method == nullptr)) {
9339 break;
9340 }
9341
9342 if (target_method->IsPrivate()) {
9343 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009344 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9345 method_handle.field_or_method_idx_,
9346 referrer,
9347 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009348 } else {
9349 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009350 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9351 method_handle.field_or_method_idx_,
9352 referrer,
9353 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009354 if (UNLIKELY(target_method == nullptr)) {
9355 break;
9356 }
9357 // Find the method specified in the parent in referring class
9358 // so invoke-super invokes the method in the parent of the
9359 // referrer.
9360 target_method =
9361 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9362 kRuntimePointerSize);
9363 }
9364 break;
9365 }
9366 case DexFile::MethodHandleType::kInvokeInterface: {
9367 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9368 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009369 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9370 method_handle.field_or_method_idx_,
9371 referrer,
9372 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009373 break;
9374 }
Orion Hodson631827d2017-04-10 14:53:47 +01009375 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009376
9377 if (UNLIKELY(target_method == nullptr)) {
9378 DCHECK(Thread::Current()->IsExceptionPending());
9379 return nullptr;
9380 }
9381
9382 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9383 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9384 uint32_t access_flags = target_method->GetAccessFlags();
9385 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9386 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9387 return nullptr;
9388 }
9389
9390 // Calculate the number of parameters from the method shorty. We add the
9391 // receiver count (0 or 1) and deduct one for the return value.
9392 uint32_t shorty_length;
9393 target_method->GetShorty(&shorty_length);
9394 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9395
Orion Hodsonecd58562018-09-24 11:27:33 +01009396 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009397 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009398 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9399 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9400 if (method_params.Get() == nullptr) {
9401 DCHECK(self->IsExceptionPending());
9402 return nullptr;
9403 }
9404
Orion Hodsonecd58562018-09-24 11:27:33 +01009405 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009406 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009407 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009408 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009409 // Insert receiver. Use the class identified in the method handle rather than the declaring
9410 // class of the resolved method which may be super class or default interface method
9411 // (b/115964401).
9412 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9413 // receiver_class should have been resolved when resolving the target method.
9414 DCHECK(receiver_class != nullptr);
9415 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009416 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009417
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009418 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009419 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009420 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009421 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009422 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009423 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009424 if (nullptr == klass) {
9425 DCHECK(self->IsExceptionPending());
9426 return nullptr;
9427 }
9428 method_params->Set(index++, klass);
9429 it.Next();
9430 }
9431
Orion Hodsonecd58562018-09-24 11:27:33 +01009432 Handle<mirror::Class> return_type =
9433 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009434 if (UNLIKELY(return_type.IsNull())) {
9435 DCHECK(self->IsExceptionPending());
9436 return nullptr;
9437 }
9438
9439 Handle<mirror::MethodType>
9440 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9441 if (UNLIKELY(method_type.IsNull())) {
9442 DCHECK(self->IsExceptionPending());
9443 return nullptr;
9444 }
9445
9446 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9447 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9448 Handle<mirror::MethodHandlesLookup> lookup =
9449 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9450 return lookup->FindConstructor(self, constructor_class, method_type);
9451 }
9452
9453 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9454 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9455}
9456
Vladimir Markoaf940202017-12-08 15:01:18 +00009457ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9458 uint32_t method_handle_idx,
9459 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009460 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009461 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009462 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009463 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9464 case DexFile::MethodHandleType::kStaticPut:
9465 case DexFile::MethodHandleType::kStaticGet:
9466 case DexFile::MethodHandleType::kInstancePut:
9467 case DexFile::MethodHandleType::kInstanceGet:
9468 return ResolveMethodHandleForField(self, method_handle, referrer);
9469 case DexFile::MethodHandleType::kInvokeStatic:
9470 case DexFile::MethodHandleType::kInvokeInstance:
9471 case DexFile::MethodHandleType::kInvokeConstructor:
9472 case DexFile::MethodHandleType::kInvokeDirect:
9473 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009474 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009475 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009476}
9477
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009478bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9479 return (entry_point == GetQuickResolutionStub()) ||
9480 (quick_resolution_trampoline_ == entry_point);
9481}
9482
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009483bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9484 return (entry_point == GetQuickToInterpreterBridge()) ||
9485 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9486}
9487
9488bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9489 return (entry_point == GetQuickGenericJniStub()) ||
9490 (quick_generic_jni_trampoline_ == entry_point);
9491}
9492
David Sehra49e0532017-08-25 08:05:29 -07009493bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9494 return entry_point == GetJniDlsymLookupStub();
9495}
9496
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009497const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9498 return GetQuickGenericJniStub();
9499}
9500
Mathieu Chartiere401d142015-04-22 13:56:20 -07009501void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009502 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009503 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9504 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009505 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009506 }
9507}
9508
Alex Lightdb01a092017-04-03 15:39:55 -07009509void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9510 DCHECK(method->IsObsolete());
9511 // We cannot mess with the entrypoints of native methods because they are used to determine how
9512 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9513 if (!method->IsNative()) {
9514 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9515 }
9516}
9517
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009518void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009519 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009520 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009521 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9522 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009523 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9524 os << "Dumping registered class loaders\n";
9525 size_t class_loader_index = 0;
9526 for (const ClassLoaderData& class_loader : class_loaders_) {
9527 ObjPtr<mirror::ClassLoader> loader =
9528 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9529 if (loader != nullptr) {
9530 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9531 bool saw_one_dex_file = false;
9532 for (const DexCacheData& dex_cache : dex_caches_) {
9533 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9534 if (saw_one_dex_file) {
9535 os << ":";
9536 }
9537 saw_one_dex_file = true;
9538 os << dex_cache.dex_file->GetLocation();
9539 }
9540 }
9541 os << "]";
9542 bool found_parent = false;
9543 if (loader->GetParent() != nullptr) {
9544 size_t parent_index = 0;
9545 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9546 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9547 soa.Self()->DecodeJObject(class_loader2.weak_root));
9548 if (loader2 == loader->GetParent()) {
9549 os << ", parent #" << parent_index;
9550 found_parent = true;
9551 break;
9552 }
9553 parent_index++;
9554 }
9555 if (!found_parent) {
9556 os << ", unregistered parent of type "
9557 << loader->GetParent()->GetClass()->PrettyDescriptor();
9558 }
9559 } else {
9560 os << ", no parent";
9561 }
9562 os << "\n";
9563 }
9564 }
9565 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009566 Runtime* runtime = Runtime::Current();
9567 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9568 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009569}
9570
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009571class CountClassesVisitor : public ClassLoaderVisitor {
9572 public:
9573 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9574
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009575 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009576 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009577 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009578 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009579 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9580 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009581 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009582 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009583
9584 size_t num_zygote_classes;
9585 size_t num_non_zygote_classes;
9586};
9587
9588size_t ClassLinker::NumZygoteClasses() const {
9589 CountClassesVisitor visitor;
9590 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009591 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009592}
9593
9594size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009595 CountClassesVisitor visitor;
9596 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009597 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009598}
9599
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009600size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009601 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009602 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009603 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009604}
9605
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009606pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009607 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009608}
9609
9610pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009611 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009612}
9613
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009614void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009615 DCHECK(!init_done_);
9616
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009617 DCHECK(klass != nullptr);
9618 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009619
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009620 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009621 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009622 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9623 int32_t index = static_cast<int32_t>(class_root);
9624 DCHECK(class_roots->Get(index) == nullptr);
9625 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009626}
9627
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009628ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9629 Thread* self,
9630 const std::vector<const DexFile*>& dex_files,
9631 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009632 Handle<mirror::ClassLoader> parent_loader,
9633 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009634
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009635 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009636
Mathieu Chartierc7853442015-03-27 14:35:38 -07009637 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009638 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009639
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009640 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009641 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009642 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009643 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009644 mirror::ObjectArray<mirror::Object>::Alloc(self,
9645 dex_elements_class.Get(),
9646 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009647 Handle<mirror::Class> h_dex_element_class =
9648 hs.NewHandle(dex_elements_class->GetComponentType());
9649
Mathieu Chartierc7853442015-03-27 14:35:38 -07009650 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009651 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009652 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009653
Andreas Gampe08883de2016-11-08 13:20:52 -08009654 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009655 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009656
Andreas Gampe08883de2016-11-08 13:20:52 -08009657 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009658 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009659
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009660 // Fill the elements array.
9661 int32_t index = 0;
9662 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009663 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009664
Calin Juravle7865ac72017-06-28 11:03:12 -07009665 // CreateWellKnownClassLoader is only used by gtests and compiler.
9666 // 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 -07009667 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9668 self,
9669 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009670 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009671 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009672
Mathieu Chartier3738e982017-05-12 16:07:28 -07009673 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9674 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009675 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009676 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009677 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009678 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009679
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009680 Handle<mirror::String> h_file_name = hs2.NewHandle(
9681 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009682 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009683 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9684
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009685 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009686 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009687 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009688
9689 h_dex_elements->Set(index, h_element.Get());
9690 index++;
9691 }
9692 DCHECK_EQ(index, h_dex_elements->GetLength());
9693
9694 // Create DexPathList.
9695 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009696 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009697 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009698 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009699 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009700 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9701 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9702 // elements.
9703 {
9704 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9705 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9706 DCHECK(native_lib_dirs != nullptr);
9707 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9708 DCHECK(list_class != nullptr);
9709 {
9710 StackHandleScope<1> h_list_scope(self);
9711 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9712 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9713 DCHECK(list_init);
9714 list_class = h_list_class.Get();
9715 }
9716 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9717 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9718 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9719 // normally never null), as long as one does not try to add elements, this will still
9720 // work.
9721 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9722 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009723
Calin Juravle7865ac72017-06-28 11:03:12 -07009724 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009725 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9726 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009727 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009728 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009729 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009730 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009731 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009732 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009733
9734 // Make a pretend boot-classpath.
9735 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009736 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009737 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009738 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009739 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009740 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009741 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009742 if (parent_loader.Get() == nullptr) {
9743 ScopedObjectAccessUnchecked soa(self);
9744 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9745 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9746 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9747 } else {
9748 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9749 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009750
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009751 ArtField* shared_libraries_field =
9752 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9753 DCHECK(shared_libraries_field != nullptr);
9754 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9755
9756 return h_class_loader.Get();
9757}
9758
9759jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9760 const std::vector<const DexFile*>& dex_files,
9761 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009762 jobject parent_loader,
9763 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009764 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9765 WellKnownClasses::dalvik_system_PathClassLoader) ||
9766 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009767 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9768 self->GetJniEnv()->IsSameObject(loader_class,
9769 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009770
9771 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9772 // We could move the jobject to the callers, but all call-sites do this...
9773 ScopedObjectAccessUnchecked soa(self);
9774
9775 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009776 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009777
9778 Handle<mirror::Class> h_loader_class =
9779 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009780 Handle<mirror::ClassLoader> h_parent =
9781 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9782 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9783 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009784
9785 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9786 self,
9787 dex_files,
9788 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009789 h_parent,
9790 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009791
9792 // Make it a global ref and return.
9793 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009794 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009795 return soa.Env()->NewGlobalRef(local_ref.get());
9796}
9797
Calin Juravle7865ac72017-06-28 11:03:12 -07009798jobject ClassLinker::CreatePathClassLoader(Thread* self,
9799 const std::vector<const DexFile*>& dex_files) {
9800 return CreateWellKnownClassLoader(self,
9801 dex_files,
9802 WellKnownClasses::dalvik_system_PathClassLoader,
9803 nullptr);
9804}
9805
Andreas Gampe8ac75952015-06-02 21:01:45 -07009806void ClassLinker::DropFindArrayClassCache() {
9807 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9808 find_array_class_cache_next_victim_ = 0;
9809}
9810
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009811void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009812 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009813 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009814 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009815 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9816 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009817 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009818 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009819 }
9820 }
9821}
9822
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009823void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9824 for (const ClassLoaderData& data : class_loaders_) {
9825 LinearAlloc* alloc = data.allocator;
9826 if (alloc != nullptr && !visitor->Visit(alloc)) {
9827 break;
9828 }
9829 }
9830}
9831
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009832void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9833 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009834 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009835 Thread* const self = Thread::Current();
9836 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009837 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009838 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009839 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009840 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9841 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009842 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009843 }
9844}
9845
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009846void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009847 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009848 std::vector<ClassLoaderData> to_delete;
9849 // Do the delete outside the lock to avoid lock violation in jit code cache.
9850 {
9851 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9852 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9853 const ClassLoaderData& data = *it;
9854 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009855 ObjPtr<mirror::ClassLoader> class_loader =
9856 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009857 if (class_loader != nullptr) {
9858 ++it;
9859 } else {
9860 VLOG(class_linker) << "Freeing class loader";
9861 to_delete.push_back(data);
9862 it = class_loaders_.erase(it);
9863 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009864 }
9865 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009866 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009867 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009868 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009869 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009870}
9871
Vladimir Marko21300532017-01-24 18:06:55 +00009872class GetResolvedClassesVisitor : public ClassVisitor {
9873 public:
9874 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9875 : result_(result),
9876 ignore_boot_classes_(ignore_boot_classes),
9877 last_resolved_classes_(result->end()),
9878 last_dex_file_(nullptr),
9879 vlog_is_on_(VLOG_IS_ON(class_linker)),
9880 extra_stats_(),
9881 last_extra_stats_(extra_stats_.end()) { }
9882
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009883 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009884 if (!klass->IsProxyClass() &&
9885 !klass->IsArrayClass() &&
9886 klass->IsResolved() &&
9887 !klass->IsErroneousResolved() &&
9888 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9889 const DexFile& dex_file = klass->GetDexFile();
9890 if (&dex_file != last_dex_file_) {
9891 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009892 DexCacheResolvedClasses resolved_classes(
9893 dex_file.GetLocation(),
9894 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9895 dex_file.GetLocationChecksum(),
9896 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009897 last_resolved_classes_ = result_->find(resolved_classes);
9898 if (last_resolved_classes_ == result_->end()) {
9899 last_resolved_classes_ = result_->insert(resolved_classes).first;
9900 }
9901 }
9902 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9903 if (UNLIKELY(vlog_is_on_) && added) {
9904 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9905 if (last_extra_stats_ == extra_stats_.end() ||
9906 last_extra_stats_->first != resolved_classes) {
9907 last_extra_stats_ = extra_stats_.find(resolved_classes);
9908 if (last_extra_stats_ == extra_stats_.end()) {
9909 last_extra_stats_ =
9910 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9911 }
9912 }
9913 }
9914 }
9915 return true;
9916 }
9917
9918 void PrintStatistics() const {
9919 if (vlog_is_on_) {
9920 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9921 auto it = extra_stats_.find(std::addressof(resolved_classes));
9922 DCHECK(it != extra_stats_.end());
9923 const ExtraStats& extra_stats = it->second;
9924 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9925 << " has " << resolved_classes.GetClasses().size() << " / "
9926 << extra_stats.number_of_class_defs_ << " resolved classes";
9927 }
9928 }
9929 }
9930
9931 private:
9932 struct ExtraStats {
9933 explicit ExtraStats(uint32_t number_of_class_defs)
9934 : number_of_class_defs_(number_of_class_defs) {}
9935 uint32_t number_of_class_defs_;
9936 };
9937
9938 std::set<DexCacheResolvedClasses>* result_;
9939 bool ignore_boot_classes_;
9940 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9941 const DexFile* last_dex_file_;
9942
9943 // Statistics.
9944 bool vlog_is_on_;
9945 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9946 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9947};
9948
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009949std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009950 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009951 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009952 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009953 std::set<DexCacheResolvedClasses> ret;
9954 VLOG(class_linker) << "Collecting resolved classes";
9955 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009956 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9957 VisitClasses(&visitor);
9958 if (VLOG_IS_ON(class_linker)) {
9959 visitor.PrintStatistics();
9960 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009961 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009962 return ret;
9963}
9964
Mathieu Chartier65975772016-08-05 10:46:36 -07009965class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9966 public:
9967 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9968 : method_(method),
9969 pointer_size_(pointer_size) {}
9970
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009971 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009972 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9973 holder_ = klass;
9974 }
9975 // Return false to stop searching if holder_ is not null.
9976 return holder_ == nullptr;
9977 }
9978
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009979 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009980 const ArtMethod* const method_;
9981 const PointerSize pointer_size_;
9982};
9983
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009984ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009985 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9986 CHECK(method->IsCopied());
9987 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9988 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009989 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009990}
9991
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009992ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9993 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009994 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009995 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009996 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009997}
9998
Roland Levillain0e840272018-08-23 19:55:30 +01009999// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +010010000template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010001 uint32_t method_idx,
10002 Handle<mirror::DexCache> dex_cache,
10003 Handle<mirror::ClassLoader> class_loader,
10004 ArtMethod* referrer,
10005 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +010010006template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010007 uint32_t method_idx,
10008 Handle<mirror::DexCache> dex_cache,
10009 Handle<mirror::ClassLoader> class_loader,
10010 ArtMethod* referrer,
10011 InvokeType type);
10012
Roland Levillain0e840272018-08-23 19:55:30 +010010013// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010014template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010015 Thread* self,
10016 ObjPtr<mirror::Class> java_lang_Class,
10017 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010018template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010019 Thread* self,
10020 ObjPtr<mirror::Class> java_lang_Class,
10021 uint32_t class_size);
10022
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010023} // namespace art