blob: 9c61386f4e17c5b3819e2671b40c4ce37894ed4a [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070019#include <unistd.h>
20
Alex Lighteb7c1442015-08-31 13:17:42 -070021#include <algorithm>
Brian Carlstromdbc05252011-09-09 01:59:59 -070022#include <deque>
Vladimir Markobf121912019-06-04 13:49:05 +010023#include <forward_list>
Ian Rogerscf7f1912014-10-22 22:06:39 -070024#include <iostream>
Vladimir Marko21300532017-01-24 18:06:55 +000025#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070026#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070027#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070028#include <string>
Andreas Gampe9f3928f2019-02-04 11:19:31 -080029#include <string_view>
Alex Lighteb7c1442015-08-31 13:17:42 -070030#include <tuple>
Alex Lighteb7c1442015-08-31 13:17:42 -070031#include <unordered_map>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070032#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070033#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070034
Andreas Gampe46ee31b2016-12-14 10:11:49 -080035#include "android-base/stringprintf.h"
36
Mathieu Chartierc7853442015-03-27 14:35:38 -070037#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070038#include "art_method-inl.h"
Vladimir Markobf121912019-06-04 13:49:05 +010039#include "barrier.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070040#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080041#include "base/casts.h"
Andreas Gampe19f54162019-05-14 16:16:28 -070042#include "base/file_utils.h"
David Sehr67bf42e2018-02-26 16:43:04 -080043#include "base/leb128.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080044#include "base/logging.h"
Vladimir Markobf121912019-06-04 13:49:05 +010045#include "base/mutex-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080046#include "base/os.h"
47#include "base/quasi_atomic.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070048#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010049#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080050#include "base/stl_util.h"
Vladimir Markob9c29f62019-03-20 14:22:51 +000051#include "base/string_view_cpp20.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080052#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010053#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080054#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080055#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070056#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070057#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070059#include "class_loader_utils.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010060#include "class_root.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070061#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000062#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010063#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080064#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070065#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080066#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080067#include "dex/dex_file-inl.h"
68#include "dex/dex_file_exception_helpers.h"
69#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080070#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000071#include "dex/utf.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010072#include "entrypoints/entrypoint_utils-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070073#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070074#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070075#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080076#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000077#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070078#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070079#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070080#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070081#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000082#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070083#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070084#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070085#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080086#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070087#include "imt_conflict_table.h"
88#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070089#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070090#include "interpreter/interpreter.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000091#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080092#include "jit/jit.h"
93#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010094#include "jni/java_vm_ext.h"
95#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070096#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070097#include "mirror/array-alloc-inl.h"
98#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000099#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -0700100#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800101#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700102#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -0700103#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800104#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -0700105#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700106#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100107#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700108#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800109#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700110#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100111#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000112#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700113#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800114#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000115#include "mirror/object-refvisitor-inl.h"
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);
Vladimir Markocce414f2019-10-07 08:51:33 +0100306 class_linker_->FixupStaticTrampolines(klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100307 }
308 }
309 num_classes_ = 0u;
310 }
311 class_linker_->VisiblyInitializedCallbackDone(self, this);
312 }
313 }
314
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100315 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100316
317 ClassLinker* const class_linker_;
318 size_t num_classes_;
319 jweak classes_[kMaxClasses];
320
321 // The thread visibility counter starts at 0 and it is incremented by the number of
322 // threads that need to run this callback (by the thread that request the callback
323 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
324 // whether after the increment or after a decrement, we know that `Run()` was executed
325 // for all threads and therefore we can mark the classes as visibly initialized.
326 std::atomic<ssize_t> thread_visibility_counter_;
327
328 // List of barries to `Pass()` for threads that wait for the callback to complete.
329 std::forward_list<Barrier*> barriers_;
330};
331
332void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
333 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
334 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
335 }
336 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
337 if (wait) {
338 maybe_barrier.emplace(0);
339 }
340 int wait_count = 0;
341 VisiblyInitializedCallback* callback = nullptr;
342 {
343 MutexLock lock(self, visibly_initialized_callback_lock_);
344 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
345 callback = visibly_initialized_callback_.release();
346 running_visibly_initialized_callbacks_.push_front(*callback);
347 }
348 if (wait) {
349 DCHECK(maybe_barrier.has_value());
350 Barrier* barrier = std::addressof(*maybe_barrier);
351 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
352 cb.AddBarrier(barrier);
353 ++wait_count;
354 }
355 }
356 }
357 if (callback != nullptr) {
358 callback->MakeVisible(self);
359 }
360 if (wait_count != 0) {
361 DCHECK(maybe_barrier.has_value());
362 maybe_barrier->Increment(self, wait_count);
363 }
364}
365
366void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
367 VisiblyInitializedCallback* callback) {
368 MutexLock lock(self, visibly_initialized_callback_lock_);
369 // Pass the barriers if requested.
370 for (Barrier* barrier : callback->GetAndClearBarriers()) {
371 barrier->Pass(self);
372 }
373 // Remove the callback from the list of running callbacks.
374 auto before = running_visibly_initialized_callbacks_.before_begin();
375 auto it = running_visibly_initialized_callbacks_.begin();
376 DCHECK(it != running_visibly_initialized_callbacks_.end());
377 while (std::addressof(*it) != callback) {
378 before = it;
379 ++it;
380 DCHECK(it != running_visibly_initialized_callbacks_.end());
381 }
382 running_visibly_initialized_callbacks_.erase_after(before);
383 // Reuse or destroy the callback object.
384 if (visibly_initialized_callback_ == nullptr) {
385 visibly_initialized_callback_.reset(callback);
386 } else {
387 delete callback;
388 }
389}
390
Alex Lightfb119572019-09-18 15:04:53 -0700391void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
392 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
393 if (cb != nullptr) {
394 cb->MakeVisible(self);
395 }
396 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
397 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
398}
399
Vladimir Markobf121912019-06-04 13:49:05 +0100400ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
401 Thread* self, Handle<mirror::Class> klass) {
402 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
403 // Thanks to the x86 memory model, we do not need any memory fences and
404 // we can immediately mark the class as visibly initialized.
405 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Markocce414f2019-10-07 08:51:33 +0100406 FixupStaticTrampolines(klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100407 return nullptr;
408 }
409 if (Runtime::Current()->IsActiveTransaction()) {
410 // Transactions are single-threaded, so we can mark the class as visibly intialized.
411 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
412 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Markocce414f2019-10-07 08:51:33 +0100413 FixupStaticTrampolines(klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100414 return nullptr;
415 }
416 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
417 MutexLock lock(self, visibly_initialized_callback_lock_);
418 if (visibly_initialized_callback_ == nullptr) {
419 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
420 }
421 DCHECK(!visibly_initialized_callback_->IsFull());
422 visibly_initialized_callback_->AddClass(self, klass.Get());
423
424 if (visibly_initialized_callback_->IsFull()) {
425 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
426 running_visibly_initialized_callbacks_.push_front(*callback);
427 return callback;
428 } else {
429 return nullptr;
430 }
431}
432
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800433void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
434 bool wrap_in_no_class_def,
435 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700436 // The class failed to initialize on a previous attempt, so we want to throw
437 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
438 // failed in verification, in which case v2 5.4.1 says we need to re-throw
439 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800440 Runtime* const runtime = Runtime::Current();
441 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700442 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000443 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
444 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800445 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700446 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800447 } else {
448 extra = verify_error->AsThrowable()->Dump();
449 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700450 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800451 if (log) {
452 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
453 << ": " << extra;
454 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700455 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700456
David Sehr709b0702016-10-13 09:12:37 -0700457 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800458 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800459 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700460 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700461 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000462 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700463 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000464 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
465 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800466 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800467 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800468 }
Alex Lightd6251582016-10-31 11:12:30 -0700469 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
470 // might have meant to go down the earlier if statement with the original error but it got
471 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000472 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800473 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
474 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
475 // exception will be a cause.
476 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700477 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700478 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700479 }
480}
481
Brian Carlstromb23eab12014-10-08 17:55:21 -0700482static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700483 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700484 if (VLOG_IS_ON(class_linker)) {
485 std::string temp;
486 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000487 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700488 }
489}
490
491static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700492 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700493 Thread* self = Thread::Current();
494 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700495
496 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700497 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700498
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800499 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
500 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
501 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800502 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800503 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
504 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
505 // could have caused the error.
506 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
507 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
508 << " failed initialization: "
509 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800510 }
511
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700512 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700513 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
514 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700515
Elliott Hughesa4f94742012-05-29 16:28:38 -0700516 // We only wrap non-Error exceptions; an Error can just be used as-is.
517 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000518 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700519 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700520 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700521}
522
Fred Shih381e4ca2014-08-25 17:24:27 -0700523// Gap between two fields in object layout.
524struct FieldGap {
525 uint32_t start_offset; // The offset from the start of the object.
526 uint32_t size; // The gap size of 1, 2, or 4 bytes.
527};
528struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800529 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700530 }
531 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
532 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800533 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700534 // Note that the priority queue returns the largest element, so operator()
535 // should return true if lhs is less than rhs.
536 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700537 }
538};
Andreas Gampec55bb392018-09-21 00:02:02 +0000539using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700540
541// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800542static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700543 DCHECK(gaps != nullptr);
544
545 uint32_t current_offset = gap_start;
546 while (current_offset != gap_end) {
547 size_t remaining = gap_end - current_offset;
548 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
549 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
550 current_offset += sizeof(uint32_t);
551 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
552 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
553 current_offset += sizeof(uint16_t);
554 } else {
555 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
556 current_offset += sizeof(uint8_t);
557 }
558 DCHECK_LE(current_offset, gap_end) << "Overran gap";
559 }
560}
561// Shuffle fields forward, making use of gaps whenever possible.
562template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000563static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700564 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700565 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700566 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700567 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700568 DCHECK(current_field_idx != nullptr);
569 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700570 DCHECK(gaps != nullptr);
571 DCHECK(field_offset != nullptr);
572
573 DCHECK(IsPowerOfTwo(n));
574 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700575 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700576 Primitive::Type type = field->GetTypeAsPrimitiveType();
577 if (Primitive::ComponentSize(type) < n) {
578 break;
579 }
580 if (!IsAligned<n>(field_offset->Uint32Value())) {
581 MemberOffset old_offset = *field_offset;
582 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
583 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
584 }
David Sehr709b0702016-10-13 09:12:37 -0700585 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700586 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700587 if (!gaps->empty() && gaps->top().size >= n) {
588 FieldGap gap = gaps->top();
589 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100590 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700591 field->SetOffset(MemberOffset(gap.start_offset));
592 if (gap.size > n) {
593 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
594 }
595 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100596 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700597 field->SetOffset(*field_offset);
598 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
599 }
600 ++(*current_field_idx);
601 }
602}
603
Andreas Gampe87658f32019-04-18 18:39:02 +0000604ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700605 : boot_class_table_(new ClassTable()),
606 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800607 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800608 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700609 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000610 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700611 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000612 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Ian Rogers98379392014-02-24 16:53:16 -0800613 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800614 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100615 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800616 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700617 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100618 visibly_initialized_callback_lock_("visibly initialized callback lock"),
619 visibly_initialized_callback_(nullptr),
Andreas Gampe7dface32017-07-25 21:32:59 -0700620 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
621 // For CHA disabled during Aot, see b/34193647.
622
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700623 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700624 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
625 "Array cache size wrong.");
626 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700627}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700628
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800629void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700630 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800631 if (c2 == nullptr) {
632 LOG(FATAL) << "Could not find class " << descriptor;
633 UNREACHABLE();
634 }
635 if (c1.Get() != c2) {
636 std::ostringstream os1, os2;
637 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
638 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
639 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
640 << ". This is most likely the result of a broken build. Make sure that "
641 << "libcore and art projects match.\n\n"
642 << os1.str() << "\n\n" << os2.str();
643 UNREACHABLE();
644 }
645}
646
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800647bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
648 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800649 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700650
Mathieu Chartiere401d142015-04-22 13:56:20 -0700651 Thread* const self = Thread::Current();
652 Runtime* const runtime = Runtime::Current();
653 gc::Heap* const heap = runtime->GetHeap();
654
Jeff Haodcdc85b2015-12-04 14:06:18 -0800655 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700656 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700657
Mathieu Chartiere401d142015-04-22 13:56:20 -0700658 // Use the pointer size from the runtime since we are probably creating the image.
659 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
660
Elliott Hughes30646832011-10-13 16:59:46 -0700661 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700662 // 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 -0800663 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700664 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700665 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700666 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
667 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000668 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100669 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800670 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100671 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700672 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700673 if (kUseBakerReadBarrier) {
674 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800675 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700676 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700677 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800678 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700679 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700680
Elliott Hughes418d20f2011-09-22 14:00:39 -0700681 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700682 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700683 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700684 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700685 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700686
Ian Rogers23435d02012-09-24 11:23:12 -0700687 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700688 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700689 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800690 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700691 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700692 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000693 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700694
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700695 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800696 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
697 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100698 runtime->SetSentinel(heap->AllocNonMovableObject(self,
699 java_lang_Object.Get(),
700 java_lang_Object->GetObjectSize(),
701 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700702
Igor Murashkin86083f72017-10-27 10:59:04 -0700703 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000704 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700705 // It might seem the lock here is unnecessary, however all the SubtypeCheck
706 // functions are annotated to require locks all the way down.
707 //
708 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
709 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000710 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
711 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700712 }
713
Ian Rogers23435d02012-09-24 11:23:12 -0700714 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700715 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700716 AllocClass(self, java_lang_Class.Get(),
717 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700718 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700719
Roland Levillain0e840272018-08-23 19:55:30 +0100720 // Setup java.lang.String.
721 //
722 // We make this class non-movable for the unlikely case where it were to be
723 // moved by a sticky-bit (minor) collection when using the Generational
724 // Concurrent Copying (CC) collector, potentially creating a stale reference
725 // in the `klass_` field of one of its instances allocated in the Large-Object
726 // Space (LOS) -- see the comment about the dirty card scanning logic in
727 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700728 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700729 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100730 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700731 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000732 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400733
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700734 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700735 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700736 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700737 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000738 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700739
Ian Rogers23435d02012-09-24 11:23:12 -0700740 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700741 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100742 mirror::ObjectArray<mirror::Class>::Alloc(self,
743 object_array_class.Get(),
744 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700745 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100746 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
747 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
748 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
749 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100750 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
751 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700752
Mathieu Chartier6beced42016-11-15 15:51:31 -0800753 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
754 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
755
Vladimir Marko02610552018-06-04 14:38:00 +0100756 // Create array interface entries to populate once we can load system classes.
757 object_array_class->SetIfTable(AllocIfTable(self, 2));
758 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
759
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700760 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100761 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
762 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
763 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
764 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
765 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
766 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
767 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
768 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
769 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700770
Vladimir Marko70e2a762019-07-12 16:49:00 +0100771 // Allocate the primitive array classes. We need only the native pointer
772 // array at this point (int[] or long[], depending on architecture) but
773 // we shall perform the same setup steps for all primitive array classes.
774 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
775 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
776 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
777 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
778 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
779 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
780 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
781 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700782
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700783 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700784
Ian Rogers52813c92012-10-11 11:50:38 -0700785 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700786 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700787 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100788 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100789 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700790 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000791 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700792
Alex Lightd6251582016-10-31 11:12:30 -0700793
794 // Setup dalvik.system.ClassExt
795 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
796 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100797 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000798 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700799
Mathieu Chartier66f19252012-09-18 08:57:04 -0700800 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700801 Handle<mirror::Class> object_array_string(hs.NewHandle(
802 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700803 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700804 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100805 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700806
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000807 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700808 // Create runtime resolution and imt conflict methods.
809 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000810 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
811 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700812
Ian Rogers23435d02012-09-24 11:23:12 -0700813 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
814 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
815 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800816 if (boot_class_path.empty()) {
817 *error_msg = "Boot classpath is empty.";
818 return false;
819 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800820 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800821 if (dex_file.get() == nullptr) {
822 *error_msg = "Null dex file.";
823 return false;
824 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700825 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800826 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700827 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700828
829 // now we can use FindSystemClass
830
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700831 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
832 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700833 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800834 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700835 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700836 quick_resolution_trampoline_ = GetQuickResolutionStub();
837 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
838 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700839 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700840
Alex Lightd6251582016-10-31 11:12:30 -0700841 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000842 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800843 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700844 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000845 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800846 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000847 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800848 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700849 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000850 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700851 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
852 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700853
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800854 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
855 // in class_table_.
856 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700857
Vladimir Marko70e2a762019-07-12 16:49:00 +0100858 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
859 // arrays - can't be done until Object has a vtable and component classes are loaded.
860 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
861 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
862 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
863 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
864 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
865 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
866 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
867 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
868 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
869 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
870 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700871
Ian Rogers23435d02012-09-24 11:23:12 -0700872 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700873 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800874 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700875 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800876 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700877 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
878 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100879 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
880 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700881
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700882 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
883 // suspension.
884 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000885 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700886 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000887 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700888 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000889 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700890 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000891 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700892
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700893 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100894 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700895
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800896 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700897
Ian Rogers23435d02012-09-24 11:23:12 -0700898 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100899 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
900 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700901
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700902 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100903 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700904 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100905 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700906
907 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700908 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
909 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100910 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700911
912 // Create java.lang.reflect.Constructor.class root and array root.
913 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
914 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100915 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700916 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
917 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100918 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700919
920 // Create java.lang.reflect.Method.class root and array root.
921 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
922 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100923 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700924 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
925 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100926 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700927
Orion Hodson005ac512017-10-24 15:43:43 +0100928 // Create java.lang.invoke.CallSite.class root
929 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
930 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100931 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100932
Narayan Kamathafa48272016-08-03 12:46:58 +0100933 // Create java.lang.invoke.MethodType.class root
934 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
935 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100936 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100937
938 // Create java.lang.invoke.MethodHandleImpl.class root
939 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
940 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100941 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100942 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100943
Orion Hodsonc069a302017-01-18 09:23:12 +0000944 // Create java.lang.invoke.MethodHandles.Lookup.class root
945 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
946 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100947 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000948
Orion Hodson005ac512017-10-24 15:43:43 +0100949 // Create java.lang.invoke.VarHandle.class root
950 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000951 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100952 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100953
954 // Create java.lang.invoke.FieldVarHandle.class root
955 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
956 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100957 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100958
959 // Create java.lang.invoke.ArrayElementVarHandle.class root
960 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
961 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100962 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100963
964 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
965 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
966 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100967 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100968
969 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
970 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
971 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100972 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000973
Narayan Kamath000e1882016-10-24 17:14:25 +0100974 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
975 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100976 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100977
Brian Carlstrom1f870082011-08-23 16:02:11 -0700978 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700979 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000980 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800981 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700982 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700983 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
984 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700985 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700986 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700987 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700988 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700989 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700990 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700991 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700992 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700993 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700994 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700995 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700996 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700997
Ian Rogers23435d02012-09-24 11:23:12 -0700998 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700999 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001000 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001001 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001002 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001003
jeffhao8cd6dda2012-02-22 10:15:34 -08001004 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -07001005 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001006 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001007 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -07001008 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001009 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
1010 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
1011 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001012 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001013 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1014 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001015
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001016 // Create conflict tables that depend on the class linker.
1017 runtime->FixupConflictTables();
1018
Ian Rogers98379392014-02-24 16:53:16 -08001019 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001020
Brian Carlstroma004aa92012-02-08 18:05:09 -08001021 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001022
1023 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001024}
1025
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001026static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1027 REQUIRES_SHARED(Locks::mutator_lock_) {
1028 // Find String.<init> -> StringFactory bindings.
1029 ObjPtr<mirror::Class> string_factory_class =
1030 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1031 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001032 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001033 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1034 // Update the primordial thread.
1035 self->InitStringEntryPoints();
1036}
1037
Ian Rogers98379392014-02-24 16:53:16 -08001038void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001039 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001040
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001041 CreateStringInitBindings(self, this);
1042
Brian Carlstrom16192862011-09-12 17:50:06 -07001043 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001044 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001045 // as the types of the field can't be resolved prior to the runtime being
1046 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001047 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001048 Handle<mirror::Class> java_lang_ref_Reference =
1049 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001050 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1051 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001052
Mathieu Chartierc7853442015-03-27 14:35:38 -07001053 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001054 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1055 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001056
Mathieu Chartierc7853442015-03-27 14:35:38 -07001057 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001058 CHECK_STREQ(queue->GetName(), "queue");
1059 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001060
Mathieu Chartierc7853442015-03-27 14:35:38 -07001061 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001062 CHECK_STREQ(queueNext->GetName(), "queueNext");
1063 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001064
Mathieu Chartierc7853442015-03-27 14:35:38 -07001065 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001066 CHECK_STREQ(referent->GetName(), "referent");
1067 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001068
Mathieu Chartierc7853442015-03-27 14:35:38 -07001069 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001070 CHECK_STREQ(zombie->GetName(), "zombie");
1071 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001072
Brian Carlstroma663ea52011-08-19 23:33:41 -07001073 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001074 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001075 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001076 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001077 CHECK(klass != nullptr);
1078 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001079 // note SetClassRoot does additional validation.
1080 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001081 }
1082
Vladimir Marko02610552018-06-04 14:38:00 +01001083 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001084
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001085 // disable the slow paths in FindClass and CreatePrimitiveClass now
1086 // that Object, Class, and Object[] are setup
1087 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001088
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001089 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1090 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1091 // ensure that the class will be initialized.
1092 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001093 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001094
1095 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1096 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1097 // Strange, but don't crash.
1098 LOG(WARNING) << "Could not prepare StackOverflowError.";
1099 self->ClearException();
1100 }
1101 }
1102
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001103 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001104}
1105
Vladimir Markodcfcce42018-06-27 10:00:28 +00001106void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001107 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1108 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001109 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001110 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001111 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -07001112 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001113 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +00001114 } else {
1115 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001116 }
1117 }
1118}
1119
Jeff Haodcdc85b2015-12-04 14:06:18 -08001120struct TrampolineCheckData {
1121 const void* quick_resolution_trampoline;
1122 const void* quick_imt_conflict_trampoline;
1123 const void* quick_generic_jni_trampoline;
1124 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001125 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001126 ArtMethod* m;
1127 bool error;
1128};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001129
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001130bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1131 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001132 CHECK(!init_done_);
1133
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001134 Runtime* const runtime = Runtime::Current();
1135 Thread* const self = Thread::Current();
1136 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001137 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1138 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001139 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1140 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001141 if (!ValidPointerSize(pointer_size_unchecked)) {
1142 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001143 return false;
1144 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001145 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001146 if (!runtime->IsAotCompiler()) {
1147 // Only the Aot compiler supports having an image with a different pointer size than the
1148 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1149 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001150 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001151 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001152 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001153 sizeof(void*));
1154 return false;
1155 }
1156 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001157 DCHECK(!runtime->HasResolutionMethod());
1158 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1159 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1160 runtime->SetImtUnimplementedMethod(
1161 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1162 runtime->SetCalleeSaveMethod(
1163 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1164 CalleeSaveType::kSaveAllCalleeSaves);
1165 runtime->SetCalleeSaveMethod(
1166 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1167 CalleeSaveType::kSaveRefsOnly);
1168 runtime->SetCalleeSaveMethod(
1169 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1170 CalleeSaveType::kSaveRefsAndArgs);
1171 runtime->SetCalleeSaveMethod(
1172 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1173 CalleeSaveType::kSaveEverything);
1174 runtime->SetCalleeSaveMethod(
1175 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1176 CalleeSaveType::kSaveEverythingForClinit);
1177 runtime->SetCalleeSaveMethod(
1178 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1179 CalleeSaveType::kSaveEverythingForSuspendCheck);
1180
Jeff Haodcdc85b2015-12-04 14:06:18 -08001181 std::vector<const OatFile*> oat_files =
1182 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1183 DCHECK(!oat_files.empty());
1184 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001185 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1186 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1187 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1188 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1189 if (kIsDebugBuild) {
1190 // Check that the other images use the same trampoline.
1191 for (size_t i = 1; i < oat_files.size(); ++i) {
1192 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1193 const void* ith_quick_resolution_trampoline =
1194 ith_oat_header.GetQuickResolutionTrampoline();
1195 const void* ith_quick_imt_conflict_trampoline =
1196 ith_oat_header.GetQuickImtConflictTrampoline();
1197 const void* ith_quick_generic_jni_trampoline =
1198 ith_oat_header.GetQuickGenericJniTrampoline();
1199 const void* ith_quick_to_interpreter_bridge_trampoline =
1200 ith_oat_header.GetQuickToInterpreterBridge();
1201 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1202 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1203 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1204 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1205 // Make sure that all methods in this image do not contain those trampolines as
1206 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1207 TrampolineCheckData data;
1208 data.error = false;
1209 data.pointer_size = GetImagePointerSize();
1210 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1211 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1212 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1213 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1214 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001215 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1216 if (obj->IsClass()) {
1217 ObjPtr<mirror::Class> klass = obj->AsClass();
1218 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1219 const void* entrypoint =
1220 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1221 if (entrypoint == data.quick_resolution_trampoline ||
1222 entrypoint == data.quick_imt_conflict_trampoline ||
1223 entrypoint == data.quick_generic_jni_trampoline ||
1224 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1225 data.m = &m;
1226 data.error = true;
1227 return;
1228 }
1229 }
1230 }
1231 };
1232 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001233 if (data.error) {
1234 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001235 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001236 *error_msg = "Found an ArtMethod with a bad entrypoint";
1237 return false;
1238 }
1239 }
1240 }
1241 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001242
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001243 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001244 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001245 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001246 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001247
Vladimir Marko024d69f2019-06-13 10:52:32 +01001248 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1249 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1250 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1251 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1252 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1253 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001254
Vladimir Marko4433c432018-12-04 14:57:47 +00001255 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1256 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001257 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001258 // Boot class loader, use a null handle.
1259 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001260 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001261 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001262 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001263 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001264 /*out*/&dex_files,
1265 error_msg)) {
1266 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001267 }
David Brazdil3e8aae02019-03-26 18:48:02 +00001268 // Assert that if absolute boot classpath locations were provided, they were
1269 // assigned to the loaded dex files.
1270 if (kIsDebugBuild && IsAbsoluteLocation(boot_class_path_locations[i])) {
1271 for (const auto& dex_file : dex_files) {
1272 DCHECK_EQ(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1273 boot_class_path_locations[i]);
1274 }
1275 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001276 // Append opened dex files at the end.
1277 boot_dex_files_.insert(boot_dex_files_.end(),
1278 std::make_move_iterator(dex_files.begin()),
1279 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001280 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001281 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1282 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1283 }
Ian Rogers98379392014-02-24 16:53:16 -08001284 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001285
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001286 VLOG(startup) << __FUNCTION__ << " exiting";
1287 return true;
1288}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001289
Vladimir Marko4433c432018-12-04 14:57:47 +00001290void ClassLinker::AddExtraBootDexFiles(
1291 Thread* self,
1292 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1293 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1294 AppendToBootClassPath(self, *dex_file);
1295 boot_dex_files_.push_back(std::move(dex_file));
1296 }
1297}
1298
Jeff Hao5872d7c2016-04-27 11:07:41 -07001299bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001300 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001301 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001302 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1303 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001304}
1305
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001306static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1307 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001308 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001309 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001310 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001311 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001312 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001313 DCHECK(dex_file_field != nullptr);
1314 DCHECK(dex_file_name_field != nullptr);
1315 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001316 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001317 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001318 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001319 // Null dex file means it was probably a jar with no dex files, return a null string.
1320 *out_name = nullptr;
1321 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001322 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001323 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001324 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001325 *out_name = name_object->AsString();
1326 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001327 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001328 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001329}
1330
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001331static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1332 ObjPtr<mirror::ClassLoader> class_loader,
1333 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1334 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001335 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001336 StackHandleScope<1> hs(soa.Self());
1337 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001338 // Get element names. Sets error to true on failure.
1339 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1340 REQUIRES_SHARED(Locks::mutator_lock_) {
1341 if (element == nullptr) {
1342 *error_msg = "Null dex element";
1343 *error = true; // Null element is a critical error.
1344 return false; // Had an error, stop the visit.
1345 }
1346 ObjPtr<mirror::String> name;
1347 if (!GetDexPathListElementName(element, &name)) {
1348 *error_msg = "Invalid dex path list element";
1349 *error = true; // Invalid element, make it a critical error.
1350 return false; // Stop the visit.
1351 }
1352 if (name != nullptr) {
1353 dex_files->push_front(name);
1354 }
1355 return true; // Continue with the next Element.
1356 };
1357 bool error = VisitClassLoaderDexElements(soa,
1358 handle,
1359 add_element_names,
1360 /*defaultReturn=*/ false);
1361 return !error;
1362}
1363
1364static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1365 ObjPtr<mirror::ClassLoader> image_class_loader,
1366 ObjPtr<mirror::ClassLoader> class_loader,
1367 std::string* error_msg)
1368 REQUIRES_SHARED(Locks::mutator_lock_) {
1369 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1370 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1371 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001372 return false;
1373 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001374 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1375 *error_msg = "Hierarchies don't match";
1376 return false;
1377 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1378 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1379 image_class_loader->PrettyTypeOf().c_str(),
1380 class_loader->PrettyTypeOf().c_str());
1381 return false;
1382 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1383 class_loader->GetClass()) {
1384 *error_msg = StringPrintf("Unknown class loader type %s",
1385 class_loader->PrettyTypeOf().c_str());
1386 // Unsupported class loader.
1387 return false;
1388 }
1389 return true;
1390}
1391
1392static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1393 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1394 std::string* error_msg)
1395 REQUIRES_SHARED(Locks::mutator_lock_) {
1396 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1397 std::equal(image_dex_files.begin(),
1398 image_dex_files.end(),
1399 loader_dex_files.begin(),
1400 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1401 REQUIRES_SHARED(Locks::mutator_lock_) {
1402 return lhs->Equals(rhs);
1403 });
1404 if (!equal) {
1405 VLOG(image) << "Image dex files " << image_dex_files.size();
1406 for (ObjPtr<mirror::String> name : image_dex_files) {
1407 VLOG(image) << name->ToModifiedUtf8();
1408 }
1409 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1410 for (ObjPtr<mirror::String> name : loader_dex_files) {
1411 VLOG(image) << name->ToModifiedUtf8();
1412 }
1413 *error_msg = "Mismatch in dex files";
1414 }
1415 return equal;
1416}
1417
1418static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1419 ObjPtr<mirror::ClassLoader> image_class_loader,
1420 ObjPtr<mirror::ClassLoader> class_loader,
1421 bool check_dex_file_names,
1422 std::string* error_msg)
1423 REQUIRES_SHARED(Locks::mutator_lock_) {
1424 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1425 return false;
1426 }
1427
1428 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1429 // No need to check further.
1430 return true;
1431 }
1432
1433 if (check_dex_file_names) {
1434 std::list<ObjPtr<mirror::String>> image_dex_files;
1435 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001436 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001437 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001438
1439 std::list<ObjPtr<mirror::String>> loader_dex_files;
1440 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1441 return false;
1442 }
1443
1444 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1445 return false;
1446 }
1447 }
1448
1449 ArtField* field =
1450 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1451 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1452 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1453 if (shared_libraries_image_loader == nullptr) {
1454 if (shared_libraries_loader != nullptr) {
1455 *error_msg = "Mismatch in shared libraries";
1456 return false;
1457 }
1458 } else if (shared_libraries_loader == nullptr) {
1459 *error_msg = "Mismatch in shared libraries";
1460 return false;
1461 } else {
1462 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1463 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1464 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1465 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1466 if (array1->GetLength() != array2->GetLength()) {
1467 *error_msg = "Mismatch in number of shared libraries";
1468 return false;
1469 }
1470
1471 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1472 // Do a full comparison of the class loaders, including comparing their dex files.
1473 if (!CompareClassLoaders(soa,
1474 array1->Get(i),
1475 array2->Get(i),
1476 /*check_dex_file_names=*/ true,
1477 error_msg)) {
1478 return false;
1479 }
1480 }
1481 }
1482
1483 // Do a full comparison of the class loaders, including comparing their dex files.
1484 if (!CompareClassLoaders(soa,
1485 image_class_loader->GetParent(),
1486 class_loader->GetParent(),
1487 /*check_dex_file_names=*/ true,
1488 error_msg)) {
1489 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001490 }
1491 return true;
1492}
1493
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001494class CHAOnDeleteUpdateClassVisitor {
1495 public:
1496 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1497 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1498 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1499 self_(Thread::Current()) {}
1500
1501 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1502 // This class is going to be unloaded. Tell CHA about it.
1503 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1504 return true;
1505 }
1506 private:
1507 const LinearAlloc* allocator_;
1508 const ClassHierarchyAnalysis* cha_;
1509 const PointerSize pointer_size_;
1510 const Thread* self_;
1511};
1512
Chris Wailes0c61be42018-09-26 17:27:34 -07001513/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001514 * A class used to ensure that all references to strings interned in an AppImage have been
1515 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001516 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001517class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001518 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001519 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1520 const InternTable::UnorderedSet& image_interns)
1521 : space_(space),
1522 image_interns_(image_interns),
1523 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001524
Chris Wailes0c61be42018-09-26 17:27:34 -07001525 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001526 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001527 if (referred_obj != nullptr &&
1528 space_.HasAddress(referred_obj.Ptr()) &&
1529 referred_obj->IsString()) {
1530 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001531 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1532 if (it != image_interns_.end() && it->Read() == referred_str) {
1533 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001534 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001535 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001536 }
1537
Chris Wailes0c61be42018-09-26 17:27:34 -07001538 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001539 mirror::CompressedReference<mirror::Object>* root) const
1540 REQUIRES_SHARED(Locks::mutator_lock_) {
1541 if (!root->IsNull()) {
1542 VisitRoot(root);
1543 }
1544 }
1545
Chris Wailes0c61be42018-09-26 17:27:34 -07001546 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001547 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001548 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001549 }
1550
1551 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001552 void operator()(ObjPtr<mirror::Object> obj,
1553 MemberOffset offset,
1554 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001555 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001556 // References within image or across images don't need a read barrier.
1557 ObjPtr<mirror::Object> referred_obj =
1558 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1559 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001560 }
1561
1562 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1563 ObjPtr<mirror::Reference> ref) const
1564 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001565 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001566 }
1567
Vladimir Marko8e05f092019-06-10 11:10:38 +01001568 size_t GetCount() const {
1569 return count_;
1570 }
1571
1572 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001573 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001574 const InternTable::UnorderedSet& image_interns_;
1575 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001576};
1577
Chris Wailes0c61be42018-09-26 17:27:34 -07001578/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001579 * This function counts references to strings interned in the AppImage.
1580 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001581 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001582size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1583 const InternTable::UnorderedSet& image_interns)
1584 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001585 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1586 const ImageHeader& image_header = space.GetImageHeader();
1587 const uint8_t* target_base = space.GetMemMap()->Begin();
1588 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001589
1590 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1591 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001592
Vladimir Marko8e05f092019-06-10 11:10:38 +01001593 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001594 bitmap->VisitMarkedRange(objects_begin,
1595 objects_end,
1596 [&space, &visitor](mirror::Object* obj)
1597 REQUIRES_SHARED(Locks::mutator_lock_) {
1598 if (space.HasAddress(obj)) {
1599 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001600 obj->VisitReferences</* kVisitNativeRoots= */ true,
1601 kVerifyNone,
1602 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001603 } else {
1604 // Don't visit native roots for non-dex-cache as they can't contain
1605 // native references to strings. This is verified during compilation
1606 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001607 obj->VisitReferences</* kVisitNativeRoots= */ false,
1608 kVerifyNone,
1609 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001610 }
1611 }
1612 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001613 return visitor.GetCount();
1614}
1615
1616template <typename Visitor>
1617static void VisitInternedStringReferences(
1618 gc::space::ImageSpace* space,
1619 bool use_preresolved_strings,
1620 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1621 const uint8_t* target_base = space->Begin();
1622 const ImageSection& sro_section =
1623 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1624 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1625
1626 VLOG(image)
1627 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1628 << num_string_offsets;
1629
1630 const auto* sro_base =
1631 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1632
1633 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1634 uint32_t base_offset = sro_base[offset_index].first;
1635
1636 if (HasDexCacheStringNativeRefTag(base_offset)) {
1637 base_offset = ClearDexCacheNativeRefTags(base_offset);
1638 DCHECK_ALIGNED(base_offset, 2);
1639
1640 ObjPtr<mirror::DexCache> dex_cache =
1641 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1642 uint32_t string_slot_index = sro_base[offset_index].second;
1643
1644 mirror::StringDexCachePair source =
1645 dex_cache->GetStrings()[string_slot_index].load(std::memory_order_relaxed);
1646 ObjPtr<mirror::String> referred_string = source.object.Read();
1647 DCHECK(referred_string != nullptr);
1648
1649 ObjPtr<mirror::String> visited = visitor(referred_string);
1650 if (visited != referred_string) {
1651 // Because we are not using a helper function we need to mark the GC card manually.
1652 WriteBarrier::ForEveryFieldWrite(dex_cache);
1653 dex_cache->GetStrings()[string_slot_index].store(
1654 mirror::StringDexCachePair(visited, source.index), std::memory_order_relaxed);
1655 }
1656 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1657 if (use_preresolved_strings) {
1658 base_offset = ClearDexCacheNativeRefTags(base_offset);
1659 DCHECK_ALIGNED(base_offset, 2);
1660
1661 ObjPtr<mirror::DexCache> dex_cache =
1662 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1663 uint32_t string_index = sro_base[offset_index].second;
1664
Mathieu Chartier77f84fc2019-06-14 12:49:54 -07001665 GcRoot<mirror::String>* preresolved_strings =
1666 dex_cache->GetPreResolvedStrings();
1667 // Handle calls to ClearPreResolvedStrings that might occur concurrently by the profile
1668 // saver that runs shortly after startup. In case the strings are cleared, there is nothing
1669 // to fix up.
1670 if (preresolved_strings != nullptr) {
1671 ObjPtr<mirror::String> referred_string =
1672 preresolved_strings[string_index].Read();
1673 if (referred_string != nullptr) {
1674 ObjPtr<mirror::String> visited = visitor(referred_string);
1675 if (visited != referred_string) {
1676 // Because we are not using a helper function we need to mark the GC card manually.
1677 WriteBarrier::ForEveryFieldWrite(dex_cache);
1678 preresolved_strings[string_index] = GcRoot<mirror::String>(visited);
1679 }
1680 }
Vladimir Marko8e05f092019-06-10 11:10:38 +01001681 }
1682 }
1683 } else {
1684 uint32_t raw_member_offset = sro_base[offset_index].second;
1685 DCHECK_ALIGNED(base_offset, 2);
1686 DCHECK_ALIGNED(raw_member_offset, 2);
1687
1688 ObjPtr<mirror::Object> obj_ptr =
1689 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1690 MemberOffset member_offset(raw_member_offset);
1691 ObjPtr<mirror::String> referred_string =
1692 obj_ptr->GetFieldObject<mirror::String,
1693 kVerifyNone,
1694 kWithoutReadBarrier,
1695 /* kIsVolatile= */ false>(member_offset);
1696 DCHECK(referred_string != nullptr);
1697
1698 ObjPtr<mirror::String> visited = visitor(referred_string);
1699 if (visited != referred_string) {
1700 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1701 /* kCheckTransaction= */ false,
1702 kVerifyNone,
1703 /* kIsVolatile= */ false>(member_offset, visited);
1704 }
1705 }
1706 }
1707}
1708
1709static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1710 REQUIRES_SHARED(Locks::mutator_lock_) {
1711 InternTable::UnorderedSet image_interns;
1712 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1713 if (section.Size() > 0) {
1714 size_t read_count;
1715 const uint8_t* data = space->Begin() + section.Offset();
1716 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1717 image_set.swap(image_interns);
1718 }
1719 size_t num_recorded_refs = 0u;
1720 VisitInternedStringReferences(
1721 space,
1722 /*use_preresolved_strings=*/ true,
1723 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1724 REQUIRES_SHARED(Locks::mutator_lock_) {
1725 auto it = image_interns.find(GcRoot<mirror::String>(str));
1726 CHECK(it != image_interns.end());
1727 CHECK(it->Read() == str);
1728 ++num_recorded_refs;
1729 return str;
1730 });
1731 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1732 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001733}
1734
Andreas Gampe2af99022017-04-25 08:32:59 -07001735// new_class_set is the set of classes that were read from the class table section in the image.
1736// If there was no class table section, it is null.
1737// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001738class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001739 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001740 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001741 ClassLinker* class_linker,
1742 gc::space::ImageSpace* space,
1743 Handle<mirror::ClassLoader> class_loader,
1744 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001745 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001746 REQUIRES(!Locks::dex_lock_)
1747 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001748
Chris Wailesfbeef462018-10-19 14:16:35 -07001749 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001750 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001751};
1752
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001753void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001754 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001755 gc::space::ImageSpace* space,
1756 Handle<mirror::ClassLoader> class_loader,
1757 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001758 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001759 REQUIRES(!Locks::dex_lock_)
1760 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001761 ScopedTrace app_image_timing("AppImage:Updating");
1762
Vladimir Marko8e05f092019-06-10 11:10:38 +01001763 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1764 // In debug build, verify the string references before applying
1765 // the Runtime::LoadAppImageStartupCache() option.
1766 VerifyInternedStringReferences(space);
1767 }
1768
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001769 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001770 Runtime* const runtime = Runtime::Current();
1771 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001772 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001773 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001774 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001775 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001776 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001777 const size_t num_dex_caches = dex_caches->GetLength();
1778 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001779 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001780 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001781 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001782 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001783 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1784 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001785 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001786
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001787 if (!load_app_image_startup_cache) {
1788 dex_cache->ClearPreResolvedStrings();
1789 }
1790
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001791 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001792 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001793 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001794 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001795 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001796 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001797 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001798
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001799 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001800 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001801 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001802 DCHECK(it != new_class_set->end());
1803 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001804 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001805
Vladimir Marko1a1de672016-10-13 12:53:15 +01001806 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001807 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001808 DCHECK(it2 != new_class_set->end());
1809 DCHECK_EQ(it2->Read(), super_class);
1810 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001811
Vladimir Marko1a1de672016-10-13 12:53:15 +01001812 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1813 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001814 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1815 if (!class_linker->IsQuickResolutionStub(code) &&
1816 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001817 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001818 !m.IsNative()) {
1819 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001820 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001821 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001822
Vladimir Marko1a1de672016-10-13 12:53:15 +01001823 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1824 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001825 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1826 if (!class_linker->IsQuickResolutionStub(code) &&
1827 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001828 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001829 !m.IsNative()) {
1830 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001831 }
1832 }
1833 }
1834 }
1835 }
1836 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001837 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001838
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001839 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001840 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001841 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001842
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001843 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001844 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001845 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001846 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1847 header.VisitPackedArtMethods([&](ArtMethod& method)
1848 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1849 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1850 if (klass != nullptr) {
1851 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1852 }
1853 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001854 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001855}
1856
Chris Wailesfbeef462018-10-19 14:16:35 -07001857void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001858 // Iterate over the string reference offsets stored in the image and intern
1859 // the strings they point to.
1860 ScopedTrace timing("AppImage:InternString");
1861
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001862 Runtime* const runtime = Runtime::Current();
1863 InternTable* const intern_table = runtime->GetInternTable();
1864
1865 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001866
1867 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1868 // for faster lookup.
1869 // TODO: Optimize with a bitmap or bloom filter
1870 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001871 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001872 REQUIRES_SHARED(Locks::mutator_lock_)
1873 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001874 const size_t non_boot_image_strings = intern_table->CountInterns(
1875 /*visit_boot_images=*/false,
1876 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001877 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001878 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1879 // Visit the smaller of the two sets to compute the intersection.
1880 if (interns.size() < non_boot_image_strings) {
1881 for (auto it = interns.begin(); it != interns.end(); ) {
1882 ObjPtr<mirror::String> string = it->Read();
1883 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1884 if (existing == nullptr) {
1885 existing = intern_table->LookupStrongLocked(string);
1886 }
1887 if (existing != nullptr) {
1888 intern_remap.Put(string.Ptr(), existing.Ptr());
1889 it = interns.erase(it);
1890 } else {
1891 ++it;
1892 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001893 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001894 } else {
1895 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1896 REQUIRES_SHARED(Locks::mutator_lock_)
1897 REQUIRES(Locks::intern_table_lock_) {
1898 auto it = interns.find(root);
1899 if (it != interns.end()) {
1900 ObjPtr<mirror::String> existing = root.Read();
1901 intern_remap.Put(it->Read(), existing.Ptr());
1902 it = interns.erase(it);
1903 }
1904 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1905 }
1906 // Sanity check to ensure correctness.
1907 if (kIsDebugBuild) {
1908 for (GcRoot<mirror::String>& root : interns) {
1909 ObjPtr<mirror::String> string = root.Read();
1910 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1911 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001912 }
1913 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001914 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001915 intern_table->AddImageStringsToTable(space, func);
1916 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001917 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001918 VisitInternedStringReferences(
1919 space,
1920 load_startup_cache,
1921 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1922 auto it = intern_remap.find(str.Ptr());
1923 if (it != intern_remap.end()) {
1924 return ObjPtr<mirror::String>(it->second);
1925 }
1926 return str;
1927 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001928 }
1929}
1930
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001931static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1932 const char* location,
1933 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001934 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001935 DCHECK(error_msg != nullptr);
1936 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001937 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001938 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001939 return std::unique_ptr<const DexFile>();
1940 }
1941 std::string inner_error_msg;
1942 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1943 if (dex_file == nullptr) {
1944 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1945 location,
1946 oat_file->GetLocation().c_str(),
1947 inner_error_msg.c_str());
1948 return std::unique_ptr<const DexFile>();
1949 }
1950
1951 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1952 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1953 location,
1954 dex_file->GetLocationChecksum(),
1955 oat_dex_file->GetDexFileLocationChecksum());
1956 return std::unique_ptr<const DexFile>();
1957 }
1958 return dex_file;
1959}
1960
1961bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1962 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1963 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001964 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001965 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001966 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001967 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001968 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001969 dex_caches_object->AsObjectArray<mirror::DexCache>();
1970 const OatFile* oat_file = space->GetOatFile();
Vladimir Marko4617d582019-03-28 13:48:31 +00001971 for (int32_t i = 0, length = dex_caches->GetLength(); i != length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001972 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001973 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1974 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1975 dex_file_location.c_str(),
1976 error_msg);
1977 if (dex_file == nullptr) {
1978 return false;
1979 }
1980 dex_cache->SetDexFile(dex_file.get());
1981 out_dex_files->push_back(std::move(dex_file));
1982 }
1983 return true;
1984}
1985
Andreas Gampe0793bec2016-12-01 11:37:33 -08001986// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1987// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001988class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001989 public:
1990 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1991 REQUIRES_SHARED(Locks::mutator_lock_) {
1992 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001993 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1994 DCHECK(obj != nullptr);
1995 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1996 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1997 if (obj->IsClass()) {
1998 auto klass = obj->AsClass();
1999 for (ArtField& field : klass->GetIFields()) {
2000 CHECK_EQ(field.GetDeclaringClass(), klass);
2001 }
2002 for (ArtField& field : klass->GetSFields()) {
2003 CHECK_EQ(field.GetDeclaringClass(), klass);
2004 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002005 const PointerSize pointer_size = isc.pointer_size_;
2006 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07002007 isc.SanityCheckArtMethod(&m, klass);
2008 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002009 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07002010 if (vtable != nullptr) {
2011 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
2012 }
2013 if (klass->ShouldHaveImt()) {
2014 ImTable* imt = klass->GetImt(pointer_size);
2015 for (size_t i = 0; i < ImTable::kSize; ++i) {
2016 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
2017 }
2018 }
2019 if (klass->ShouldHaveEmbeddedVTable()) {
2020 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
2021 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
2022 }
2023 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00002024 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07002025 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2026 if (iftable->GetMethodArrayCount(i) > 0) {
2027 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
2028 }
2029 }
2030 }
2031 };
2032 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08002033 }
2034
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002035 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
2036 ClassLinker* class_linker,
2037 mirror::MethodDexCacheType* arr,
2038 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08002039 REQUIRES_SHARED(Locks::mutator_lock_) {
2040 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002041 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08002042 }
2043
Andreas Gampe0793bec2016-12-01 11:37:33 -08002044 private:
2045 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
2046 : spaces_(heap->GetBootImageSpaces()),
2047 pointer_size_(class_linker->GetImagePointerSize()) {
2048 space_begin_.reserve(spaces_.size());
2049 method_sections_.reserve(spaces_.size());
2050 runtime_method_sections_.reserve(spaces_.size());
2051 for (gc::space::ImageSpace* space : spaces_) {
2052 space_begin_.push_back(space->Begin());
2053 auto& header = space->GetImageHeader();
2054 method_sections_.push_back(&header.GetMethodsSection());
2055 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
2056 }
2057 }
2058
2059 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
2060 REQUIRES_SHARED(Locks::mutator_lock_) {
2061 if (m->IsRuntimeMethod()) {
2062 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
2063 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
2064 } else if (m->IsCopied()) {
2065 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
2066 } else if (expected_class != nullptr) {
2067 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
2068 }
2069 if (!spaces_.empty()) {
2070 bool contains = false;
2071 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
2072 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
2073 contains = method_sections_[i]->Contains(offset) ||
2074 runtime_method_sections_[i]->Contains(offset);
2075 }
2076 CHECK(contains) << m << " not found";
2077 }
2078 }
2079
2080 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
2081 ObjPtr<mirror::Class> expected_class)
2082 REQUIRES_SHARED(Locks::mutator_lock_) {
2083 CHECK(arr != nullptr);
2084 for (int32_t j = 0; j < arr->GetLength(); ++j) {
2085 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
2086 // expected_class == null means we are a dex cache.
2087 if (expected_class != nullptr) {
2088 CHECK(method != nullptr);
2089 }
2090 if (method != nullptr) {
2091 SanityCheckArtMethod(method, expected_class);
2092 }
2093 }
2094 }
2095
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002096 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08002097 REQUIRES_SHARED(Locks::mutator_lock_) {
2098 CHECK_EQ(arr != nullptr, size != 0u);
2099 if (arr != nullptr) {
2100 bool contains = false;
2101 for (auto space : spaces_) {
2102 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002103 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002104 contains = true;
2105 break;
2106 }
2107 }
2108 CHECK(contains);
2109 }
2110 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002111 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
2112 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08002113 // expected_class == null means we are a dex cache.
2114 if (method != nullptr) {
2115 SanityCheckArtMethod(method, nullptr);
2116 }
2117 }
2118 }
2119
2120 const std::vector<gc::space::ImageSpace*>& spaces_;
2121 const PointerSize pointer_size_;
2122
2123 // Cached sections from the spaces.
2124 std::vector<const uint8_t*> space_begin_;
2125 std::vector<const ImageSection*> method_sections_;
2126 std::vector<const ImageSection*> runtime_method_sections_;
2127};
2128
Andreas Gampebe7af222017-07-25 09:57:28 -07002129static void VerifyAppImage(const ImageHeader& header,
2130 const Handle<mirror::ClassLoader>& class_loader,
2131 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
2132 ClassTable* class_table, gc::space::ImageSpace* space)
2133 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002134 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2135 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
2136 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2137 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
2138 << mirror::Class::PrettyClass(klass);
2139 }
2140 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07002141 {
2142 // Verify that all direct interfaces of classes in the class table are also resolved.
2143 std::vector<ObjPtr<mirror::Class>> classes;
2144 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
2145 REQUIRES_SHARED(Locks::mutator_lock_) {
2146 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
2147 classes.push_back(klass);
2148 }
2149 return true;
2150 };
2151 class_table->Visit(verify_direct_interfaces_in_table);
2152 Thread* self = Thread::Current();
2153 for (ObjPtr<mirror::Class> klass : classes) {
2154 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
2155 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
2156 << klass->PrettyDescriptor() << " iface #" << i;
2157 }
2158 }
2159 }
2160 // Check that all non-primitive classes in dex caches are also in the class table.
2161 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2162 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2163 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
2164 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
2165 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
2166 if (klass != nullptr && !klass->IsPrimitive()) {
2167 CHECK(class_table->Contains(klass))
2168 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
2169 }
2170 }
2171 }
2172}
2173
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002174bool ClassLinker::AddImageSpace(
2175 gc::space::ImageSpace* space,
2176 Handle<mirror::ClassLoader> class_loader,
2177 jobjectArray dex_elements,
2178 const char* dex_location,
2179 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
2180 std::string* error_msg) {
2181 DCHECK(out_dex_files != nullptr);
2182 DCHECK(error_msg != nullptr);
2183 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08002184 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002185 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002186 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002187 DCHECK(dex_caches_object != nullptr);
2188 Runtime* const runtime = Runtime::Current();
2189 gc::Heap* const heap = runtime->GetHeap();
2190 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002191 // Check that the image is what we are expecting.
2192 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
2193 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
2194 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
2195 image_pointer_size_);
2196 return false;
2197 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002198 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
2199 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
2200 *error_msg = StringPrintf("Expected %zu image roots but got %d",
2201 expected_image_roots,
2202 header.GetImageRoots()->GetLength());
2203 return false;
2204 }
2205 StackHandleScope<3> hs(self);
2206 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
2207 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2208 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2209 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002210 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002211 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2212 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002213 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002214 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002215 *error_msg = StringPrintf("Expected %d class roots but got %d",
2216 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002217 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002218 return false;
2219 }
2220 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002221 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2222 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2223 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002224 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2225 return false;
2226 }
2227 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002228 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002229 if (oat_file->GetOatHeader().GetDexFileCount() !=
2230 static_cast<uint32_t>(dex_caches->GetLength())) {
2231 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2232 "image";
2233 return false;
2234 }
2235
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002236 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002237 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
David Brazdil3e8aae02019-03-26 18:48:02 +00002238 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Andreas Gamped5d807b2019-04-18 14:46:51 -07002239 if (class_loader == nullptr) {
2240 // For app images, we'll see the relative location. b/130666977.
2241 DCHECK_EQ(dex_location, DexFileLoader::GetBaseLocation(dex_file_location));
2242 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002243 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2244 dex_file_location.c_str(),
2245 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002246 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002247 return false;
2248 }
2249
2250 if (app_image) {
2251 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2252 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002253 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002254 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002255 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002256 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002257 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002258 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002259 }
2260 }
2261 } else {
2262 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002263 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2264 this,
2265 dex_cache->GetResolvedMethods(),
2266 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002267 }
2268 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002269 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002270 }
2271 out_dex_files->push_back(std::move(dex_file));
2272 }
2273
2274 if (app_image) {
2275 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002276 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002277 // Check that the class loader resolves the same way as the ones in the image.
2278 // Image class loader [A][B][C][image dex files]
2279 // Class loader = [???][dex_elements][image dex files]
2280 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002281 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002282 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2283 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2284 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002285 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2286 *error_msg = "Unexpected BootClassLoader in app image";
2287 return false;
2288 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002289 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2290 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2291 // special case the comparison of dex files of the two class loaders, but then do full
2292 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002293 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002294 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002295 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2296 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2297 if (element != nullptr) {
2298 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002299 ObjPtr<mirror::String> name;
2300 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2301 loader_dex_file_names.push_back(name);
2302 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002303 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002304 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002305 std::string temp_error_msg;
2306 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2307 bool success = GetDexFileNames(
2308 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2309 if (success) {
2310 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2311 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2312 static_cast<size_t>(dex_caches->GetLength()));
2313 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2314 image_dex_file_names.resize(image_count);
2315 success = success && CompareDexFiles(image_dex_file_names,
2316 loader_dex_file_names,
2317 &temp_error_msg);
2318 success = success && CompareClassLoaders(soa,
2319 image_class_loader.Get(),
2320 class_loader.Get(),
2321 /*check_dex_file_names=*/ false,
2322 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002323 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002324 if (!success) {
2325 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2326 temp_error_msg.c_str());
2327 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002328 }
2329 }
2330
2331 if (kSanityCheckObjects) {
2332 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002333 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002334 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2335 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2336 if (field != nullptr) {
2337 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2338 }
2339 }
2340 }
2341 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002342 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002343 }
2344 }
2345
2346 // Set entry point to interpreter if in InterpretOnly mode.
2347 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002348 // Set image methods' entry point to interpreter.
2349 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2350 if (!method.IsRuntimeMethod()) {
2351 DCHECK(method.GetDeclaringClass() != nullptr);
2352 if (!method.IsNative() && !method.IsResolutionMethod()) {
2353 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2354 image_pointer_size_);
2355 }
2356 }
2357 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002358 }
2359
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002360 ClassTable* class_table = nullptr;
2361 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002362 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002363 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002364 }
2365 // If we have a class table section, read it and use it for verification in
2366 // UpdateAppImageClassLoadersAndDexCaches.
2367 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002368 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002369 const bool added_class_table = class_table_section.Size() > 0u;
2370 if (added_class_table) {
2371 const uint64_t start_time2 = NanoTime();
2372 size_t read_count = 0;
2373 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2374 /*make copy*/false,
2375 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002376 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002377 }
2378 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002379 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002380
2381 {
2382 ScopedTrace trace("AppImage:UpdateClassLoaders");
2383 // Update class loader and resolved strings. If added_class_table is false, the resolved
2384 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002385 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002386 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002387 // Note: We probably don't need the read barrier unless we copy the app image objects into
2388 // the region space.
2389 ObjPtr<mirror::Class> klass(root.Read());
2390 // Do not update class loader for boot image classes where the app image
2391 // class loader is only the initiating loader but not the defining loader.
2392 // Avoid read barrier since we are comparing against null.
2393 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2394 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2395 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002396 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002397 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002398
Vladimir Marko305c38b2018-02-14 11:50:07 +00002399 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002400 // Every class in the app image has initially SubtypeCheckInfo in the
2401 // Uninitialized state.
2402 //
2403 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2404 // after class initialization is complete. The app image ClassStatus as-is
2405 // are almost all ClassStatus::Initialized, and being in the
2406 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2407 //
2408 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2409 //
2410 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002411 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002412 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2413 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002414 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002415 }
2416 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002417 }
2418 if (!oat_file->GetBssGcRoots().empty()) {
2419 // Insert oat file to class table for visiting .bss GC roots.
2420 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002421 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002422
Mathieu Chartier69731002016-03-02 16:08:31 -08002423 if (added_class_table) {
2424 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2425 class_table->AddClassSet(std::move(temp_set));
2426 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002427
Mathieu Chartier69731002016-03-02 16:08:31 -08002428 if (kIsDebugBuild && app_image) {
2429 // This verification needs to happen after the classes have been added to the class loader.
2430 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002431 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002432 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002433 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002434
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002435 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002436 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002437}
2438
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002439bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002440 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2441 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002442}
2443
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002444void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002445 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2446 // enabling tracing requires the mutator lock, there are no race conditions here.
2447 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002448 Thread* const self = Thread::Current();
2449 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002450 if (kUseReadBarrier) {
2451 // We do not track new roots for CC.
2452 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2453 kVisitRootFlagClearRootLog |
2454 kVisitRootFlagStartLoggingNewRoots |
2455 kVisitRootFlagStopLoggingNewRoots));
2456 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002457 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002458 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2459 // There is 3 GC cases to handle:
2460 // Non moving concurrent:
2461 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002462 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002463 //
2464 // Moving non-concurrent:
2465 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2466 // To prevent missing roots, this case needs to ensure that there is no
2467 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2468 // class which is in the class table.
2469 //
2470 // Moving concurrent:
2471 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2472 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002473 //
2474 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2475 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2476 // these objects.
2477 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002478 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002479 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002480 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002481 for (const ClassLoaderData& data : class_loaders_) {
2482 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2483 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2484 }
2485 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002486 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002487 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002488 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002489 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002490 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002491 // Concurrent moving GC marked new roots through the to-space invariant.
2492 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002493 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002494 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2495 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2496 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2497 if (old_ref != nullptr) {
2498 DCHECK(old_ref->IsClass());
2499 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2500 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2501 // Concurrent moving GC marked new roots through the to-space invariant.
2502 CHECK_EQ(new_ref, old_ref);
2503 }
2504 }
2505 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002506 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002507 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002508 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002509 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002510 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002511 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002512 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002513 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002514 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002515 }
2516 // We deliberately ignore the class roots in the image since we
2517 // handle image roots by using the MS/CMS rescanning of dirty cards.
2518}
2519
Brian Carlstroma663ea52011-08-19 23:33:41 -07002520// Keep in sync with InitCallback. Anything we visit, we need to
2521// reinit references to when reinitializing a ClassLinker from a
2522// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002523void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002524 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002525 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002526 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2527 // unloading if we are marking roots.
2528 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002529}
2530
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002531class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2532 public:
2533 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2534 : visitor_(visitor),
2535 done_(false) {}
2536
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002537 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002538 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002539 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002540 if (!done_ && class_table != nullptr) {
2541 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2542 if (!class_table->Visit(visitor)) {
2543 // If the visitor ClassTable returns false it means that we don't need to continue.
2544 done_ = true;
2545 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002546 }
2547 }
2548
2549 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002550 // Class visitor that limits the class visits from a ClassTable to the classes with
2551 // the provided defining class loader. This filter is used to avoid multiple visits
2552 // of the same class which can be recorded for multiple initiating class loaders.
2553 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2554 public:
2555 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2556 ClassVisitor* visitor)
2557 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2558
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002559 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002560 if (klass->GetClassLoader() != defining_class_loader_) {
2561 return true;
2562 }
2563 return (*visitor_)(klass);
2564 }
2565
Vladimir Marko0984e482019-03-27 16:41:41 +00002566 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002567 ClassVisitor* const visitor_;
2568 };
2569
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002570 ClassVisitor* const visitor_;
2571 // If done is true then we don't need to do any more visiting.
2572 bool done_;
2573};
2574
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002575void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002576 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002577 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2578 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002579 }
2580}
2581
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002582void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002583 Thread* const self = Thread::Current();
2584 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2585 // Not safe to have thread suspension when we are holding a lock.
2586 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002587 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002588 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002589 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002590 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002591 }
2592}
2593
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002594class GetClassesInToVector : public ClassVisitor {
2595 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002596 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002597 classes_.push_back(klass);
2598 return true;
2599 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002600 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002601};
2602
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002603class GetClassInToObjectArray : public ClassVisitor {
2604 public:
2605 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2606 : arr_(arr), index_(0) {}
2607
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002608 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002609 ++index_;
2610 if (index_ <= arr_->GetLength()) {
2611 arr_->Set(index_ - 1, klass);
2612 return true;
2613 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002614 return false;
2615 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002616
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002617 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002618 return index_ <= arr_->GetLength();
2619 }
2620
2621 private:
2622 mirror::ObjectArray<mirror::Class>* const arr_;
2623 int32_t index_;
2624};
2625
2626void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002627 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2628 // is avoiding duplicates.
2629 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002630 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002631 GetClassesInToVector accumulator;
2632 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002633 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002634 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002635 return;
2636 }
2637 }
2638 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002639 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002640 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002641 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002642 // We size the array assuming classes won't be added to the class table during the visit.
2643 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002644 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002645 size_t class_table_size;
2646 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002647 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002648 // Add 100 in case new classes get loaded when we are filling in the object array.
2649 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002650 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002651 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002652 classes.Assign(
2653 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002654 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002655 GetClassInToObjectArray accumulator(classes.Get());
2656 VisitClasses(&accumulator);
2657 if (accumulator.Succeeded()) {
2658 break;
2659 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002660 }
2661 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2662 // If the class table shrank during creation of the clases array we expect null elements. If
2663 // the class table grew then the loop repeats. If classes are created after the loop has
2664 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002665 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002666 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002667 return;
2668 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002669 }
2670 }
2671}
2672
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002673ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002674 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002675 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002676 // CHA unloading analysis is not needed. No negative consequences are expected because
2677 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002678 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002679 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002680 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002681 while (!running_visibly_initialized_callbacks_.empty()) {
2682 std::unique_ptr<VisiblyInitializedCallback> callback(
2683 std::addressof(running_visibly_initialized_callbacks_.front()));
2684 running_visibly_initialized_callbacks_.pop_front();
2685 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002686}
2687
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002688void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002689 Runtime* const runtime = Runtime::Current();
2690 JavaVMExt* const vm = runtime->GetJavaVM();
2691 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002692 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002693 if (runtime->GetJit() != nullptr) {
2694 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2695 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002696 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002697 code_cache->RemoveMethodsIn(self, *data.allocator);
2698 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002699 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002700 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002701 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002702 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002703 // Cleanup references to single implementation ArtMethods that will be deleted.
2704 if (cleanup_cha) {
2705 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2706 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2707 }
2708
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002709 delete data.allocator;
2710 delete data.class_table;
2711}
2712
Vladimir Markobcf17522018-06-01 13:14:32 +01002713ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2714 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002715 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002716 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2717 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002718}
2719
Vladimir Markobcf17522018-06-01 13:14:32 +01002720ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2721 Thread* self,
2722 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002723 StackHandleScope<1> hs(self);
2724 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002725 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002726 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002727 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002728 self->AssertPendingOOMException();
2729 return nullptr;
2730 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002731 // Use InternWeak() so that the location String can be collected when the ClassLoader
2732 // with this DexCache is collected.
2733 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002734 if (location == nullptr) {
2735 self->AssertPendingOOMException();
2736 return nullptr;
2737 }
2738 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002739 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002740}
2741
Vladimir Markobcf17522018-06-01 13:14:32 +01002742ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2743 const DexFile& dex_file,
2744 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002745 ObjPtr<mirror::String> location = nullptr;
2746 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002747 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002748 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002749 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002750 mirror::DexCache::InitializeDexCache(self,
2751 dex_cache,
2752 location,
2753 &dex_file,
2754 linear_alloc,
2755 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002756 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002757 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002758}
2759
Vladimir Marko70e2a762019-07-12 16:49:00 +01002760template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002761ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2762 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002763 uint32_t class_size,
2764 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002765 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002766 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002767 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002768 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2769 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002770 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002771 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002772 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002773 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002774 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002775}
2776
Vladimir Marko70e2a762019-07-12 16:49:00 +01002777template <bool kMovable>
2778ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2779 ObjPtr<mirror::Class> java_lang_Class,
2780 uint32_t class_size) {
2781 mirror::Class::InitializeClassVisitor visitor(class_size);
2782 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2783}
2784
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002785ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002786 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002787}
2788
Vladimir Marko70e2a762019-07-12 16:49:00 +01002789void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2790 ClassRoot primitive_root,
2791 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002792 // We make this class non-movable for the unlikely case where it were to be
2793 // moved by a sticky-bit (minor) collection when using the Generational
2794 // Concurrent Copying (CC) collector, potentially creating a stale reference
2795 // in the `klass_` field of one of its instances allocated in the Large-Object
2796 // Space (LOS) -- see the comment about the dirty card scanning logic in
2797 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002798 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2799 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2800 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2801 DCHECK(component_type->IsPrimitive());
2802 array_class->SetComponentType(component_type);
2803 SetClassRoot(array_root, array_class);
2804}
2805
2806void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2807 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2808 array_class->SetSuperClass(java_lang_Object);
2809 array_class->SetVTable(java_lang_Object->GetVTable());
2810 array_class->SetPrimitiveType(Primitive::kPrimNot);
2811 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2812 array_class->SetClassFlags(component_type->IsPrimitive()
2813 ? mirror::kClassFlagNoReferenceFields
2814 : mirror::kClassFlagObjectArray);
2815 array_class->SetClassLoader(component_type->GetClassLoader());
2816 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2817 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2818 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2819 array_class->SetImt(object_imt, image_pointer_size_);
2820 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2821 // the kAccVerificationAttempted flag is added below, and there are no
2822 // methods that need the kAccSkipAccessChecks flag.
2823 DCHECK_EQ(array_class->NumMethods(), 0u);
2824
2825 // don't need to set new_class->SetObjectSize(..)
2826 // because Object::SizeOf delegates to Array::SizeOf
2827
2828 // All arrays have java/lang/Cloneable and java/io/Serializable as
2829 // interfaces. We need to set that up here, so that stuff like
2830 // "instanceof" works right.
2831
2832 // Use the single, global copies of "interfaces" and "iftable"
2833 // (remember not to free them for arrays).
2834 {
2835 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2836 CHECK(array_iftable != nullptr);
2837 array_class->SetIfTable(array_iftable);
2838 }
2839
2840 // Inherit access flags from the component type.
2841 int access_flags = component_type->GetAccessFlags();
2842 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2843 access_flags &= kAccJavaFlagsMask;
2844 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2845 // and remove "interface".
2846 access_flags |= kAccAbstract | kAccFinal;
2847 access_flags &= ~kAccInterface;
2848 // Arrays are access-checks-clean and preverified.
2849 access_flags |= kAccVerificationAttempted;
2850
2851 array_class->SetAccessFlags(access_flags);
2852
Vladimir Markobf121912019-06-04 13:49:05 +01002853 // Array classes are fully initialized either during single threaded startup,
2854 // or from a pre-fence visitor, so visibly initialized.
2855 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002856}
2857
2858void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2859 // Do not hold lock on the array class object, the initialization of
2860 // core array classes is done while the process is still single threaded.
2861 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2862 FinishArrayClassSetup(array_class);
2863
2864 std::string temp;
2865 const char* descriptor = array_class->GetDescriptor(&temp);
2866 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2867 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2868 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002869}
2870
Vladimir Markobcf17522018-06-01 13:14:32 +01002871ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002872 Thread* self,
2873 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002874 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002875 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002876}
2877
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002878ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2879 const char* descriptor,
2880 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002881 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002882 if (kIsDebugBuild) {
2883 StackHandleScope<1> hs(self);
2884 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2885 Thread::PoisonObjectPointersIfDebug();
2886 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002887
2888 // For temporary classes we must wait for them to be retired.
2889 if (init_done_ && klass->IsTemp()) {
2890 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002891 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002892 ThrowEarlierClassFailure(klass);
2893 return nullptr;
2894 }
2895 StackHandleScope<1> hs(self);
2896 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2897 ObjectLock<mirror::Class> lock(self, h_class);
2898 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002899 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002900 lock.WaitIgnoringInterrupts();
2901 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002902 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002903 ThrowEarlierClassFailure(h_class.Get());
2904 return nullptr;
2905 }
2906 CHECK(h_class->IsRetired());
2907 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002908 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002909 }
2910
Brian Carlstromaded5f72011-10-07 17:15:04 -07002911 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002912 size_t index = 0;
2913 // Maximum number of yield iterations until we start sleeping.
2914 static const size_t kNumYieldIterations = 1000;
2915 // How long each sleep is in us.
2916 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002917 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002918 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002919 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002920 {
2921 ObjectTryLock<mirror::Class> lock(self, h_class);
2922 // Can not use a monitor wait here since it may block when returning and deadlock if another
2923 // thread has locked klass.
2924 if (lock.Acquired()) {
2925 // Check for circular dependencies between classes, the lock is required for SetStatus.
2926 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2927 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002928 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002929 return nullptr;
2930 }
2931 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002932 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002933 {
2934 // Handle wrapper deals with klass moving.
2935 ScopedThreadSuspension sts(self, kSuspended);
2936 if (index < kNumYieldIterations) {
2937 sched_yield();
2938 } else {
2939 usleep(kSleepDurationUS);
2940 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002941 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002942 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002943 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002944
Vladimir Marko72ab6842017-01-20 19:32:50 +00002945 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002946 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002947 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002948 }
2949 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002950 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002951 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002952 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002953}
2954
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002955using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002956
2957// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002958ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002959 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002960 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002961 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002962 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002963 return ClassPathEntry(dex_file, dex_class_def);
2964 }
2965 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002966 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002967}
2968
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002969bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2970 Thread* self,
2971 const char* descriptor,
2972 size_t hash,
2973 Handle<mirror::ClassLoader> class_loader,
2974 /*out*/ ObjPtr<mirror::Class>* result) {
2975 ArtField* field =
2976 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2977 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2978 if (raw_shared_libraries == nullptr) {
2979 return true;
2980 }
2981
2982 StackHandleScope<2> hs(self);
2983 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2984 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2985 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2986 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2987 temp_loader.Assign(shared_libraries->Get(i));
2988 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2989 return false; // One of the shared libraries is not supported.
2990 }
2991 if (*result != nullptr) {
2992 return true; // Found the class up the chain.
2993 }
2994 }
2995 return true;
2996}
2997
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002998bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2999 Thread* self,
3000 const char* descriptor,
3001 size_t hash,
3002 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01003003 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07003004 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07003005 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07003006 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07003007 return true;
3008 }
3009
David Brazdil05909d82018-12-06 16:25:16 +00003010 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07003011 // For regular path or dex class loader the search order is:
3012 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003013 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07003014 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07003015
Calin Juravlecdd49122017-07-05 20:09:53 -07003016 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
3017 StackHandleScope<1> hs(self);
3018 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
3019 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
3020 return false; // One of the parents is not supported.
3021 }
3022 if (*result != nullptr) {
3023 return true; // Found the class up the chain.
3024 }
Andreas Gampef865ea92015-04-13 22:14:19 -07003025
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003026 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
3027 return false; // One of the shared library loader is not supported.
3028 }
3029 if (*result != nullptr) {
3030 return true; // Found the class in a shared library.
3031 }
3032
Calin Juravlecdd49122017-07-05 20:09:53 -07003033 // Search the current class loader classpath.
3034 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00003035 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07003036 }
3037
Calin Juravlecdd49122017-07-05 20:09:53 -07003038 if (IsDelegateLastClassLoader(soa, class_loader)) {
3039 // For delegate last, the search order is:
3040 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003041 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07003042 // - class loader dex files
3043 // - parent
3044 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
3045 if (*result != nullptr) {
3046 return true; // The class is part of the boot class path.
3047 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003048 if (self->IsExceptionPending()) {
3049 // Pending exception means there was an error other than ClassNotFound that must be returned
3050 // to the caller.
3051 return false;
3052 }
Calin Juravlecdd49122017-07-05 20:09:53 -07003053
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01003054 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
3055 return false; // One of the shared library loader is not supported.
3056 }
3057 if (*result != nullptr) {
3058 return true; // Found the class in a shared library.
3059 }
3060
Calin Juravlecdd49122017-07-05 20:09:53 -07003061 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
3062 if (*result != nullptr) {
3063 return true; // Found the class in the current class loader
3064 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003065 if (self->IsExceptionPending()) {
3066 // Pending exception means there was an error other than ClassNotFound that must be returned
3067 // to the caller.
3068 return false;
3069 }
Calin Juravlecdd49122017-07-05 20:09:53 -07003070
3071 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
3072 StackHandleScope<1> hs(self);
3073 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
3074 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
3075 }
3076
3077 // Unsupported class loader.
3078 *result = nullptr;
3079 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07003080}
3081
Andreas Gampe501c3b02019-04-17 21:54:27 +00003082namespace {
3083
3084// Matches exceptions caught in DexFile.defineClass.
3085ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
3086 ClassLinker* class_linker)
3087 REQUIRES_SHARED(Locks::mutator_lock_) {
3088 return
3089 // ClassNotFoundException.
3090 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
3091 class_linker))
3092 ||
3093 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
3094 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
3095}
3096
3097// Clear exceptions caught in DexFile.defineClass.
3098ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
3099 REQUIRES_SHARED(Locks::mutator_lock_) {
3100 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
3101 self->ClearException();
3102 }
3103}
3104
3105} // namespace
3106
Calin Juravle415dc3d2017-06-28 11:03:12 -07003107// Finds the class in the boot class loader.
3108// If the class is found the method returns the resolved class. Otherwise it returns null.
3109ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
3110 const char* descriptor,
3111 size_t hash) {
3112 ObjPtr<mirror::Class> result = nullptr;
3113 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
3114 if (pair.second != nullptr) {
3115 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
3116 if (klass != nullptr) {
3117 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003118 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07003119 result = DefineClass(self,
3120 descriptor,
3121 hash,
3122 ScopedNullHandle<mirror::ClassLoader>(),
3123 *pair.first,
3124 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003125 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07003126 if (result == nullptr) {
3127 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003128 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07003129 }
3130 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07003131 return result;
3132}
Andreas Gampef865ea92015-04-13 22:14:19 -07003133
Calin Juravle415dc3d2017-06-28 11:03:12 -07003134ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
3135 ScopedObjectAccessAlreadyRunnable& soa,
3136 const char* descriptor,
3137 size_t hash,
3138 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00003139 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
3140 IsInMemoryDexClassLoader(soa, class_loader) ||
3141 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07003142 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07003143
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003144 ObjPtr<mirror::Class> ret;
3145 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003146 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003147 if (dex_class_def != nullptr) {
3148 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
3149 descriptor,
3150 hash,
3151 class_loader,
3152 *cp_dex_file,
3153 *dex_class_def);
3154 if (klass == nullptr) {
3155 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003156 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003157 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00003158 } else {
3159 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003160 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003161 ret = klass;
3162 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003163 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08003164 return true; // Continue with the next DexFile.
3165 };
3166
3167 VisitClassLoaderDexFiles(soa, class_loader, define_class);
3168 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07003169}
3170
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003171ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
3172 const char* descriptor,
3173 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08003174 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08003175 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003176 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07003177 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003178 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003179 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
3180 // for primitive classes that aren't backed by dex files.
3181 return FindPrimitiveClass(descriptor[0]);
3182 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003183 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003184 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003185 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07003186 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003187 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003188 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003189 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003190 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003191 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003192 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07003193 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08003194 return DefineClass(self,
3195 descriptor,
3196 hash,
3197 ScopedNullHandle<mirror::ClassLoader>(),
3198 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07003199 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07003200 } else {
3201 // The boot class loader is searched ahead of the application class loader, failures are
3202 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
3203 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003204 ObjPtr<mirror::Throwable> pre_allocated =
3205 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003206 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07003207 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05003208 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003209 }
3210 ObjPtr<mirror::Class> result_ptr;
3211 bool descriptor_equals;
3212 if (descriptor[0] == '[') {
3213 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
3214 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
3215 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
3216 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05003217 } else {
Ian Rogers98379392014-02-24 16:53:16 -08003218 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003219 bool known_hierarchy =
3220 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
3221 if (result_ptr != nullptr) {
3222 // The chain was understood and we found the class. We still need to add the class to
3223 // the class table to protect from racy programs that can try and redefine the path list
3224 // which would change the Class<?> returned for subsequent evaluation of const-class.
3225 DCHECK(known_hierarchy);
3226 DCHECK(result_ptr->DescriptorEquals(descriptor));
3227 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00003228 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003229 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00003230 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
3231 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003232 //
3233 // If the chain was understood but we did not find the class, let the Java-side
3234 // rediscover all this and throw the exception with the right stack trace. Note that
3235 // the Java-side could still succeed for racy programs if another thread is actively
3236 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07003237
Alex Light185a4612018-10-04 15:54:25 -07003238 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07003239 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00003240 // Oops, we can't call into java so we can't run actual class-loader code.
3241 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003242 ObjPtr<mirror::Throwable> pre_allocated =
3243 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3244 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003245 return nullptr;
3246 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003247
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003248 // Inlined DescriptorToDot(descriptor) with extra validation.
3249 //
3250 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
3251 // the DescriptorEquals() check below and give a confusing error message. For example,
3252 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
3253 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
3254 // "class loader [...] returned class java.lang.String instead of java.lang.String".
3255 size_t descriptor_length = strlen(descriptor);
3256 if (UNLIKELY(descriptor[0] != 'L') ||
3257 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
3258 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
3259 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
3260 return nullptr;
3261 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003262
Vladimir Marko5fdd7782017-04-20 11:26:03 +01003263 std::string class_name_string(descriptor + 1, descriptor_length - 2);
3264 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00003265 if (known_hierarchy &&
3266 fast_class_not_found_exceptions_ &&
3267 !Runtime::Current()->IsJavaDebuggable()) {
3268 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
3269 // debuggable, optimize this path by throwing directly here without going back to Java
3270 // language. This reduces how many ClassNotFoundExceptions happen.
3271 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
3272 "%s",
3273 class_name_string.c_str());
3274 } else {
3275 ScopedLocalRef<jobject> class_loader_object(
3276 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
3277 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
3278 {
3279 ScopedThreadStateChange tsc(self, kNative);
3280 ScopedLocalRef<jobject> class_name_object(
3281 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
3282 if (class_name_object.get() == nullptr) {
3283 DCHECK(self->IsExceptionPending()); // OOME.
3284 return nullptr;
3285 }
3286 CHECK(class_loader_object.get() != nullptr);
3287 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
3288 WellKnownClasses::java_lang_ClassLoader_loadClass,
3289 class_name_object.get()));
3290 }
3291 if (result.get() == nullptr && !self->IsExceptionPending()) {
3292 // broken loader - throw NPE to be compatible with Dalvik
3293 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
3294 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003295 return nullptr;
3296 }
Andreas Gampe87658f32019-04-18 18:39:02 +00003297 result_ptr = soa.Decode<mirror::Class>(result.get());
3298 // Check the name of the returned class.
3299 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003300 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003301 } else {
3302 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003303 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003304 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003305
3306 if (self->IsExceptionPending()) {
3307 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3308 // However, to comply with the RI behavior, first check if another thread succeeded.
3309 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3310 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3311 self->ClearException();
3312 return EnsureResolved(self, descriptor, result_ptr);
3313 }
3314 return nullptr;
3315 }
3316
3317 // Try to insert the class to the class table, checking for mismatch.
3318 ObjPtr<mirror::Class> old;
3319 {
3320 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3321 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3322 old = class_table->Lookup(descriptor, hash);
3323 if (old == nullptr) {
3324 old = result_ptr; // For the comparison below, after releasing the lock.
3325 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003326 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003327 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003328 } // else throw below, after releasing the lock.
3329 }
3330 }
3331 if (UNLIKELY(old != result_ptr)) {
3332 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3333 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003334 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003335 const char* loader_class_name =
3336 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3337 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3338 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3339 << DescriptorToDot(descriptor) << "\").";
3340 return EnsureResolved(self, descriptor, old);
3341 }
3342 if (UNLIKELY(!descriptor_equals)) {
3343 std::string result_storage;
3344 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3345 std::string loader_storage;
3346 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3347 ThrowNoClassDefFoundError(
3348 "Initiating class loader of type %s returned class %s instead of %s.",
3349 DescriptorToDot(loader_class_name).c_str(),
3350 DescriptorToDot(result_name).c_str(),
3351 DescriptorToDot(descriptor).c_str());
3352 return nullptr;
3353 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003354 // Success.
3355 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003356}
3357
Vladimir Markob9c29f62019-03-20 14:22:51 +00003358static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3359 std::string_view descriptor_sv(descriptor);
Vladimir Marko29885b32019-04-03 10:09:26 +01003360 return
3361 // Reserved conscrypt packages (includes sub-packages under these paths).
3362 StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3363 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/") ||
3364 // Reserved updatable-media package (includes sub-packages under this path).
3365 StartsWith(descriptor_sv, "Landroid/media/");
Vladimir Markob9c29f62019-03-20 14:22:51 +00003366}
3367
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003368ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3369 const char* descriptor,
3370 size_t hash,
3371 Handle<mirror::ClassLoader> class_loader,
3372 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003373 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003374 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003375 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003376
Brian Carlstromaded5f72011-10-07 17:15:04 -07003377 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003378 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003379 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003380 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003381 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003382 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003383 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003384 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003385 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003386 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003387 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003388 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003389 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003390 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003391 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003392 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003393 }
3394
Vladimir Markob9c29f62019-03-20 14:22:51 +00003395 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3396 // some runtime modules. Prevent definition of classes in app class loader that could clash
3397 // with these modules as these classes could be resolved differently during execution.
3398 if (class_loader != nullptr &&
3399 Runtime::Current()->IsAotCompiler() &&
3400 IsReservedBootClassPathDescriptor(descriptor)) {
3401 ObjPtr<mirror::Throwable> pre_allocated =
3402 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3403 self->SetException(pre_allocated);
3404 return nullptr;
3405 }
3406
Alex Lighte9f61032018-09-24 16:04:51 -07003407 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3408 // code to be executed. We put it up here so we can avoid all the allocations associated with
3409 // creating the class. This can happen with (eg) jit threads.
3410 if (!self->CanLoadClasses()) {
3411 // Make sure we don't try to load anything, potentially causing an infinite loop.
3412 ObjPtr<mirror::Throwable> pre_allocated =
3413 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3414 self->SetException(pre_allocated);
3415 return nullptr;
3416 }
3417
Andreas Gampefa4333d2017-02-14 11:10:34 -08003418 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003419 // Allocate a class with the status of not ready.
3420 // Interface object should get the right size here. Regular class will
3421 // figure out the right size later and be replaced with one of the right
3422 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003423 if (CanAllocClass()) {
3424 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3425 } else {
3426 return nullptr;
3427 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003428 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003429 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003430 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003431 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003432 }
Alex Lightb0f11922017-01-23 14:25:17 -08003433 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3434 // nothing.
3435 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003436 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003437 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3438 // will only be called once.
3439 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3440 klass,
3441 class_loader,
3442 dex_file,
3443 dex_class_def,
3444 &new_dex_file,
3445 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003446 // Check to see if an exception happened during runtime callbacks. Return if so.
3447 if (self->IsExceptionPending()) {
3448 return nullptr;
3449 }
Alex Lightb0f11922017-01-23 14:25:17 -08003450 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003451 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003452 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003453 return nullptr;
3454 }
3455 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003456 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003457
Jeff Hao848f70a2014-01-15 13:49:50 -08003458 // Mark the string class by setting its access flag.
3459 if (UNLIKELY(!init_done_)) {
3460 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3461 klass->SetStringClass();
3462 }
3463 }
3464
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003465 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003466 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003467 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003468 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003469
Mathieu Chartier590fee92013-09-13 13:46:47 -07003470 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003471 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003472 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003473 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3474 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003475 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003476 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003477
Mathieu Chartierc7853442015-03-27 14:35:38 -07003478 // Load the fields and other things after we are inserted in the table. This is so that we don't
3479 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3480 // other reason is that the field roots are only visited from the class table. So we need to be
3481 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003482 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003483 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003484 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003485 // An exception occured during load, set status to erroneous while holding klass' lock in case
3486 // notification is necessary.
3487 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003488 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003489 }
3490 return nullptr;
3491 }
3492
Brian Carlstromaded5f72011-10-07 17:15:04 -07003493 // Finish loading (if necessary) by finding parents
3494 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003495 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003496 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003497 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003498 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003499 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003500 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003501 }
3502 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003503
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003504 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003505 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003506 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003507
Brian Carlstromaded5f72011-10-07 17:15:04 -07003508 // Link the class (if necessary)
3509 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003510 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003511 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003512
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003513 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003514 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003515 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003516 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003517 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003518 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003519 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003520 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003521 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003522 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003523 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003524
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003525 // Instrumentation may have updated entrypoints for all methods of all
3526 // classes. However it could not update methods of this class while we
3527 // were loading it. Now the class is resolved, we can update entrypoints
3528 // as required by instrumentation.
3529 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3530 // We must be in the kRunnable state to prevent instrumentation from
3531 // suspending all threads to update entrypoints while we are doing it
3532 // for this class.
3533 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003534 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003535 }
3536
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003537 /*
3538 * We send CLASS_PREPARE events to the debugger from here. The
3539 * definition of "preparation" is creating the static fields for a
3540 * class and initializing them to the standard default values, but not
3541 * executing any code (that comes later, during "initialization").
3542 *
3543 * We did the static preparation in LinkClass.
3544 *
3545 * The class has been prepared and resolved but possibly not yet verified
3546 * at this point.
3547 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003548 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003549
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003550 // Notify native debugger of the new class and its layout.
3551 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3552
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003553 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003554}
3555
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003556uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003557 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003558 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003559 size_t num_8 = 0;
3560 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003561 size_t num_32 = 0;
3562 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003563 ClassAccessor accessor(dex_file, dex_class_def);
3564 // We allow duplicate definitions of the same field in a class_data_item
3565 // but ignore the repeated indexes here, b/21868015.
3566 uint32_t last_field_idx = dex::kDexNoIndex;
3567 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3568 uint32_t field_idx = field.GetIndex();
3569 // Ordering enforced by DexFileVerifier.
3570 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3571 if (UNLIKELY(field_idx == last_field_idx)) {
3572 continue;
3573 }
3574 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003575 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003576 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3577 char c = descriptor[0];
3578 switch (c) {
3579 case 'L':
3580 case '[':
3581 num_ref++;
3582 break;
3583 case 'J':
3584 case 'D':
3585 num_64++;
3586 break;
3587 case 'I':
3588 case 'F':
3589 num_32++;
3590 break;
3591 case 'S':
3592 case 'C':
3593 num_16++;
3594 break;
3595 case 'B':
3596 case 'Z':
3597 num_8++;
3598 break;
3599 default:
3600 LOG(FATAL) << "Unknown descriptor: " << c;
3601 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003602 }
3603 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003604 return mirror::Class::ComputeClassSize(false,
3605 0,
3606 num_8,
3607 num_16,
3608 num_32,
3609 num_64,
3610 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003611 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003612}
3613
Alex Lightfc49fec2018-01-16 22:28:36 +00003614// Special case to get oat code without overwriting a trampoline.
3615const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003616 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003617 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003618 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003619 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003620 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003621 if (code != nullptr) {
3622 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003623 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003624
3625 jit::Jit* jit = Runtime::Current()->GetJit();
3626 if (jit != nullptr) {
3627 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3628 if (code != nullptr) {
3629 return code;
3630 }
3631 }
3632
Alex Lightfc49fec2018-01-16 22:28:36 +00003633 if (method->IsNative()) {
3634 // No code and native? Use generic trampoline.
3635 return GetQuickGenericJniStub();
3636 }
3637 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003638}
3639
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003640bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003641 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003642 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3643 return false;
3644 }
3645
Elliott Hughes956af0f2014-12-11 14:34:28 -08003646 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003647 return true;
3648 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003649
3650 Runtime* runtime = Runtime::Current();
3651 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3652 if (instr->InterpretOnly()) {
3653 return true;
3654 }
3655
3656 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3657 // Doing this check avoids doing compiled/interpreter transitions.
3658 return true;
3659 }
3660
Alex Light3dacdd62019-03-12 15:45:47 +00003661 if (Thread::Current()->IsForceInterpreter() ||
3662 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003663 // Force the use of interpreter when it is required by the debugger.
3664 return true;
3665 }
3666
Alex Light8f34aba2017-10-09 13:46:32 -07003667 if (Thread::Current()->IsAsyncExceptionPending()) {
3668 // Force use of interpreter to handle async-exceptions
3669 return true;
3670 }
3671
Alex Light2d441b12018-06-08 15:33:21 -07003672 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3673 const void* instr_target = instr->GetCodeForInvoke(method);
3674 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3675 return ShouldUseInterpreterEntrypoint(method, instr_target);
3676 }
3677
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003678 if (runtime->IsJavaDebuggable()) {
3679 // For simplicity, we ignore precompiled code and go to the interpreter
3680 // assuming we don't already have jitted code.
3681 // We could look at the oat file where `quick_code` is being defined,
3682 // and check whether it's been compiled debuggable, but we decided to
3683 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003684 jit::Jit* jit = Runtime::Current()->GetJit();
3685 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3686 }
3687
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003688 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003689 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003690 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003691 // since we want to JIT it (at first use) with extra stackmaps for native
3692 // debugging. We keep however all AOT code from the boot image,
3693 // since the JIT-at-first-use is blocking and would result in non-negligible
3694 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003695 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003696 }
3697
3698 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003699}
3700
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003701void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003702 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003703 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003704 if (klass->NumDirectMethods() == 0) {
3705 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003706 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003707 if (UNLIKELY(klass->IsProxyClass())) {
3708 return;
3709 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003710 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003711 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003712 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003713 return; // OAT file unavailable.
3714 }
Ian Rogers19846512012-02-24 11:42:47 -08003715 }
Alex Light64ad14d2014-08-19 14:23:13 -07003716
Mathieu Chartierf8322842014-05-16 10:59:25 -07003717 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003718 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3719 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3720 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003721 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003722 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003723 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003724 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3725 klass->GetDexClassDefIndex(),
3726 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003727 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003728 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003729 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003730 if (!method->IsStatic()) {
3731 // Only update static methods.
3732 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003733 }
Nicolas Geoffray5a0b6722019-09-24 15:09:40 +01003734 if (!IsQuickResolutionStub(method->GetEntryPointFromQuickCompiledCode())) {
3735 // Only update methods whose entrypoint is the resolution stub.
3736 continue;
3737 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003738 const void* quick_code = nullptr;
3739 if (has_oat_class) {
3740 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003741 quick_code = oat_method.GetQuickCode();
3742 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003743 // Check if we have JIT compiled code for it.
Vladimir Markocce414f2019-10-07 08:51:33 +01003744 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003745 if (quick_code == nullptr && jit != nullptr) {
3746 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003747 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003748 // Check whether the method is native, in which case it's generic JNI.
3749 if (quick_code == nullptr && method->IsNative()) {
3750 quick_code = GetQuickGenericJniStub();
3751 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003752 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003753 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003754 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003755 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003756 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003757 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003758}
3759
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003760// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3761// method. Should only be called on non-invokable methods.
3762inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003763 DCHECK(method != nullptr);
3764 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003765 method->SetEntryPointFromQuickCompiledCodePtrSize(
3766 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3767 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003768}
3769
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003770static void LinkCode(ClassLinker* class_linker,
3771 ArtMethod* method,
3772 const OatFile::OatClass* oat_class,
3773 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003774 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003775 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003776 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003777 // The following code only applies to a non-compiler runtime.
3778 return;
3779 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003780
Ian Rogers62d6c772013-02-27 08:32:07 -08003781 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003782 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003783
Alex Light9139e002015-10-09 15:59:48 -07003784 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003785 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003786 return;
3787 }
Ian Rogers19846512012-02-24 11:42:47 -08003788
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003789 const void* quick_code = nullptr;
3790 if (oat_class != nullptr) {
3791 // Every kind of method should at least get an invoke stub from the oat_method.
3792 // non-abstract methods also get their code pointers.
3793 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3794 quick_code = oat_method.GetQuickCode();
3795 }
3796
3797 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3798
3799 // Note: this mimics the logic in image_writer.cc that installs the resolution
3800 // stub only if we have compiled code and the method needs a class initialization
3801 // check.
3802 if (quick_code == nullptr) {
3803 method->SetEntryPointFromQuickCompiledCode(
3804 method->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge());
3805 } else if (enter_interpreter) {
3806 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003807 } else if (NeedsClinitCheckBeforeCall(method)) {
3808 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3809 // If we do have code but the method needs a class initialization check before calling
3810 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003811 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3812 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003813 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003814 } else {
3815 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003816 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003817
Ian Rogers62d6c772013-02-27 08:32:07 -08003818 if (method->IsNative()) {
3819 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003820 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003821
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003822 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003823 // We have a native method here without code. Then it should have the generic JNI
3824 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003825 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003826 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003827 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003828 }
3829}
3830
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003831void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003832 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003833 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003834 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003835 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003836 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003837 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003838 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003839 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003840
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003841 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003842 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003843 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003844 klass->SetAccessFlags(access_flags);
3845 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003846 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003847 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003848
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003849 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003850 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003851}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003852
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003853LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3854 LinearAlloc* allocator,
3855 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003856 if (length == 0) {
3857 return nullptr;
3858 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003859 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3860 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3861 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003862 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003863 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003864 CHECK(ret != nullptr);
3865 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3866 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003867}
3868
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003869LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3870 LinearAlloc* allocator,
3871 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003872 if (length == 0) {
3873 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003874 }
Vladimir Marko14632852015-08-17 12:07:23 +01003875 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3876 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003877 const size_t storage_size =
3878 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003879 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003880 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003881 CHECK(ret != nullptr);
3882 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003883 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003884 }
3885 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003886}
3887
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003888LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003889 if (class_loader == nullptr) {
3890 return Runtime::Current()->GetLinearAlloc();
3891 }
3892 LinearAlloc* allocator = class_loader->GetAllocator();
3893 DCHECK(allocator != nullptr);
3894 return allocator;
3895}
3896
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003897LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003898 if (class_loader == nullptr) {
3899 return Runtime::Current()->GetLinearAlloc();
3900 }
3901 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3902 LinearAlloc* allocator = class_loader->GetAllocator();
3903 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003904 RegisterClassLoader(class_loader);
3905 allocator = class_loader->GetAllocator();
3906 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003907 }
3908 return allocator;
3909}
3910
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003911void ClassLinker::LoadClass(Thread* self,
3912 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003913 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003914 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003915 ClassAccessor accessor(dex_file,
3916 dex_class_def,
3917 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003918 if (!accessor.HasClassData()) {
3919 return;
3920 }
3921 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003922 {
3923 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3924 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003925 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003926 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003927 // We allow duplicate definitions of the same field in a class_data_item
3928 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003929 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003930 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3931 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003932 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003933 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3934 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003935 accessor.NumInstanceFields());
3936 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003937 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003938 uint32_t last_static_field_idx = 0u;
3939 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003940
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003941 // Methods
3942 bool has_oat_class = false;
3943 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3944 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3945 : OatFile::OatClass::Invalid();
3946 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3947 klass->SetMethodsPtr(
3948 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3949 accessor.NumDirectMethods(),
3950 accessor.NumVirtualMethods());
3951 size_t class_def_method_index = 0;
3952 uint32_t last_dex_method_index = dex::kDexNoIndex;
3953 size_t last_class_def_method_index = 0;
3954
3955 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3956 // methods needs to decode all of the fields.
3957 accessor.VisitFieldsAndMethods([&](
3958 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3959 uint32_t field_idx = field.GetIndex();
3960 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3961 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3962 LoadField(field, klass, &sfields->At(num_sfields));
3963 ++num_sfields;
3964 last_static_field_idx = field_idx;
3965 }
3966 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3967 uint32_t field_idx = field.GetIndex();
3968 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3969 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3970 LoadField(field, klass, &ifields->At(num_ifields));
3971 ++num_ifields;
3972 last_instance_field_idx = field_idx;
3973 }
3974 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3975 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3976 image_pointer_size_);
3977 LoadMethod(dex_file, method, klass, art_method);
3978 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3979 uint32_t it_method_index = method.GetIndex();
3980 if (last_dex_method_index == it_method_index) {
3981 // duplicate case
3982 art_method->SetMethodIndex(last_class_def_method_index);
3983 } else {
3984 art_method->SetMethodIndex(class_def_method_index);
3985 last_dex_method_index = it_method_index;
3986 last_class_def_method_index = class_def_method_index;
3987 }
3988 ++class_def_method_index;
3989 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3990 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3991 class_def_method_index - accessor.NumDirectMethods(),
3992 image_pointer_size_);
3993 LoadMethod(dex_file, method, klass, art_method);
3994 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3995 ++class_def_method_index;
3996 });
3997
3998 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003999 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004000 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
4001 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
4002 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00004003 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
4004 if (sfields != nullptr) {
4005 sfields->SetSize(num_sfields);
4006 }
4007 if (ifields != nullptr) {
4008 ifields->SetSize(num_ifields);
4009 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004010 }
Vladimir Marko81819db2015-11-05 15:30:12 +00004011 // Set the field arrays.
4012 klass->SetSFieldsPtr(sfields);
4013 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004014 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004015 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07004016 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07004017 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004018 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07004019 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07004020}
4021
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004022void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004023 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07004024 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004025 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004026 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004027 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00004028
David Brazdil85865692018-10-30 17:26:20 +00004029 // Get access flags from the DexFile and set hiddenapi runtime access flags.
4030 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07004031}
4032
Mathieu Chartier268764d2016-09-13 12:09:38 -07004033void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004034 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004035 Handle<mirror::Class> klass,
4036 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004037 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004038 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07004039 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07004040
Mathieu Chartier268764d2016-09-13 12:09:38 -07004041 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07004042 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004043 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07004044 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07004045
David Brazdil85865692018-10-30 17:26:20 +00004046 // Get access flags from the DexFile and set hiddenapi runtime access flags.
4047 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00004048
Ian Rogersdfb325e2013-10-30 01:00:44 -07004049 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07004050 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004051 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
4052 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004053 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004054 klass->SetFinalizable();
4055 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004056 std::string temp;
4057 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07004058 // The Enum class declares a "final" finalize() method to prevent subclasses from
4059 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
4060 // subclasses, so we exclude it here.
4061 // We also want to avoid setting the flag on Object, where we know that finalize() is
4062 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07004063 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
4064 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07004065 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07004066 }
4067 }
4068 }
4069 } else if (method_name[0] == '<') {
4070 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07004071 bool is_init = (strcmp("<init>", method_name) == 0);
4072 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07004073 if (UNLIKELY(!is_init && !is_clinit)) {
4074 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
4075 } else {
4076 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
4077 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07004078 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07004079 access_flags |= kAccConstructor;
4080 }
4081 }
4082 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01004083 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
4084 // Check if the native method is annotated with @FastNative or @CriticalNative.
4085 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
4086 dex_file, dst->GetClassDef(), dex_method_idx);
4087 }
Ian Rogers241b5de2013-10-09 17:58:57 -07004088 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00004089 // Must be done after SetAccessFlags since IsAbstract depends on it.
4090 if (klass->IsInterface() && dst->IsAbstract()) {
4091 dst->CalculateAndSetImtIndex();
4092 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07004093}
4094
Ian Rogers7b078e82014-09-10 14:44:24 -07004095void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004096 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004097 self,
4098 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004099 Runtime::Current()->GetLinearAlloc());
4100 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07004101 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07004102}
4103
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004104void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004105 ObjPtr<mirror::DexCache> dex_cache) {
4106 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004107 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07004108 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004109 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004110}
4111
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004112void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00004113 ObjPtr<mirror::DexCache> dex_cache,
4114 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004115 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08004116 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00004117 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004118 // For app images, the dex cache location may be a suffix of the dex file location since the
4119 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08004120 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
4121 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004122 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
4123 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00004124 // The following paths checks don't work on preopt when using boot dex files, where the dex
4125 // cache location is the one on device, and the dex_file's location is the one on host.
4126 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
4127 CHECK_GE(dex_file_location.length(), dex_cache_length)
4128 << dex_cache_location << " " << dex_file.GetLocation();
4129 const std::string dex_file_suffix = dex_file_location.substr(
4130 dex_file_location.length() - dex_cache_length,
4131 dex_cache_length);
4132 // Example dex_cache location is SettingsProvider.apk and
4133 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
4134 CHECK_EQ(dex_cache_location, dex_file_suffix);
4135 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004136 const OatFile* oat_file =
4137 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00004138 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
4139 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
4140 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
4141 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08004142 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004143 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
4144 DexCacheData data = *it;
4145 if (self->IsJWeakCleared(data.weak_root)) {
4146 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004147 it = dex_caches_.erase(it);
4148 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00004149 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004150 it->dex_file->GetOatDexFile() != nullptr &&
4151 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00004152 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004153 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004154 ++it;
4155 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004156 }
Vladimir Markob066d432018-01-03 13:14:37 +00004157 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00004158 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004159 }
David Brazdila5c3a802019-03-08 14:59:41 +00004160 // Let hiddenapi assign a domain to the newly registered dex file.
4161 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
4162
Vladimir Markocd556b02017-02-03 11:47:34 +00004163 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004164 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004165 DexCacheData data;
4166 data.weak_root = dex_cache_jweak;
4167 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00004168 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00004169 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00004170 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004171 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
4172 // path dex caches without an image.
4173 data.class_table->InsertStrongRoot(dex_cache);
4174 if (class_loader != nullptr) {
4175 // Since we added a strong root to the class table, do the write barrier as required for
4176 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004177 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07004178 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004179 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004180}
4181
Vladimir Markocd556b02017-02-03 11:47:34 +00004182ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
4183 return data.IsValid()
4184 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
4185 : nullptr;
4186}
4187
4188ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
4189 Thread* self,
4190 ObjPtr<mirror::DexCache> dex_cache,
4191 const DexCacheData& data,
4192 ObjPtr<mirror::ClassLoader> class_loader) {
4193 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
4194 if (data.class_table != ClassTableForClassLoader(class_loader)) {
4195 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
4196 "Attempt to register dex file %s with multiple class loaders",
4197 data.dex_file->GetLocation().c_str());
4198 return nullptr;
4199 }
4200 return dex_cache;
4201}
4202
Alex Light07f06212017-06-01 14:01:43 -07004203void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
4204 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004205 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07004206 Thread* self = Thread::Current();
4207 StackHandleScope<2> hs(self);
4208 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
4209 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
4210 const DexFile* dex_file = dex_cache->GetDexFile();
4211 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
4212 if (kIsDebugBuild) {
4213 DexCacheData old_data;
4214 {
4215 ReaderMutexLock mu(self, *Locks::dex_lock_);
4216 old_data = FindDexCacheDataLocked(*dex_file);
4217 }
4218 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
4219 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
4220 << "been registered on dex file " << dex_file->GetLocation();
4221 }
4222 ClassTable* table;
4223 {
4224 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4225 table = InsertClassTableForClassLoader(h_class_loader.Get());
4226 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004227 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4228 // a thread holding the dex lock and blocking on a condition variable regarding
4229 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004230 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07004231 WriterMutexLock mu(self, *Locks::dex_lock_);
4232 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
4233 table->InsertStrongRoot(h_dex_cache.Get());
4234 if (h_class_loader.Get() != nullptr) {
4235 // Since we added a strong root to the class table, do the write barrier as required for
4236 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004237 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004238 }
4239}
4240
Vladimir Markocd556b02017-02-03 11:47:34 +00004241ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4242 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004243 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00004244 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004245 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004246 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004247 old_data = FindDexCacheDataLocked(dex_file);
4248 }
4249 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
4250 if (old_dex_cache != nullptr) {
4251 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07004252 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004253 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004254 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4255 DCHECK(linear_alloc != nullptr);
4256 ClassTable* table;
4257 {
4258 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4259 table = InsertClassTableForClassLoader(class_loader);
4260 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004261 // Don't alloc while holding the lock, since allocation may need to
4262 // suspend all threads and another thread may need the dex_lock_ to
4263 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004264 StackHandleScope<3> hs(self);
4265 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004266 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07004267 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
4268 self,
4269 dex_file)));
4270 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004271 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004272 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4273 // a thread holding the dex lock and blocking on a condition variable regarding
4274 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004275 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004276 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004277 old_data = FindDexCacheDataLocked(dex_file);
4278 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004279 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004280 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
4281 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
4282 // that the arrays are null.
4283 mirror::DexCache::InitializeDexCache(self,
4284 h_dex_cache.Get(),
4285 h_location.Get(),
4286 &dex_file,
4287 linear_alloc,
4288 image_pointer_size_);
4289 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004290 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004291 }
4292 if (old_dex_cache != nullptr) {
4293 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4294 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004295 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00004296 self->ClearException();
4297 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
4298 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
4299 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004300 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004301 self->AssertPendingOOMException();
4302 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004303 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004304 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004305 if (h_class_loader.Get() != nullptr) {
4306 // Since we added a strong root to the class table, do the write barrier as required for
4307 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004308 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004309 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004310 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004311}
4312
Vladimir Markocd556b02017-02-03 11:47:34 +00004313bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004314 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004315 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004316}
4317
Vladimir Markocd556b02017-02-03 11:47:34 +00004318ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4319 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004320 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
4321 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004322 if (dex_cache != nullptr) {
4323 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004324 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004325 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004326 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004327 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004328 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004329 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004330 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004331 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
4332 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004333 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004334}
4335
Vladimir Markocd556b02017-02-03 11:47:34 +00004336ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4337 const DexFile* dex_file = dex_cache->GetDexFile();
4338 DCHECK(dex_file != nullptr);
4339 ReaderMutexLock mu(self, *Locks::dex_lock_);
4340 // Search assuming unique-ness of dex file.
4341 for (const DexCacheData& data : dex_caches_) {
4342 // Avoid decoding (and read barriers) other unrelated dex caches.
4343 if (data.dex_file == dex_file) {
4344 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
4345 if (registered_dex_cache != nullptr) {
4346 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4347 return data.class_table;
4348 }
4349 }
4350 }
4351 return nullptr;
4352}
4353
4354ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
4355 // Search assuming unique-ness of dex file.
4356 for (const DexCacheData& data : dex_caches_) {
4357 // Avoid decoding (and read barriers) other unrelated dex caches.
4358 if (data.dex_file == &dex_file) {
4359 return data;
4360 }
4361 }
4362 return DexCacheData();
4363}
4364
Vladimir Marko70e2a762019-07-12 16:49:00 +01004365void ClassLinker::CreatePrimitiveClass(Thread* self,
4366 Primitive::Type type,
4367 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004368 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004369 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004370 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4371 // Do not hold lock on the primitive class object, the initialization of
4372 // primitive classes is done while the process is still single threaded.
4373 primitive_class->SetAccessFlags(
4374 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4375 primitive_class->SetPrimitiveType(type);
4376 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4377 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4378 // the kAccVerificationAttempted flag was added above, and there are no
4379 // methods that need the kAccSkipAccessChecks flag.
4380 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004381 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4382 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004383 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004384 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004385 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004386 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004387 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004388 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004389}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004390
Vladimir Marko02610552018-06-04 14:38:00 +01004391inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4392 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4393}
4394
Brian Carlstrombe977852011-07-19 14:54:54 -07004395// Create an array class (i.e. the class object for the array, not the
4396// array itself). "descriptor" looks like "[C" or "[[[[B" or
4397// "[Ljava/lang/String;".
4398//
4399// If "descriptor" refers to an array of primitives, look up the
4400// primitive type's internally-generated class object.
4401//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004402// "class_loader" is the class loader of the class that's referring to
4403// us. It's used to ensure that we're looking for the element type in
4404// the right context. It does NOT become the class loader for the
4405// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004406//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004407// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004408ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4409 const char* descriptor,
4410 size_t hash,
4411 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004412 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004413 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004414 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004415
4416 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4417 // code to be executed. We put it up here so we can avoid all the allocations associated with
4418 // creating the class. This can happen with (eg) jit threads.
4419 if (!self->CanLoadClasses()) {
4420 // Make sure we don't try to load anything, potentially causing an infinite loop.
4421 ObjPtr<mirror::Throwable> pre_allocated =
4422 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4423 self->SetException(pre_allocated);
4424 return nullptr;
4425 }
4426
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004427 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4428 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004429 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004430 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004431 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004432 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4433 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004434 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004435 DCHECK(self->IsExceptionPending());
4436 return nullptr;
4437 } else {
4438 self->ClearException();
4439 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004440 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004441 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4442 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4443 return nullptr;
4444 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004445 // See if the component type is already loaded. Array classes are
4446 // always associated with the class loader of their underlying
4447 // element type -- an array of Strings goes with the loader for
4448 // java/lang/String -- so we need to look for it there. (The
4449 // caller should have checked for the existence of the class
4450 // before calling here, but they did so with *their* class loader,
4451 // not the component type's loader.)
4452 //
4453 // If we find it, the caller adds "loader" to the class' initiating
4454 // loader list, which should prevent us from going through this again.
4455 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004456 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004457 // are the same, because our caller (FindClass) just did the
4458 // lookup. (Even if we get this wrong we still have correct behavior,
4459 // because we effectively do this lookup again when we add the new
4460 // class to the hash table --- necessary because of possible races with
4461 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004462 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004463 ObjPtr<mirror::Class> new_class =
4464 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004465 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004466 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004467 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004468 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004469 // Core array classes, i.e. Object[], Class[], String[] and primitive
4470 // arrays, have special initialization and they should be found above.
4471 DCHECK(!component_type->IsObjectClass() ||
4472 // Guard from false positives for errors before setting superclass.
4473 component_type->IsErroneousUnresolved());
4474 DCHECK(!component_type->IsStringClass());
4475 DCHECK(!component_type->IsClassClass());
4476 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004477
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004478 // Fill out the fields in the Class.
4479 //
4480 // It is possible to execute some methods against arrays, because
4481 // all arrays are subclasses of java_lang_Object_, so we need to set
4482 // up a vtable. We can just point at the one in java_lang_Object_.
4483 //
4484 // Array classes are simple enough that we don't need to do a full
4485 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004486 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4487 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4488 size_t usable_size)
4489 REQUIRES_SHARED(Locks::mutator_lock_) {
4490 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4491 init_class(obj, usable_size);
4492 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4493 klass->SetComponentType(component_type.Get());
4494 // Do not hold lock for initialization, the fence issued after the visitor
4495 // returns ensures memory visibility together with the implicit consume
4496 // semantics (for all supported architectures) for any thread that loads
4497 // the array class reference from any memory locations afterwards.
4498 FinishArrayClassSetup(klass);
4499 };
4500 auto new_class = hs.NewHandle<mirror::Class>(
4501 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004502 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004503 self->AssertPendingOOMException();
4504 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004505 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004506
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004507 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004508 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004509 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4510 // duplicate events in case of races. Array classes don't really follow dedicated
4511 // load and prepare, anyways.
4512 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4513 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4514
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004515 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004516 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004517 }
4518 // Another thread must have loaded the class after we
4519 // started but before we finished. Abandon what we've
4520 // done.
4521 //
4522 // (Yes, this happens.)
4523
Vladimir Markobcf17522018-06-01 13:14:32 +01004524 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004525}
4526
Vladimir Marko9186b182018-11-06 14:55:54 +00004527ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4528 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004529 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004530 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4531 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4532 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4533 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4534 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4535 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4536 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4537 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4538 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004539 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004540 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004541 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004542 return GetClassRoot(class_root, this);
4543}
4544
4545ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4546 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4547 if (UNLIKELY(result == nullptr)) {
4548 std::string printable_type(PrintableChar(type));
4549 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4550 }
4551 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004552}
4553
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004554ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4555 ObjPtr<mirror::Class> klass,
4556 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004557 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004558 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004559 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004560 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004561 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004562 source += " from ";
4563 source += dex_cache->GetLocation()->ToModifiedUtf8();
4564 }
4565 LOG(INFO) << "Loaded class " << descriptor << source;
4566 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004567 {
4568 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004569 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004570 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004571 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004572 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004573 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004574 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004575 VerifyObject(klass);
4576 class_table->InsertWithHash(klass, hash);
4577 if (class_loader != nullptr) {
4578 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004579 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004580 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004581 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004582 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004583 }
4584 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004585 if (kIsDebugBuild) {
4586 // Test that copied methods correctly can find their holder.
4587 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4588 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4589 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004590 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004591 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004592}
4593
Vladimir Marko1998cd02017-01-13 13:02:58 +00004594void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004595 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4596 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4597 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4598 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004599 }
4600}
4601
Alex Lighte64300b2015-12-15 15:02:47 -08004602// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004603void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004604 LengthPrefixedArray<ArtMethod>* new_methods) {
4605 klass->SetMethodsPtrUnchecked(new_methods,
4606 klass->NumDirectMethods(),
4607 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004608 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004609 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004610}
4611
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004612ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4613 const char* descriptor,
4614 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004615 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4616}
4617
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004618ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4619 const char* descriptor,
4620 size_t hash,
4621 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004622 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4623 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4624 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004625 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004626 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004627 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004628 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004629 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004630 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004631}
4632
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004633class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4634 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004635 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004636
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004637 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004638 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004639 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004640 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004641 if (class_table != nullptr) {
4642 class_table->FreezeSnapshot();
4643 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004644 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004645};
4646
4647void ClassLinker::MoveClassTableToPreZygote() {
4648 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004649 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004650 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004651 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004652}
4653
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004654// Look up classes by hash and descriptor and put all matching ones in the result array.
4655class LookupClassesVisitor : public ClassLoaderVisitor {
4656 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004657 LookupClassesVisitor(const char* descriptor,
4658 size_t hash,
4659 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004660 : descriptor_(descriptor),
4661 hash_(hash),
4662 result_(result) {}
4663
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004664 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004665 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004666 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004667 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004668 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4669 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004670 result_->push_back(klass);
4671 }
4672 }
4673
4674 private:
4675 const char* const descriptor_;
4676 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004677 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004678};
4679
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004680void ClassLinker::LookupClasses(const char* descriptor,
4681 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004682 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004683 Thread* const self = Thread::Current();
4684 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004685 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004686 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004687 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004688 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004689 result.push_back(klass);
4690 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004691 LookupClassesVisitor visitor(descriptor, hash, &result);
4692 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004693}
4694
Alex Lightf1f10492015-10-07 16:08:36 -07004695bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4696 Handle<mirror::Class> klass,
4697 Handle<mirror::Class> supertype) {
4698 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004699 DCHECK(klass != nullptr);
4700 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004701
Alex Lightf1f10492015-10-07 16:08:36 -07004702 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4703 VerifyClass(self, supertype);
4704 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004705
4706 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4707 // The supertype is either verified, or we soft failed at AOT time.
4708 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004709 return true;
4710 }
4711 // If we got this far then we have a hard failure.
4712 std::string error_msg =
4713 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004714 klass->PrettyDescriptor().c_str(),
4715 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004716 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004717 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004718 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004719 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004720 // Set during VerifyClass call (if at all).
4721 self->ClearException();
4722 }
4723 // Change into a verify error.
4724 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004725 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004726 self->GetException()->SetCause(cause.Get());
4727 }
4728 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4729 if (Runtime::Current()->IsAotCompiler()) {
4730 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4731 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004732 // Need to grab the lock to change status.
4733 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004734 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004735 return false;
4736}
4737
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004738verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004739 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004740 {
4741 // TODO: assert that the monitor on the Class is held
4742 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004743
Andreas Gampe884f3b82016-03-30 19:52:58 -07004744 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004745 ClassStatus old_status = klass->GetStatus();
4746 while (old_status == ClassStatus::kVerifying ||
4747 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004748 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004749 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4750 // case we may see the same status again. b/62912904. This is why the check is
4751 // greater or equal.
4752 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004753 << "Class '" << klass->PrettyClass()
4754 << "' performed an illegal verification state transition from " << old_status
4755 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004756 old_status = klass->GetStatus();
4757 }
jeffhao98eacac2011-09-14 16:11:53 -07004758
Andreas Gampe884f3b82016-03-30 19:52:58 -07004759 // The class might already be erroneous, for example at compile time if we attempted to verify
4760 // this class as a parent to another.
4761 if (klass->IsErroneous()) {
4762 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004763 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004764 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004765
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004766 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004767 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004768 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004769 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004770 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004771
4772 // For AOT, don't attempt to re-verify if we have already found we should
4773 // verify at runtime.
4774 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004775 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004776 }
jeffhao98eacac2011-09-14 16:11:53 -07004777
Vladimir Marko2c64a832018-01-04 11:31:56 +00004778 if (klass->GetStatus() == ClassStatus::kResolved) {
4779 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004780 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004781 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004782 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004783 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004784 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004785 }
4786
4787 // Skip verification if disabled.
4788 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004789 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004790 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004791 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004792 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004793 }
4794
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004795 VLOG(class_linker) << "Beginning verification for class: "
4796 << klass->PrettyDescriptor()
4797 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4798
Ian Rogers9ffb0392012-09-10 11:56:50 -07004799 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004800 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004801 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4802 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004803 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004804 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004805 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004806 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004807
Alex Lightf1f10492015-10-07 16:08:36 -07004808 // Verify all default super-interfaces.
4809 //
4810 // (1) Don't bother if the superclass has already had a soft verification failure.
4811 //
4812 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4813 // recursive initialization by themselves. This is because when an interface is initialized
4814 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4815 // but choose not to for an optimization. If the interfaces is being verified due to a class
4816 // initialization (which would need all the default interfaces to be verified) the class code
4817 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004818 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004819 && !klass->IsInterface()) { // See (2)
4820 int32_t iftable_count = klass->GetIfTableCount();
4821 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4822 // Loop through all interfaces this class has defined. It doesn't matter the order.
4823 for (int32_t i = 0; i < iftable_count; i++) {
4824 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004825 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004826 // We only care if we have default interfaces and can skip if we are already verified...
4827 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4828 continue;
4829 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4830 // We had a hard failure while verifying this interface. Just return immediately.
4831 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004832 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004833 } else if (UNLIKELY(!iface->IsVerified())) {
4834 // We softly failed to verify the iface. Stop checking and clean up.
4835 // Put the iface into the supertype handle so we know what caused us to fail.
4836 supertype.Assign(iface.Get());
4837 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004838 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004839 }
4840 }
4841
Alex Lightf1f10492015-10-07 16:08:36 -07004842 // At this point if verification failed, then supertype is the "first" supertype that failed
4843 // verification (without a specific order). If verification succeeded, then supertype is either
4844 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004845 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004846 supertype.Get() == klass->GetSuperClass() ||
4847 !supertype->IsVerified());
4848
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004849 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004850 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004851 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004852 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004853
4854 VLOG(class_linker) << "Class preverified status for class "
4855 << klass->PrettyDescriptor()
4856 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4857 << ": "
4858 << preverified;
4859
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004860 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4861 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004862 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4863 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004864
Ian Rogers62d6c772013-02-27 08:32:07 -08004865 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004866 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004867 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004868 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004869 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004870
4871 // Verification is done, grab the lock again.
4872 ObjectLock<mirror::Class> lock(self, klass);
4873
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004874 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4875 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004876 VLOG(class_linker) << "Soft verification failure in class "
4877 << klass->PrettyDescriptor()
4878 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4879 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004880 }
Ian Rogers1f539342012-10-03 21:09:42 -07004881 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004882 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004883 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004884 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004885 // Even though there were no verifier failures we need to respect whether the super-class and
4886 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004887 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004888 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004889 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004890 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4891 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004892 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004893 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004894 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004895 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004896 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004897 // Soft failures at compile time should be retried at runtime. Soft
4898 // failures at runtime will be handled by slow paths in the generated
4899 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004900 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004901 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004902 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004903 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004904 // As this is a fake verified status, make sure the methods are _not_ marked
4905 // kAccSkipAccessChecks later.
4906 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004907 }
4908 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004909 } else {
David Sehr709b0702016-10-13 09:12:37 -07004910 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004911 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4912 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004913 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004914 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004915 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004916 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004917 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004918 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004919 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004920 // method.
4921 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004922 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004923 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004924
4925 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4926 // Never skip access checks if the verification soft fail is forced.
4927 // Mark the class as having a verification attempt to avoid re-running the verifier.
4928 klass->SetVerificationAttempted();
4929 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004930 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004931 }
Andreas Gampe48498592014-09-10 19:48:05 -07004932 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004933 // Done verifying. Notify the compiler about the verification status, in case the class
4934 // was verified implicitly (eg super class of a compiled class).
4935 if (Runtime::Current()->IsAotCompiler()) {
4936 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4937 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4938 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004939 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004940}
4941
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004942verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4943 Handle<mirror::Class> klass,
4944 verifier::HardFailLogMode log_level,
4945 std::string* error_msg) {
4946 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004947 return verifier::ClassVerifier::VerifyClass(self,
4948 klass.Get(),
4949 runtime->GetCompilerCallbacks(),
4950 runtime->IsAotCompiler(),
4951 log_level,
4952 Runtime::Current()->GetTargetSdkVersion(),
4953 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004954}
4955
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004956bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004957 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004958 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004959 // If we're compiling, we can only verify the class using the oat file if
4960 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004961 // the compilation unit (app - dependencies). We will let the compiler callback
4962 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004963 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004964 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004965 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004966 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004967 return false;
4968 }
4969 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004970 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004971 return false;
4972 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004973 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004974
Andreas Gampeb40d3612018-06-26 15:49:42 -07004975 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004976 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004977 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004978 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4979 // For boot classpath classes in the case we're not using a default boot image:
4980 // we don't have the infrastructure yet to query verification data on individual
4981 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4982 // verified. This should be taken into account when measuring boot time and app
4983 // startup compare to the (current) production system where both:
4984 // 1) updatable boot classpath classes, and
4985 // 2) classes in /system referencing updatable classes
4986 // will be verified at runtime.
David Srbecky3db3d372019-04-17 18:19:17 +01004987 if (Runtime::Current()->IsUsingApexBootImageLocation()) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004988 oat_file_class_status = ClassStatus::kVerified;
4989 return true;
4990 }
4991 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004992 return false;
4993 }
4994
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004995 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004996 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004997 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004998 return true;
4999 }
5000 // If we only verified a subset of the classes at compile time, we can end up with classes that
5001 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005002 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07005003 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005004 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005005 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07005006 // Compile time verification failed with a soft error. Compile time verification can fail
5007 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08005008 // class ... {
5009 // Foo x;
5010 // .... () {
5011 // if (...) {
5012 // v1 gets assigned a type of resolved class Foo
5013 // } else {
5014 // v1 gets assigned a type of unresolved class Bar
5015 // }
5016 // iput x = v1
5017 // } }
5018 // when we merge v1 following the if-the-else it results in Conflict
5019 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
5020 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
5021 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
5022 // at compile time).
5023 return false;
5024 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00005025 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07005026 // Compile time verification failed with a hard error. This is caused by invalid instructions
5027 // in the class. These errors are unrecoverable.
5028 return false;
5029 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005030 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08005031 // Status is uninitialized if we couldn't determine the status at compile time, for example,
5032 // not loading the class.
5033 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
5034 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005035 return false;
5036 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07005037 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07005038 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07005039 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07005040 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005041 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005042}
5043
Alex Light5a559862016-01-29 12:24:48 -08005044void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08005045 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08005046 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005047 }
5048}
5049
Alex Light5a559862016-01-29 12:24:48 -08005050void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005051 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00005052 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005053 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005054 return; // native or abstract method
5055 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005056 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005057 return; // nothing to process
5058 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08005059 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005060 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005061 for (uint32_t idx = 0; idx < handlers_size; idx++) {
5062 CatchHandlerIterator iterator(handlers_ptr);
5063 for (; iterator.HasNext(); iterator.Next()) {
5064 // Ensure exception types are resolved so that they don't need resolution to be delivered,
5065 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08005066 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005067 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005068 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005069 DCHECK(Thread::Current()->IsExceptionPending());
5070 Thread::Current()->ClearException();
5071 }
5072 }
5073 }
5074 handlers_ptr = iterator.EndDataPointer();
5075 }
5076}
5077
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01005078ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
5079 jstring name,
5080 jobjectArray interfaces,
5081 jobject loader,
5082 jobjectArray methods,
5083 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005084 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07005085
5086 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
5087 // code to be executed. We put it up here so we can avoid all the allocations associated with
5088 // creating the class. This can happen with (eg) jit-threads.
5089 if (!self->CanLoadClasses()) {
5090 // Make sure we don't try to load anything, potentially causing an infinite loop.
5091 ObjPtr<mirror::Throwable> pre_allocated =
5092 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
5093 self->SetException(pre_allocated);
5094 return nullptr;
5095 }
5096
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005097 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005098 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005099 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005100 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005101 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005102 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005103 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005104 DCHECK(temp_klass->GetClass() != nullptr);
5105 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08005106 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
5107 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005108 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
5109 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
5110 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
5111 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005112 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08005113 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005114 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005115 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00005116 std::string storage;
5117 const char* descriptor = temp_klass->GetDescriptor(&storage);
5118 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005119
Mathieu Chartierd57d4542015-10-14 10:55:30 -07005120 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005121 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07005122
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005123 // Insert the class before loading the fields as the field roots
5124 // (ArtField::declaring_class_) are only visited from the class
5125 // table. There can't be any suspend points between inserting the
5126 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00005127 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005128 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08005129
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005130 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07005131 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07005132 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005133 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005134
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005135 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
5136 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005137 ArtField& interfaces_sfield = sfields->At(0);
5138 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005139 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005140 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005141
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005142 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005143 ArtField& throws_sfield = sfields->At(1);
5144 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005145 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005146 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04005147
Ian Rogers466bb252011-10-14 03:29:56 -07005148 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08005149 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04005150
Alex Lighte64300b2015-12-15 15:02:47 -08005151 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07005152 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01005153 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07005154 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005155 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08005156
5157 // Create the methods array.
5158 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
5159 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005160 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
5161 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08005162 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005163 self->AssertPendingOOMException();
5164 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005165 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005166 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005167
5168 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005169 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005170
5171 // Create virtual method using specified prototypes.
5172 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005173 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005174 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005175 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005176 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005177 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5178 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005179 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005180
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005181 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005182 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005183 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005184 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005185 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005186
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005187 // At this point the class is loaded. Publish a ClassLoad event.
5188 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5189 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5190
5191 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005192 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005193 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005194 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005195 // Link the fields and virtual methods, creating vtable and iftables.
5196 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005197 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005198 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005199 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005200 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005201 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005202 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005203 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005204 CHECK(temp_klass->IsRetired());
5205 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005206
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005207 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005208 interfaces_sfield.SetObject<false>(
5209 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005210 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005211 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5212 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005213 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005214 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005215
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005216 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5217
Vladimir Marko305c38b2018-02-14 11:50:07 +00005218 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5219 // See also ClassLinker::EnsureInitialized().
5220 if (kBitstringSubtypeCheckEnabled) {
5221 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5222 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5223 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5224 }
5225
Vladimir Markobf121912019-06-04 13:49:05 +01005226 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005227 {
5228 // Lock on klass is released. Lock new class object.
5229 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005230 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005231 // Conservatively go through the ClassStatus::kInitialized state.
5232 callback = MarkClassInitialized(self, klass);
5233 }
5234 if (callback != nullptr) {
5235 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005236 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005237
5238 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07005239 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005240 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005241 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5242
Ian Rogersc2b44472011-12-14 21:17:17 -08005243 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005244 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
5245 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005246 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08005247 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005248
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005249 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005250 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005251 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005252 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005253 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005254
5255 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005256 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005257 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005258
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005259 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005260 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005261 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005262 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08005263 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005264 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005265}
5266
Mathieu Chartiere401d142015-04-22 13:56:20 -07005267void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5268 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005269 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5270 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005271
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005272 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5273 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005274 ArtMethod* proxy_constructor =
5275 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005276 DCHECK(proxy_constructor != nullptr)
5277 << "Could not find <init> method in java.lang.reflect.Proxy";
5278
Jeff Haodb8a6642014-08-14 17:18:52 -07005279 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5280 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005281 DCHECK(out != nullptr);
5282 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005283 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005284 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005285 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005286 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5287 kAccPublic |
5288 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005289 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005290
5291 // Set the original constructor method.
5292 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005293}
5294
Mathieu Chartiere401d142015-04-22 13:56:20 -07005295void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005296 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005297 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5298 CHECK_STREQ(np->GetName(), "<init>");
5299 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005300 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005301}
5302
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005303void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005304 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005305 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005306 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005307 DCHECK(out != nullptr);
5308 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005309
Alex Lighte9dd04f2016-03-16 16:09:45 -07005310 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005311 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005312 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5313 // preference to the invocation handler.
5314 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5315 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005316 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5317 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005318 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5319
5320 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5321 // method they copy might (if it's a default method).
5322 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005323
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005324 // Set the original interface method.
5325 out->SetDataPtrSize(prototype, image_pointer_size_);
5326
Ian Rogers466bb252011-10-14 03:29:56 -07005327 // At runtime the method looks like a reference and argument saving method, clone the code
5328 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005329 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005330}
Jesse Wilson95caa792011-10-12 18:14:17 -04005331
Mathieu Chartiere401d142015-04-22 13:56:20 -07005332void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005333 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005334 CHECK(!prototype->IsFinal());
5335 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005336 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005337
5338 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5339 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005340 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005341 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005342}
5343
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005344bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005345 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005346 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005347 return true;
5348 }
5349 if (!can_init_statics) {
5350 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005351 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005352 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005353 return false;
5354 }
5355 // Check if there are encoded static values needing initialization.
5356 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005357 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005358 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005359 if (dex_class_def->static_values_off_ != 0) {
5360 return false;
5361 }
5362 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005363 // If we are a class we need to initialize all interfaces with default methods when we are
5364 // initialized. Check all of them.
5365 if (!klass->IsInterface()) {
5366 size_t num_interfaces = klass->GetIfTableCount();
5367 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005368 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005369 if (iface->HasDefaultMethods() &&
5370 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5371 return false;
5372 }
5373 }
5374 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005375 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005376 if (klass->IsInterface() || !klass->HasSuperClass()) {
5377 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005378 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005379 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005380 if (!can_init_parents && !super_class->IsInitialized()) {
5381 return false;
5382 }
5383 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005384}
5385
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005386bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5387 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005388 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5389
5390 // Are we already initialized and therefore done?
5391 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5392 // an initialized class will never change its state.
5393 if (klass->IsInitialized()) {
5394 return true;
5395 }
5396
5397 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005398 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005399 return false;
5400 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005401
Ian Rogers7b078e82014-09-10 14:44:24 -07005402 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005403 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005404 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005405 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005406
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005407 // Re-check under the lock in case another thread initialized ahead of us.
5408 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005409 return true;
5410 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005411
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005412 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005413 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005414 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005415 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005416 return false;
5417 }
5418
Vladimir Marko72ab6842017-01-20 19:32:50 +00005419 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5420 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005421
5422 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005423 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005424 if (!klass->IsVerified()) {
5425 // We failed to verify, expect either the klass to be erroneous or verification failed at
5426 // compile time.
5427 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005428 // The class is erroneous. This may be a verifier error, or another thread attempted
5429 // verification and/or initialization and failed. We can distinguish those cases by
5430 // whether an exception is already pending.
5431 if (self->IsExceptionPending()) {
5432 // Check that it's a VerifyError.
5433 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005434 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005435 } else {
5436 // Check that another thread attempted initialization.
5437 DCHECK_NE(0, klass->GetClinitThreadId());
5438 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5439 // Need to rethrow the previous failure now.
5440 ThrowEarlierClassFailure(klass.Get(), true);
5441 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005442 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005443 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005444 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005445 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005446 self->AssertNoPendingException();
5447 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005448 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005449 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005450 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005451 } else {
5452 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005453 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005454
5455 // A separate thread could have moved us all the way to initialized. A "simple" example
5456 // involves a subclass of the current class being initialized at the same time (which
5457 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005458 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005459 if (klass->IsInitialized()) {
5460 return true;
5461 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005462 }
5463
Vladimir Marko2c64a832018-01-04 11:31:56 +00005464 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005465 // initializing higher up the stack or another thread has beat us
5466 // to initializing and we need to wait. Either way, this
5467 // invocation of InitializeClass will not be responsible for
5468 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005469 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005470 // Could have got an exception during verification.
5471 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005472 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005473 return false;
5474 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005475 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005476 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005477 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005478 return true;
5479 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005480 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005481 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005482 }
5483
Jeff Haoe2e40342017-07-19 10:45:18 -07005484 // Try to get the oat class's status for this class if the oat file is present. The compiler
5485 // tries to validate superclass descriptors, and writes the result into the oat file.
5486 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5487 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5488 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005489 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005490 const Runtime* runtime = Runtime::Current();
5491 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5492 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5493 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005494 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005495 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005496 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005497 return false;
5498 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005499 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005500
Vladimir Marko2c64a832018-01-04 11:31:56 +00005501 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005502 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005503
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005504 // From here out other threads may observe that we're initializing and so changes of state
5505 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005506 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005507 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005508
5509 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005510 }
5511
Andreas Gampeaf864702019-07-23 14:05:35 -07005512 uint64_t t_sub = 0;
5513
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005514 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005515 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005516 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005517 if (!super_class->IsInitialized()) {
5518 CHECK(!super_class->IsInterface());
5519 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005520 StackHandleScope<1> hs(self);
5521 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Andreas Gampeaf864702019-07-23 14:05:35 -07005522 uint64_t super_t0 = NanoTime();
Ian Rogers7b078e82014-09-10 14:44:24 -07005523 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Andreas Gampeaf864702019-07-23 14:05:35 -07005524 uint64_t super_t1 = NanoTime();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005525 if (!super_initialized) {
5526 // The super class was verified ahead of entering initializing, we should only be here if
5527 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005528 // For the case of aot compiler, the super class might also be initializing but we don't
5529 // want to process circular dependencies in pre-compile.
5530 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005531 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005532 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005533 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005534 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005535 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005536 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005537 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005538 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005539 return false;
5540 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005541 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005542 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005543 }
5544
Alex Lighteb7c1442015-08-31 13:17:42 -07005545 if (!klass->IsInterface()) {
5546 // Initialize interfaces with default methods for the JLS.
5547 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005548 // Only setup the (expensive) handle scope if we actually need to.
5549 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005550 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005551 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5552 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005553 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005554 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005555 CHECK(handle_scope_iface->IsInterface());
5556 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5557 // We have already done this for this interface. Skip it.
5558 continue;
5559 }
5560 // We cannot just call initialize class directly because we need to ensure that ALL
5561 // interfaces with default methods are initialized. Non-default interface initialization
5562 // will not affect other non-default super-interfaces.
Andreas Gampeaf864702019-07-23 14:05:35 -07005563 uint64_t inf_t0 = NanoTime(); // This is not very precise, misses all walking.
Alex Light56a40f52015-10-14 11:07:41 -07005564 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5565 handle_scope_iface,
5566 can_init_statics,
5567 can_init_parents);
Andreas Gampeaf864702019-07-23 14:05:35 -07005568 uint64_t inf_t1 = NanoTime();
Alex Light56a40f52015-10-14 11:07:41 -07005569 if (!iface_initialized) {
5570 ObjectLock<mirror::Class> lock(self, klass);
5571 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005572 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005573 return false;
5574 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005575 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005576 }
5577 }
5578 }
5579
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005580 const size_t num_static_fields = klass->NumStaticFields();
5581 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005582 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005583 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005584 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005585 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005586 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005587
5588 // Eagerly fill in static fields so that the we don't have to do as many expensive
5589 // Class::FindStaticField in ResolveField.
5590 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005591 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005592 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005593 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005594 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005595 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005596 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5597 field,
5598 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5599 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005600 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005601 } else {
5602 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005603 }
5604 }
5605
Vladimir Markoe11dd502017-12-08 14:09:45 +00005606 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5607 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005608 this,
5609 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005610 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005611
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005612 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005613 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005614 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005615 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5616 if (!value_it.HasNext()) {
5617 break;
5618 }
5619 ArtField* art_field = ResolveField(field.GetIndex(),
5620 dex_cache,
5621 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005622 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005623 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005624 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005625 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005626 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005627 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005628 if (self->IsExceptionPending()) {
5629 break;
5630 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005631 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005632 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005633 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005634 }
5635 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005636
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005637
Mathieu Chartierda595be2016-08-10 13:57:39 -07005638 if (!self->IsExceptionPending()) {
5639 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5640 if (clinit != nullptr) {
5641 CHECK(can_init_statics);
5642 JValue result;
5643 clinit->Invoke(self, nullptr, 0, &result, "V");
5644 }
5645 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005646 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005647 uint64_t t1 = NanoTime();
5648
Vladimir Markobf121912019-06-04 13:49:05 +01005649 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005650 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005651 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005652 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005653
5654 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005655 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005656 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005657 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005658 } else if (Runtime::Current()->IsTransactionAborted()) {
5659 // The exception thrown when the transaction aborted has been caught and cleared
5660 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005661 VLOG(compiler) << "Return from class initializer of "
5662 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005663 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005664 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005665 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005666 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005667 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005668 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5669 RuntimeStats* thread_stats = self->GetStats();
5670 ++global_stats->class_init_count;
5671 ++thread_stats->class_init_count;
Andreas Gampeaf864702019-07-23 14:05:35 -07005672 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5673 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005674 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005675 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005676 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005677 std::string temp;
5678 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005679 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005680 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005681 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005682 }
Vladimir Markobf121912019-06-04 13:49:05 +01005683 if (callback != nullptr) {
5684 callback->MakeVisible(self);
5685 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005686 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005687}
5688
Alex Lighteb7c1442015-08-31 13:17:42 -07005689// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5690// and perform the initialization only on those interfaces that contain default methods.
5691bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5692 Handle<mirror::Class> iface,
5693 bool can_init_statics,
5694 bool can_init_parents) {
5695 CHECK(iface->IsInterface());
5696 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005697 // Only create the (expensive) handle scope if we need it.
5698 if (UNLIKELY(num_direct_ifaces > 0)) {
5699 StackHandleScope<1> hs(self);
5700 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5701 // First we initialize all of iface's super-interfaces recursively.
5702 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005703 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005704 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005705 if (!super_iface->HasBeenRecursivelyInitialized()) {
5706 // Recursive step
5707 handle_super_iface.Assign(super_iface);
5708 if (!InitializeDefaultInterfaceRecursive(self,
5709 handle_super_iface,
5710 can_init_statics,
5711 can_init_parents)) {
5712 return false;
5713 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005714 }
5715 }
5716 }
5717
5718 bool result = true;
5719 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5720 // initialize if we don't have default methods.
5721 if (iface->HasDefaultMethods()) {
5722 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5723 }
5724
5725 // Mark that this interface has undergone recursive default interface initialization so we know we
5726 // can skip it on any later class initializations. We do this even if we are not a default
5727 // interface since we can still avoid the traversal. This is purely a performance optimization.
5728 if (result) {
5729 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005730 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5731 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5732 // initialization is a performance optimization (to avoid another idempotent visit
5733 // for other implementing classes/interfaces), and can be revisited later.
5734 ObjectTryLock<mirror::Class> lock(self, iface);
5735 if (lock.Acquired()) {
5736 iface->SetRecursivelyInitialized();
5737 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005738 }
5739 return result;
5740}
5741
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005742bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5743 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005744 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005745 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005746 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005747 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005748 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005749 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005750
5751 // When we wake up, repeat the test for init-in-progress. If
5752 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005753 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005754 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005755 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005756 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005757 return false;
5758 }
5759 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005760 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005761 continue;
5762 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005763 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005764 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005765 // Compile time initialization failed.
5766 return false;
5767 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005768 if (klass->IsErroneous()) {
5769 // The caller wants an exception, but it was thrown in a
5770 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005771 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005772 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005773 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005774 return false;
5775 }
5776 if (klass->IsInitialized()) {
5777 return true;
5778 }
David Sehr709b0702016-10-13 09:12:37 -07005779 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005780 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005781 }
Ian Rogers07140832014-09-30 15:43:59 -07005782 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005783}
5784
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005785static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5786 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005787 ArtMethod* method,
5788 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005789 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005790 DCHECK(Thread::Current()->IsExceptionPending());
5791 DCHECK(!m->IsProxyMethod());
5792 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005793 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5794 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005795 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005796 std::string return_type = dex_file->PrettyType(return_type_idx);
5797 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005798 ThrowWrappedLinkageError(klass.Get(),
5799 "While checking class %s method %s signature against %s %s: "
5800 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005801 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5802 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005803 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005804 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005805 return_type.c_str(), class_loader.c_str());
5806}
5807
5808static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5809 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005810 ArtMethod* method,
5811 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005812 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005813 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005814 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005815 DCHECK(Thread::Current()->IsExceptionPending());
5816 DCHECK(!m->IsProxyMethod());
5817 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005818 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5819 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005820 ThrowWrappedLinkageError(klass.Get(),
5821 "While checking class %s method %s signature against %s %s: "
5822 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005823 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5824 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005825 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005826 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005827 index, arg_type.c_str(), class_loader.c_str());
5828}
5829
5830static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5831 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005832 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005833 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005834 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005835 ThrowLinkageError(klass.Get(),
5836 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005837 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5838 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005839 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005840 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005841 error_msg.c_str());
5842}
5843
Ian Rogersb5fb2072014-12-02 17:22:02 -08005844static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005845 Handle<mirror::Class> klass,
5846 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005847 ArtMethod* method1,
5848 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005849 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005850 {
5851 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005852 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005853 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005854 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005855 return false;
5856 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005857 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005858 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005859 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005860 return false;
5861 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005862 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005863 ThrowSignatureMismatch(klass, super_klass, method1,
5864 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005865 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005866 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005867 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005868 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005869 return false;
5870 }
5871 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005872 const dex::TypeList* types1 = method1->GetParameterTypeList();
5873 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005874 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005875 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005876 ThrowSignatureMismatch(klass, super_klass, method1,
5877 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005878 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005879 return false;
5880 }
5881 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005882 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005883 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005884 ThrowSignatureMismatch(klass, super_klass, method1,
5885 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005886 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005887 return false;
5888 }
5889 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005890 }
5891 uint32_t num_types = types1->Size();
5892 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005893 ThrowSignatureMismatch(klass, super_klass, method1,
5894 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005895 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005896 return false;
5897 }
5898 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005899 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005900 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005901 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005902 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005903 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005904 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005905 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005906 return false;
5907 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005908 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005909 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005910 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005911 if (UNLIKELY(other_param_type == nullptr)) {
5912 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005913 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005914 return false;
5915 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005916 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005917 ThrowSignatureMismatch(klass, super_klass, method1,
5918 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5919 i,
David Sehr709b0702016-10-13 09:12:37 -07005920 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005921 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005922 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005923 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005924 return false;
5925 }
5926 }
5927 return true;
5928}
5929
5930
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005931bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005932 if (klass->IsInterface()) {
5933 return true;
5934 }
Ian Rogers151f2212014-05-06 11:27:27 -07005935 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005936 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005937 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005938 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005939 if (klass->HasSuperClass() &&
5940 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005941 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005942 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005943 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5944 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5945 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005946 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5947 klass,
5948 super_klass,
5949 m,
5950 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005951 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005952 return false;
5953 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005954 }
5955 }
5956 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005957 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005958 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5959 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5960 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005961 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005962 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5963 j, image_pointer_size_);
5964 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5965 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005966 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5967 klass,
5968 super_klass,
5969 m,
5970 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005971 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005972 return false;
5973 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005974 }
5975 }
5976 }
5977 }
5978 return true;
5979}
5980
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005981bool ClassLinker::EnsureInitialized(Thread* self,
5982 Handle<mirror::Class> c,
5983 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005984 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005985 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005986
Mathieu Chartier524507a2014-08-27 15:28:28 -07005987 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005988 // If we've seen an initialized but not visibly initialized class
5989 // many times, request visible initialization.
5990 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5991 // Thanks to the x86 memory model classes skip the initialized status.
5992 DCHECK(c->IsVisiblyInitialized());
5993 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5994 if (self->IncrementMakeVisiblyInitializedCounter()) {
5995 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5996 }
5997 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005998 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005999 return true;
6000 }
Igor Murashkin86083f72017-10-27 10:59:04 -07006001 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
6002 //
6003 // Ensure the bitstring is initialized before any of the class initialization
6004 // logic occurs. Once a class initializer starts running, objects can
6005 // escape into the heap and use the subtype checking code.
6006 //
6007 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
6008 // can be used as a source for the IsSubClass check, and that all ancestors
6009 // of the class are Assigned (can be used as a target for IsSubClass check)
6010 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00006011 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07006012 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00006013 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07006014 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
6015 }
Ian Rogers7b078e82014-09-10 14:44:24 -07006016 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07006017 if (!success) {
6018 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07006019 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07006020 }
6021 } else {
6022 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08006023 }
6024 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07006025}
6026
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006027void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
6028 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006029 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006030 for (ArtField& field : new_class->GetIFields()) {
6031 if (field.GetDeclaringClass() == temp_class) {
6032 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006033 }
6034 }
6035
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006036 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006037 for (ArtField& field : new_class->GetSFields()) {
6038 if (field.GetDeclaringClass() == temp_class) {
6039 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006040 }
6041 }
6042
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006043 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006044 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08006045 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006046 if (method.GetDeclaringClass() == temp_class) {
6047 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006048 }
6049 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006050
6051 // Make sure the remembered set and mod-union tables know that we updated some of the native
6052 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006053 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006054}
6055
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006056void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08006057 CHECK(class_loader->GetAllocator() == nullptr);
6058 CHECK(class_loader->GetClassTable() == nullptr);
6059 Thread* const self = Thread::Current();
6060 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08006061 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08006062 // Create and set the class table.
6063 data.class_table = new ClassTable;
6064 class_loader->SetClassTable(data.class_table);
6065 // Create and set the linear allocator.
6066 data.allocator = Runtime::Current()->CreateLinearAlloc();
6067 class_loader->SetAllocator(data.allocator);
6068 // Add to the list so that we know to free the data later.
6069 class_loaders_.push_back(data);
6070}
6071
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006072ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07006073 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07006074 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006075 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07006076 ClassTable* class_table = class_loader->GetClassTable();
6077 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08006078 RegisterClassLoader(class_loader);
6079 class_table = class_loader->GetClassTable();
6080 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07006081 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006082 return class_table;
6083}
6084
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006085ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07006086 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006087}
6088
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006089static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006090 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006091 while (klass->HasSuperClass()) {
6092 klass = klass->GetSuperClass();
6093 if (klass->ShouldHaveImt()) {
6094 return klass->GetImt(pointer_size);
6095 }
6096 }
6097 return nullptr;
6098}
6099
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006100bool ClassLinker::LinkClass(Thread* self,
6101 const char* descriptor,
6102 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006103 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006104 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006105 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006106
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006107 if (!LinkSuperClass(klass)) {
6108 return false;
6109 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006110 ArtMethod* imt_data[ImTable::kSize];
6111 // If there are any new conflicts compared to super class.
6112 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006113 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006114 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006115 return false;
6116 }
Ian Rogers7b078e82014-09-10 14:44:24 -07006117 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006118 return false;
6119 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006120 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006121 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07006122 return false;
6123 }
6124 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00006125 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006126
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006127 ImTable* imt = nullptr;
6128 if (klass->ShouldHaveImt()) {
6129 // If there are any new conflicts compared to the super class we can not make a copy. There
6130 // can be cases where both will have a conflict method at the same slot without having the same
6131 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
6132 // will possibly create a table that is incorrect for either of the classes.
6133 // Same IMT with new_conflict does not happen very often.
6134 if (!new_conflict) {
6135 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
6136 if (super_imt != nullptr) {
6137 bool imt_equals = true;
6138 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
6139 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
6140 }
6141 if (imt_equals) {
6142 imt = super_imt;
6143 }
6144 }
6145 }
6146 if (imt == nullptr) {
6147 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
6148 imt = reinterpret_cast<ImTable*>(
6149 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
6150 if (imt == nullptr) {
6151 return false;
6152 }
6153 imt->Populate(imt_data, image_pointer_size_);
6154 }
6155 }
6156
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006157 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
6158 // We don't need to retire this class as it has no embedded tables or it was created the
6159 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006160 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006161
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006162 if (klass->ShouldHaveEmbeddedVTable()) {
6163 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006164 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006165 if (klass->ShouldHaveImt()) {
6166 klass->SetImt(imt, image_pointer_size_);
6167 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006168
6169 // Update CHA info based on whether we override methods.
6170 // Have to do this before setting the class as resolved which allows
6171 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006172 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006173 cha_->UpdateAfterLoadingOf(klass);
6174 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006175
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006176 // This will notify waiters on klass that saw the not yet resolved
6177 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006178 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006179 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006180 } else {
6181 CHECK(!klass->IsResolved());
6182 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006183 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006184 Handle<mirror::Class> h_new_class =
6185 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006186 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6187 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6188 // may not see any references to the target space and clean the card for a class if another
6189 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006190 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006191 klass->SetSFieldsPtrUnchecked(nullptr);
6192 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006193 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006194 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006195 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006196 return false;
6197 }
6198
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006199 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6200 ObjectLock<mirror::Class> lock(self, h_new_class);
6201 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006202
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006203 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006204 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006205 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006206 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006207 const ObjPtr<mirror::Class> existing =
6208 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006209 if (class_loader != nullptr) {
6210 // We updated the class in the class table, perform the write barrier so that the GC knows
6211 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006212 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006213 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006214 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006215 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006216 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6217 }
6218 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006219
Mingyao Yang063fc772016-08-02 11:02:54 -07006220 // Update CHA info based on whether we override methods.
6221 // Have to do this before setting the class as resolved which allows
6222 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006223 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006224 cha_->UpdateAfterLoadingOf(h_new_class);
6225 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006226
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006227 // This will notify waiters on temp class that saw the not yet resolved class in the
6228 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006229 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006230
Vladimir Marko2c64a832018-01-04 11:31:56 +00006231 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006232 // This will notify waiters on new_class that saw the not yet resolved
6233 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006234 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006235 // Return the new class.
6236 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006237 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006238 return true;
6239}
6240
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006241bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006242 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006243 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006244 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6245 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006246 // Check that a class does not inherit from itself directly.
6247 //
6248 // TODO: This is a cheap check to detect the straightforward case
6249 // of a class extending itself (b/28685551), but we should do a
6250 // proper cycle detection on loaded classes, to detect all cases
6251 // of class circularity errors (b/28830038).
6252 if (super_class_idx == class_def.class_idx_) {
6253 ThrowClassCircularityError(klass.Get(),
6254 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006255 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006256 return false;
6257 }
6258
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006259 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006260 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006261 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006262 return false;
6263 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006264 // Verify
6265 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006266 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006267 super_class->PrettyDescriptor().c_str(),
6268 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006269 return false;
6270 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006271 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006272 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006273 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006274 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006275 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006276 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006277 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006278 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006279 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006280 DCHECK(Thread::Current()->IsExceptionPending());
6281 return false;
6282 }
6283 // Verify
6284 if (!klass->CanAccess(interface)) {
6285 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006286 ThrowIllegalAccessError(klass.Get(),
6287 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006288 interface->PrettyDescriptor().c_str(),
6289 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006290 return false;
6291 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006292 }
6293 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006294 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006295 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006296 return true;
6297}
6298
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006299bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006300 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006301 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006302 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6303 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006304 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006305 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006306 return false;
6307 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006308 return true;
6309 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006310 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006311 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006312 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006313 return false;
6314 }
6315 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006316 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006317 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6318 return false;
6319 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006320 if (super->IsFinal()) {
6321 ThrowVerifyError(klass.Get(),
6322 "Superclass %s of %s is declared final",
6323 super->PrettyDescriptor().c_str(),
6324 klass->PrettyDescriptor().c_str());
6325 return false;
6326 }
6327 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006328 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006329 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006330 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006331 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006332 return false;
6333 }
6334 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006335 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006336 super->PrettyDescriptor().c_str(),
6337 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006338 return false;
6339 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006340
Brian Carlstromf3632832014-05-20 15:36:53 -07006341 // Inherit kAccClassIsFinalizable from the superclass in case this
6342 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006343 if (super->IsFinalizable()) {
6344 klass->SetFinalizable();
6345 }
6346
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006347 // Inherit class loader flag form super class.
6348 if (super->IsClassLoaderClass()) {
6349 klass->SetClassLoaderClass();
6350 }
6351
Elliott Hughes2da50362011-10-10 16:57:08 -07006352 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006353 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006354 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006355 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006356 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006357 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006358 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006359 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006360 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006361 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006362 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006363 return false;
6364 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006365
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006366 if (kIsDebugBuild) {
6367 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006368 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006369 CHECK(super->IsResolved());
6370 super = super->GetSuperClass();
6371 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006372 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006373 return true;
6374}
6375
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006376// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006377bool ClassLinker::LinkMethods(Thread* self,
6378 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006379 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006380 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006381 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006382 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006383 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6384 // need to have default methods be in the virtuals array of each class but we don't set that up
6385 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006386 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006387 // Link virtual methods then interface methods.
6388 // We set up the interface lookup table first because we need it to determine if we need to update
6389 // any vtable entries with new default method implementations.
6390 return SetupInterfaceLookupTable(self, klass, interfaces)
6391 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006392 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006393}
6394
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006395// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6396// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6397// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006398class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006399 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006400 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006401 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006402 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6403 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006404 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006405 }
6406
6407 const char* GetName() {
6408 if (name_ == nullptr) {
6409 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6410 }
6411 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006412 }
6413
Mathieu Chartiere401d142015-04-22 13:56:20 -07006414 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006415 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006416 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006417 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006418 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006419 if (dex_file_ == other_dex_file) {
6420 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6421 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006422 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006423 uint32_t other_name_len;
6424 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6425 &other_name_len);
6426 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6427 return false;
6428 }
6429 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6430 }
6431
6432 private:
6433 // Dex file for the method to compare against.
6434 const DexFile* const dex_file_;
6435 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006436 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006437 // Lazily computed name from the dex file's strings.
6438 const char* name_;
6439 // Lazily computed name length.
6440 uint32_t name_len_;
6441};
6442
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006443class LinkVirtualHashTable {
6444 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006445 LinkVirtualHashTable(Handle<mirror::Class> klass,
6446 size_t hash_size,
6447 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006448 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006449 : klass_(klass),
6450 hash_size_(hash_size),
6451 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006452 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006453 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6454 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006455
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006456 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006457 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6458 virtual_method_index, image_pointer_size_);
6459 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006460 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006461 uint32_t index = hash % hash_size_;
6462 // Linear probe until we have an empty slot.
6463 while (hash_table_[index] != invalid_index_) {
6464 if (++index == hash_size_) {
6465 index = 0;
6466 }
6467 }
6468 hash_table_[index] = virtual_method_index;
6469 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006470
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006471 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006472 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006473 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006474 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006475 size_t index = hash % hash_size_;
6476 while (true) {
6477 const uint32_t value = hash_table_[index];
6478 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6479 // the block and can safely assume not found.
6480 if (value == invalid_index_) {
6481 break;
6482 }
6483 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006484 ArtMethod* virtual_method =
6485 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6486 if (comparator->HasSameNameAndSignature(
6487 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006488 hash_table_[index] = removed_index_;
6489 return value;
6490 }
6491 }
6492 if (++index == hash_size_) {
6493 index = 0;
6494 }
6495 }
6496 return GetNotFoundIndex();
6497 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006498
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006499 static uint32_t GetNotFoundIndex() {
6500 return invalid_index_;
6501 }
6502
6503 private:
6504 static const uint32_t invalid_index_;
6505 static const uint32_t removed_index_;
6506
6507 Handle<mirror::Class> klass_;
6508 const size_t hash_size_;
6509 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006510 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006511};
6512
6513const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6514const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6515
Stephen Hines1ddd9132017-02-08 01:51:18 -08006516bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006517 Thread* self,
6518 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006519 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006520 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006521 if (klass->IsInterface()) {
6522 // No vtable.
6523 if (!IsUint<16>(num_virtual_methods)) {
6524 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6525 return false;
6526 }
6527 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006528 // Assign each method an IMT index and set the default flag.
6529 for (size_t i = 0; i < num_virtual_methods; ++i) {
6530 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6531 m->SetMethodIndex(i);
6532 if (!m->IsAbstract()) {
6533 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6534 has_defaults = true;
6535 }
6536 }
6537 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6538 // during initialization. This is a performance optimization. We could simply traverse the
6539 // virtual_methods_ array again during initialization.
6540 if (has_defaults) {
6541 klass->SetHasDefaultMethods();
6542 }
6543 return true;
6544 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006545 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6546 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006547 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006548 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006549 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006550 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006551 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006552 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006553 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006554 return false;
6555 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006556 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006557 vtable->SetElementPtrSize(
6558 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006559 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006560 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6561 // might give us new default methods). If no new interfaces then we can skip the rest since
6562 // the class cannot override any of the super-class's methods. This is required for
6563 // correctness since without it we might not update overridden default method vtable entries
6564 // correctly.
6565 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006566 klass->SetVTable(vtable.Get());
6567 return true;
6568 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006569 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006570 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006571 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006572 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006573 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6574 // might give us new default methods). See comment above.
6575 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006576 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006577 return true;
6578 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006579 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6580 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006581 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006582 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006583 return false;
6584 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006585 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006586 // How the algorithm works:
6587 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6588 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6589 // method which has not been matched to a vtable method, and j if the virtual method at the
6590 // index overrode the super virtual method at index j.
6591 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6592 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6593 // the need for the initial vtable which we later shrink back down).
6594 // 3. Add non overridden methods to the end of the vtable.
6595 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006596 // + 1 so that even if we only have new default methods we will still be able to use this hash
6597 // table (i.e. it will never have 0 size).
6598 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006599 uint32_t* hash_table_ptr;
6600 std::unique_ptr<uint32_t[]> hash_heap_storage;
6601 if (hash_table_size <= kMaxStackHash) {
6602 hash_table_ptr = reinterpret_cast<uint32_t*>(
6603 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6604 } else {
6605 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6606 hash_table_ptr = hash_heap_storage.get();
6607 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006608 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006609 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006610 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006611 DCHECK(klass->GetVirtualMethodDuringLinking(
6612 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006613 hash_table.Add(i);
6614 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006615 // 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 -07006616 // the hash table.
6617 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006618 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006619 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006620 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6621 super_method->GetAccessFlags())) {
6622 // Continue on to the next method since this one is package private and canot be overridden.
6623 // Before Android 4.1, the package-private method super_method might have been incorrectly
6624 // overridden.
6625 continue;
6626 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006627 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006628 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006629 // We remove the method so that subsequent lookups will be faster by making the hash-map
6630 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006631 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6632 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006633 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6634 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006635 if (super_method->IsFinal()) {
6636 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6637 virtual_method->PrettyMethod().c_str(),
6638 super_method->GetDeclaringClassDescriptor());
6639 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006640 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006641 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6642 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006643 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006644 // We didn't directly override this method but we might through default methods...
6645 // Check for default method update.
6646 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006647 switch (FindDefaultMethodImplementation(self,
6648 super_method,
6649 klass,
6650 /*out*/&default_method)) {
6651 case DefaultMethodSearchResult::kDefaultConflict: {
6652 // A conflict was found looking for default methods. Note this (assuming it wasn't
6653 // pre-existing) in the translations map.
6654 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6655 // Don't generate another conflict method to reduce memory use as an optimization.
6656 default_translations->insert(
6657 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6658 }
6659 break;
6660 }
6661 case DefaultMethodSearchResult::kAbstractFound: {
6662 // No conflict but method is abstract.
6663 // We note that this vtable entry must be made abstract.
6664 if (UNLIKELY(!super_method->IsAbstract())) {
6665 default_translations->insert(
6666 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6667 }
6668 break;
6669 }
6670 case DefaultMethodSearchResult::kDefaultFound: {
6671 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6672 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6673 // Found a default method implementation that is new.
6674 // TODO Refactor this add default methods to virtuals here and not in
6675 // LinkInterfaceMethods maybe.
6676 // The problem is default methods might override previously present
6677 // default-method or miranda-method vtable entries from the superclass.
6678 // Unfortunately we need these to be entries in this class's virtuals. We do not
6679 // give these entries there until LinkInterfaceMethods so we pass this map around
6680 // to let it know which vtable entries need to be updated.
6681 // Make a note that vtable entry j must be updated, store what it needs to be updated
6682 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6683 // then.
6684 default_translations->insert(
6685 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006686 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6687 << " overridden by default "
6688 << default_method->PrettyMethod()
6689 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006690 }
6691 break;
6692 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006693 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006694 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006695 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006696 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006697 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006698 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006699 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006700 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6701 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006702 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006703 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006704 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006705 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006706 local_method->SetMethodIndex(actual_count);
6707 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006708 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006709 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006710 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006711 return false;
6712 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006713 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006714 CHECK_LE(actual_count, max_count);
6715 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006716 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6717 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006718 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006719 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006720 return false;
6721 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006722 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006723 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006724 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006725 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006726 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006727 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6728 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006729 return false;
6730 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006731 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006732 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006733 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006734 return false;
6735 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006736 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006737 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6738 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006739 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006740 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006741 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006742 }
6743 return true;
6744}
6745
Alex Light9139e002015-10-09 15:59:48 -07006746// Determine if the given iface has any subinterface in the given list that declares the method
6747// specified by 'target'.
6748//
6749// Arguments
6750// - self: The thread we are running on
6751// - target: A comparator that will match any method that overrides the method we are checking for
6752// - iftable: The iftable we are searching for an overriding method on.
6753// - ifstart: The index of the interface we are checking to see if anything overrides
6754// - iface: The interface we are checking to see if anything overrides.
6755// - image_pointer_size:
6756// The image pointer size.
6757//
6758// Returns
6759// - True: There is some method that matches the target comparator defined in an interface that
6760// is a subtype of iface.
6761// - False: There is no method that matches the target comparator in any interface that is a subtype
6762// of iface.
6763static bool ContainsOverridingMethodOf(Thread* self,
6764 MethodNameAndSignatureComparator& target,
6765 Handle<mirror::IfTable> iftable,
6766 size_t ifstart,
6767 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006768 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006769 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006770 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006771 DCHECK(iface != nullptr);
6772 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006773 DCHECK_GE(ifstart, 0u);
6774 DCHECK_LT(ifstart, iftable->Count());
6775 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6776 DCHECK(iface->IsInterface());
6777
6778 size_t iftable_count = iftable->Count();
6779 StackHandleScope<1> hs(self);
6780 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6781 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6782 // Skip ifstart since our current interface obviously cannot override itself.
6783 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006784 // Iterate through every method on this interface. The order does not matter.
6785 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006786 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006787 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006788 // Check if the i'th interface is a subtype of this one.
6789 if (iface->IsAssignableFrom(current_iface.Get())) {
6790 return true;
6791 }
6792 break;
6793 }
6794 }
6795 }
6796 return false;
6797}
6798
Alex Lighteb7c1442015-08-31 13:17:42 -07006799// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006800// out_default_method and returns kDefaultFound on success. If no default method was found return
6801// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6802// default_method conflict) it will return kDefaultConflict.
6803ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6804 Thread* self,
6805 ArtMethod* target_method,
6806 Handle<mirror::Class> klass,
6807 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006808 DCHECK(self != nullptr);
6809 DCHECK(target_method != nullptr);
6810 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006811
6812 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006813
6814 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6815 // table. This lets us walk the table backwards when searching for default methods. The first one
6816 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6817 // track of it and then continue checking all other interfaces, since we need to throw an error if
6818 // we encounter conflicting default method implementations (one is not a subtype of the other).
6819 //
6820 // The order of unrelated interfaces does not matter and is not defined.
6821 size_t iftable_count = klass->GetIfTableCount();
6822 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006823 // No interfaces. We have already reset out to null so just return kAbstractFound.
6824 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006825 }
6826
Alex Light9139e002015-10-09 15:59:48 -07006827 StackHandleScope<3> hs(self);
6828 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006829 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006830 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006831 MethodNameAndSignatureComparator target_name_comparator(
6832 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6833 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006834 for (size_t k = iftable_count; k != 0; ) {
6835 --k;
6836
Alex Lighteb7c1442015-08-31 13:17:42 -07006837 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006838
6839 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006840 // Iterate through every declared method on this interface. The order does not matter.
6841 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6842 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006843 // Skip abstract methods and methods with different names.
6844 if (current_method->IsAbstract() ||
6845 !target_name_comparator.HasSameNameAndSignature(
6846 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6847 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006848 } else if (!current_method->IsPublic()) {
6849 // The verifier should have caught the non-public method for dex version 37. Just warn and
6850 // skip it since this is from before default-methods so we don't really need to care that it
6851 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006852 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6853 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006854 << "This will be a fatal error in subsequent versions of android. "
6855 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006856 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006857 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006858 // We have multiple default impls of the same method. This is a potential default conflict.
6859 // We need to check if this possibly conflicting method is either a superclass of the chosen
6860 // default implementation or is overridden by a non-default interface method. In either case
6861 // there is no conflict.
6862 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6863 !ContainsOverridingMethodOf(self,
6864 target_name_comparator,
6865 iftable,
6866 k,
6867 iface,
6868 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006869 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006870 << current_method->PrettyMethod() << " and "
6871 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6872 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006873 *out_default_method = nullptr;
6874 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006875 } else {
6876 break; // Continue checking at the next interface.
6877 }
6878 } else {
Alex Light9139e002015-10-09 15:59:48 -07006879 // chosen_iface == null
6880 if (!ContainsOverridingMethodOf(self,
6881 target_name_comparator,
6882 iftable,
6883 k,
6884 iface,
6885 image_pointer_size_)) {
6886 // Don't set this as the chosen interface if something else is overriding it (because that
6887 // other interface would be potentially chosen instead if it was default). If the other
6888 // interface was abstract then we wouldn't select this interface as chosen anyway since
6889 // the abstract method masks it.
6890 *out_default_method = current_method;
6891 chosen_iface.Assign(iface.Get());
6892 // We should now finish traversing the graph to find if we have default methods that
6893 // conflict.
6894 } else {
David Sehr709b0702016-10-13 09:12:37 -07006895 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6896 << "' was "
6897 << "skipped because it was overridden by an abstract method in a "
6898 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006899 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006900 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006901 break;
6902 }
6903 }
Alex Light9139e002015-10-09 15:59:48 -07006904 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006905 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6906 << "' selected "
6907 << "as the implementation for '" << target_method->PrettyMethod()
6908 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006909 return DefaultMethodSearchResult::kDefaultFound;
6910 } else {
6911 return DefaultMethodSearchResult::kAbstractFound;
6912 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006913}
6914
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006915ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006916 ArtMethod* conflict_method,
6917 ArtMethod* interface_method,
6918 ArtMethod* method,
6919 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006920 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006921 Runtime* const runtime = Runtime::Current();
6922 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6923 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6924
6925 // Create a new entry if the existing one is the shared conflict method.
6926 ArtMethod* new_conflict_method = new_entry
6927 ? runtime->CreateImtConflictMethod(linear_alloc)
6928 : conflict_method;
6929
6930 // Allocate a new table. Note that we will leak this table at the next conflict,
6931 // but that's a tradeoff compared to making the table fixed size.
6932 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006933 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6934 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006935 if (data == nullptr) {
6936 LOG(ERROR) << "Failed to allocate conflict table";
6937 return conflict_method;
6938 }
6939 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6940 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006941 method,
6942 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006943
6944 // Do a fence to ensure threads see the data in the table before it is assigned
6945 // to the conflict method.
6946 // Note that there is a race in the presence of multiple threads and we may leak
6947 // memory from the LinearAlloc, but that's a tradeoff compared to using
6948 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006949 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006950 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006951 return new_conflict_method;
6952}
6953
Vladimir Marko921094a2017-01-12 18:37:06 +00006954bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6955 Handle<mirror::Class> klass,
6956 Handle<mirror::IfTable> iftable) {
6957 DCHECK(!klass->IsInterface());
6958 const bool has_superclass = klass->HasSuperClass();
6959 const bool extend_super_iftable = has_superclass;
6960 const size_t ifcount = klass->GetIfTableCount();
6961 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6962 for (size_t i = 0; i < ifcount; ++i) {
6963 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6964 if (num_methods > 0) {
6965 const bool is_super = i < super_ifcount;
6966 // This is an interface implemented by a super-class. Therefore we can just copy the method
6967 // array from the superclass.
6968 const bool super_interface = is_super && extend_super_iftable;
6969 ObjPtr<mirror::PointerArray> method_array;
6970 if (super_interface) {
6971 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6972 DCHECK(if_table != nullptr);
6973 DCHECK(if_table->GetMethodArray(i) != nullptr);
6974 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006975 StackHandleScope<1u> hs(self);
6976 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6977 method_array =
6978 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006979 } else {
6980 method_array = AllocPointerArray(self, num_methods);
6981 }
6982 if (UNLIKELY(method_array == nullptr)) {
6983 self->AssertPendingOOMException();
6984 return false;
6985 }
6986 iftable->SetMethodArray(i, method_array);
6987 }
6988 }
6989 return true;
6990}
6991
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006992void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6993 ArtMethod* imt_conflict_method,
6994 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006995 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006996 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006997 // Place method in imt if entry is empty, place conflict otherwise.
6998 if (*imt_ref == unimplemented_method) {
6999 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00007000 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007001 // If we are not a conflict and we have the same signature and name as the imt
7002 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00007003 // Note that we have checked IsRuntimeMethod, as there may be multiple different
7004 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007005 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007006 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07007007 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007008 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007009 *imt_ref = current_method;
7010 } else {
Alex Light9139e002015-10-09 15:59:48 -07007011 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007012 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07007013 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00007014 } else {
7015 // Place the default conflict method. Note that there may be an existing conflict
7016 // method in the IMT, but it could be one tailored to the super class, with a
7017 // specific ImtConflictTable.
7018 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007019 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07007020 }
7021}
7022
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007023void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07007024 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
7025 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007026 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007027 Runtime* const runtime = Runtime::Current();
7028 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
7029 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007030 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007031 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007032 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007033 FillIMTFromIfTable(klass->GetIfTable(),
7034 unimplemented_method,
7035 conflict_method,
7036 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007037 /*create_conflict_tables=*/true,
7038 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007039 &new_conflict,
7040 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007041 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007042 if (!klass->ShouldHaveImt()) {
7043 return;
7044 }
7045 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
7046 // we can just use the same pointer.
7047 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007048 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007049 if (super_class != nullptr && super_class->ShouldHaveImt()) {
7050 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7051 bool same = true;
7052 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
7053 ArtMethod* method = imt_data[i];
7054 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
7055 if (method != super_method) {
7056 bool is_conflict_table = method->IsRuntimeMethod() &&
7057 method != unimplemented_method &&
7058 method != conflict_method;
7059 // Verify conflict contents.
7060 bool super_conflict_table = super_method->IsRuntimeMethod() &&
7061 super_method != unimplemented_method &&
7062 super_method != conflict_method;
7063 if (!is_conflict_table || !super_conflict_table) {
7064 same = false;
7065 } else {
7066 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
7067 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
7068 same = same && table1->Equals(table2, image_pointer_size_);
7069 }
7070 }
7071 }
7072 if (same) {
7073 imt = super_imt;
7074 }
7075 }
7076 if (imt == nullptr) {
7077 imt = klass->GetImt(image_pointer_size_);
7078 DCHECK(imt != nullptr);
7079 imt->Populate(imt_data, image_pointer_size_);
7080 } else {
7081 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007082 }
7083}
7084
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007085ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
7086 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07007087 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007088 void* data = linear_alloc->Alloc(Thread::Current(),
7089 ImtConflictTable::ComputeSize(count,
7090 image_pointer_size));
7091 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
7092}
7093
7094ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
7095 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
7096}
7097
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007098void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007099 ArtMethod* unimplemented_method,
7100 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007101 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007102 bool create_conflict_tables,
7103 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007104 /*out*/bool* new_conflict,
7105 /*out*/ArtMethod** imt) {
7106 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007107 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007108 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007109 const size_t num_virtuals = interface->NumVirtualMethods();
7110 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7111 // Virtual methods can be larger than the if table methods if there are default methods.
7112 DCHECK_GE(num_virtuals, method_array_count);
7113 if (kIsDebugBuild) {
7114 if (klass->IsInterface()) {
7115 DCHECK_EQ(method_array_count, 0u);
7116 } else {
7117 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
7118 }
7119 }
7120 if (method_array_count == 0) {
7121 continue;
7122 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007123 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007124 for (size_t j = 0; j < method_array_count; ++j) {
7125 ArtMethod* implementation_method =
7126 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7127 if (ignore_copied_methods && implementation_method->IsCopied()) {
7128 continue;
7129 }
7130 DCHECK(implementation_method != nullptr);
7131 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7132 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7133 // or interface methods in the IMT here they will not create extra conflicts since we compare
7134 // names and signatures in SetIMTRef.
7135 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007136 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007137
7138 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7139 // the same implementation method, keep track of this to avoid creating a conflict table in
7140 // this case.
7141
7142 // Conflict table size for each IMT slot.
7143 ++conflict_counts[imt_index];
7144
7145 SetIMTRef(unimplemented_method,
7146 imt_conflict_method,
7147 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007148 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007149 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007150 }
7151 }
7152
7153 if (create_conflict_tables) {
7154 // Create the conflict tables.
7155 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007156 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007157 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007158 if (imt[i] == imt_conflict_method) {
7159 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7160 if (new_table != nullptr) {
7161 ArtMethod* new_conflict_method =
7162 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7163 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7164 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007165 } else {
7166 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007167 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007168 }
7169 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007170 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007171 }
7172 }
7173
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007174 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007175 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007176 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7177 // Virtual methods can be larger than the if table methods if there are default methods.
7178 if (method_array_count == 0) {
7179 continue;
7180 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007181 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007182 for (size_t j = 0; j < method_array_count; ++j) {
7183 ArtMethod* implementation_method =
7184 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7185 if (ignore_copied_methods && implementation_method->IsCopied()) {
7186 continue;
7187 }
7188 DCHECK(implementation_method != nullptr);
7189 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007190 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007191 if (!imt[imt_index]->IsRuntimeMethod() ||
7192 imt[imt_index] == unimplemented_method ||
7193 imt[imt_index] == imt_conflict_method) {
7194 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007195 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007196 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7197 const size_t num_entries = table->NumEntries(image_pointer_size_);
7198 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7199 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007200 }
7201 }
7202 }
7203}
7204
Alex Lighteb7c1442015-08-31 13:17:42 -07007205// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7206// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007207static bool NotSubinterfaceOfAny(
7208 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
7209 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007210 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007211 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007212 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007213 for (ObjPtr<mirror::Class> c : classes) {
7214 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007215 return false;
7216 }
7217 }
7218 return true;
7219}
7220
7221// Fills in and flattens the interface inheritance hierarchy.
7222//
7223// By the end of this function all interfaces in the transitive closure of to_process are added to
7224// the iftable and every interface precedes all of its sub-interfaces in this list.
7225//
7226// all I, J: Interface | I <: J implies J precedes I
7227//
7228// (note A <: B means that A is a subtype of B)
7229//
7230// This returns the total number of items in the iftable. The iftable might be resized down after
7231// this call.
7232//
7233// We order this backwards so that we do not need to reorder superclass interfaces when new
7234// interfaces are added in subclass's interface tables.
7235//
7236// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7237// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7238// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7239// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007240static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007241 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07007242 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07007243 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007244 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007245 // This is the set of all class's already in the iftable. Used to make checking if a class has
7246 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007247 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07007248 // The first super_ifcount elements are from the superclass. We note that they are already added.
7249 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007250 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007251 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
7252 classes_in_iftable.insert(iface);
7253 }
7254 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007255 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007256 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7257 // At this point in the loop current-iface-list has the invariant that:
7258 // for every pair of interfaces I,J within it:
7259 // if index_of(I) < index_of(J) then I is not a subtype of J
7260
7261 // If we have already seen this element then all of its super-interfaces must already be in the
7262 // current-iface-list so we can skip adding it.
7263 if (!ContainsElement(classes_in_iftable, interface)) {
7264 // We haven't seen this interface so add all of its super-interfaces onto the
7265 // current-iface-list, skipping those already on it.
7266 int32_t ifcount = interface->GetIfTableCount();
7267 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007268 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007269 if (!ContainsElement(classes_in_iftable, super_interface)) {
7270 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
7271 classes_in_iftable.insert(super_interface);
7272 iftable->SetInterface(filled_ifcount, super_interface);
7273 filled_ifcount++;
7274 }
7275 }
7276 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7277 // Place this interface onto the current-iface-list after all of its super-interfaces.
7278 classes_in_iftable.insert(interface);
7279 iftable->SetInterface(filled_ifcount, interface);
7280 filled_ifcount++;
7281 } else if (kIsDebugBuild) {
7282 // Check all super-interfaces are already in the list.
7283 int32_t ifcount = interface->GetIfTableCount();
7284 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007285 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007286 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007287 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7288 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007289 }
7290 }
7291 }
7292 if (kIsDebugBuild) {
7293 // Check that the iftable is ordered correctly.
7294 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007295 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007296 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007297 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007298 // !(if_a <: if_b)
7299 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007300 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7301 << ") extends "
7302 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007303 << "interface list.";
7304 }
7305 }
7306 }
7307 return filled_ifcount;
7308}
7309
7310bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
7311 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7312 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007313 const bool has_superclass = klass->HasSuperClass();
7314 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007315 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007316 const size_t num_interfaces =
7317 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007318 if (num_interfaces == 0) {
7319 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007320 if (LIKELY(has_superclass)) {
7321 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7322 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007323 // Class implements no interfaces.
7324 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007325 return true;
7326 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007327 // Class implements same interfaces as parent, are any of these not marker interfaces?
7328 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007329 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007330 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007331 if (super_iftable->GetMethodArrayCount(i) > 0) {
7332 has_non_marker_interface = true;
7333 break;
7334 }
7335 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007336 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007337 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007338 klass->SetIfTable(super_iftable);
7339 return true;
7340 }
7341 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007342 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007343 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007344 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007345 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007346 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007347 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007348 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007349 if (UNLIKELY(!interface->IsInterface())) {
7350 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007351 ThrowIncompatibleClassChangeError(klass.Get(),
7352 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007353 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007354 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7355 return false;
7356 }
7357 ifcount += interface->GetIfTableCount();
7358 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007359 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007360 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007361 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007362 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007363 return false;
7364 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007365 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007366 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007367 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007368 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007369 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007370 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007371 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007372 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007373
7374 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7375 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7376 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007377 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007378
7379 size_t new_ifcount;
7380 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007381 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007382 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007383 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007384 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007385 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007386 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007387 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007388
7389 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007390 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007391
Ian Rogers7b078e82014-09-10 14:44:24 -07007392 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007393
Ian Rogersb52b01a2012-01-12 17:01:38 -08007394 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007395 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007396 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007397 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007398 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007399 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007400 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007401 return false;
7402 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007403 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007404 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007405 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007406 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007407 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007408 return true;
7409}
7410
Alex Light1f3925d2016-09-07 12:04:20 -07007411// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7412// of methods must be unique.
7413static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7414 return nullptr;
7415}
7416
7417template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007418static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007419 const ScopedArenaVector<ArtMethod*>& list,
7420 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007421 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007422 for (ArtMethod* method : list) {
7423 if (cmp.HasSameNameAndSignature(method)) {
7424 return method;
7425 }
7426 }
Alex Light1f3925d2016-09-07 12:04:20 -07007427 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007428}
7429
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007430namespace {
7431
Alex Light1f3925d2016-09-07 12:04:20 -07007432// Check that all vtable entries are present in this class's virtuals or are the same as a
7433// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007434void CheckClassOwnsVTableEntries(Thread* self,
7435 Handle<mirror::Class> klass,
7436 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007437 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007438 StackHandleScope<2> hs(self);
7439 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007440 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007441 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007442 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007443 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7444 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7445 CHECK(m != nullptr);
7446
Alex Lighta41a30782017-03-29 11:33:19 -07007447 if (m->GetMethodIndexDuringLinking() != i) {
7448 LOG(WARNING) << m->PrettyMethod()
7449 << " has an unexpected method index for its spot in the vtable for class"
7450 << klass->PrettyClass();
7451 }
Alex Lighte64300b2015-12-15 15:02:47 -08007452 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7453 auto is_same_method = [m] (const ArtMethod& meth) {
7454 return &meth == m;
7455 };
Alex Light3f980532017-03-17 15:10:32 -07007456 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7457 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7458 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7459 << klass->PrettyClass() << " or any of its superclasses!";
7460 }
Alex Lighte64300b2015-12-15 15:02:47 -08007461 }
7462}
7463
Alex Light1f3925d2016-09-07 12:04:20 -07007464// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7465// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007466template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007467void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007468 REQUIRES_SHARED(Locks::mutator_lock_) {
7469 StackHandleScope<1> hs(self);
7470 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7471 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007472
7473 // Observations:
7474 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7475 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7476 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7477 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7478 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7479 // * The single-pass algorithm will trade memory for speed, but that is OK.
7480
7481 CHECK_GT(num_entries, 0);
7482
7483 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7484 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7485 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7486 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7487 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7488 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7489 << m2->PrettyMethod() << " (0x" << std::hex
7490 << reinterpret_cast<uintptr_t>(m2) << ")";
7491 };
7492 struct BaseHashType {
7493 static size_t HashCombine(size_t seed, size_t val) {
7494 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7495 }
7496 };
7497
7498 // Check assuming all entries come from the same dex file.
7499 {
7500 // Find the first interesting method and its dex file.
7501 int32_t start = 0;
7502 for (; start < num_entries; ++start) {
7503 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7504 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7505 // maybe).
7506 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7507 vtable_entry->GetAccessFlags())) {
7508 continue;
7509 }
7510 break;
7511 }
7512 if (start == num_entries) {
7513 return;
7514 }
7515 const DexFile* dex_file =
7516 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7517 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7518
7519 // Helper function to avoid logging if we have to run the cross-file checks.
7520 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7521 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7522 using PairType = std::pair<uint32_t, uint16_t>;
7523 struct PairHash : BaseHashType {
7524 size_t operator()(const PairType& key) const {
7525 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7526 }
7527 };
7528 std::unordered_map<PairType, int32_t, PairHash> seen;
7529 seen.reserve(2 * num_entries);
7530 bool need_slow_path = false;
7531 bool found_dup = false;
7532 for (int i = start; i < num_entries; ++i) {
7533 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7534 // wrt/ kPointerSize.
7535 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7536 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7537 vtable_entry->GetAccessFlags())) {
7538 continue;
7539 }
7540 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7541 if (dex_file != m->GetDexFile()) {
7542 need_slow_path = true;
7543 break;
7544 }
7545 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7546 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7547 auto it = seen.find(pair);
7548 if (it != seen.end()) {
7549 found_dup = true;
7550 if (log_warn) {
7551 log_fn(it->second, i);
7552 }
7553 } else {
7554 seen.emplace(pair, i);
7555 }
7556 }
7557 return std::make_pair(need_slow_path, found_dup);
7558 };
7559 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7560 if (!result.first) {
7561 if (result.second) {
7562 check_fn(/* log_warn= */ true);
7563 }
7564 return;
7565 }
7566 }
7567
7568 // Need to check across dex files.
7569 struct Entry {
7570 size_t cached_hash = 0;
7571 const char* name = nullptr;
7572 Signature signature = Signature::NoSignature();
7573 uint32_t name_len = 0;
7574
7575 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7576 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7577 signature(dex_file->GetMethodSignature(mid)) {
7578 }
7579
7580 bool operator==(const Entry& other) const {
7581 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7582 return false;
7583 }
7584 return signature == other.signature;
7585 }
7586 };
7587 struct EntryHash {
7588 size_t operator()(const Entry& key) const {
7589 return key.cached_hash;
7590 }
7591 };
7592 std::unordered_map<Entry, int32_t, EntryHash> map;
7593 for (int32_t i = 0; i < num_entries; ++i) {
7594 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7595 // wrt/ kPointerSize.
7596 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7597 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7598 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007599 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7600 vtable_entry->GetAccessFlags())) {
7601 continue;
7602 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007603 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7604 const DexFile* dex_file = m->GetDexFile();
7605 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7606
7607 Entry e(dex_file, mid);
7608
7609 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7610 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7611 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7612 sig_hash);
7613
7614 auto it = map.find(e);
7615 if (it != map.end()) {
7616 log_fn(it->second, i);
7617 } else {
7618 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007619 }
7620 }
7621}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007622
7623void CheckVTableHasNoDuplicates(Thread* self,
7624 Handle<mirror::Class> klass,
7625 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007626 REQUIRES_SHARED(Locks::mutator_lock_) {
7627 switch (pointer_size) {
7628 case PointerSize::k64:
7629 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7630 break;
7631 case PointerSize::k32:
7632 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7633 break;
7634 }
7635}
Alex Light1f3925d2016-09-07 12:04:20 -07007636
7637static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7638 REQUIRES_SHARED(Locks::mutator_lock_) {
7639 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7640 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7641}
7642
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007643} // namespace
7644
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007645void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7646 ArtMethod* unimplemented_method,
7647 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007648 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007649 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007650 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007651 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007652 if (super_class->ShouldHaveImt()) {
7653 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7654 for (size_t i = 0; i < ImTable::kSize; ++i) {
7655 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007656 }
7657 } else {
7658 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007659 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007660 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007661 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007662 FillIMTFromIfTable(if_table,
7663 unimplemented_method,
7664 imt_conflict_method,
7665 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007666 /*create_conflict_tables=*/false,
7667 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007668 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007669 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007670 }
7671 }
7672}
7673
Vladimir Marko921094a2017-01-12 18:37:06 +00007674class ClassLinker::LinkInterfaceMethodsHelper {
7675 public:
7676 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7677 Handle<mirror::Class> klass,
7678 Thread* self,
7679 Runtime* runtime)
7680 : class_linker_(class_linker),
7681 klass_(klass),
7682 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7683 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7684 self_(self),
7685 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7686 allocator_(&stack_),
7687 default_conflict_methods_(allocator_.Adapter()),
7688 overriding_default_conflict_methods_(allocator_.Adapter()),
7689 miranda_methods_(allocator_.Adapter()),
7690 default_methods_(allocator_.Adapter()),
7691 overriding_default_methods_(allocator_.Adapter()),
7692 move_table_(allocator_.Adapter()) {
7693 }
7694
7695 ArtMethod* FindMethod(ArtMethod* interface_method,
7696 MethodNameAndSignatureComparator& interface_name_comparator,
7697 ArtMethod* vtable_impl)
7698 REQUIRES_SHARED(Locks::mutator_lock_);
7699
7700 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7701 MethodNameAndSignatureComparator& interface_name_comparator)
7702 REQUIRES_SHARED(Locks::mutator_lock_);
7703
7704 bool HasNewVirtuals() const {
7705 return !(miranda_methods_.empty() &&
7706 default_methods_.empty() &&
7707 overriding_default_methods_.empty() &&
7708 overriding_default_conflict_methods_.empty() &&
7709 default_conflict_methods_.empty());
7710 }
7711
7712 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7713
7714 ObjPtr<mirror::PointerArray> UpdateVtable(
7715 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007716 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007717
7718 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7719
7720 void UpdateIMT(ArtMethod** out_imt);
7721
7722 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7723 if (kIsDebugBuild) {
7724 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7725 // Check that there are no stale methods are in the dex cache array.
7726 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7727 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007728 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7729 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007730 CHECK(move_table_.find(m) == move_table_.end() ||
7731 // The original versions of copied methods will still be present so allow those too.
7732 // Note that if the first check passes this might fail to GetDeclaringClass().
7733 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7734 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7735 [m] (ArtMethod& meth) {
7736 return &meth == m;
7737 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7738 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7739 }
7740 }
7741 }
7742
7743 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7744 LengthPrefixedArray<ArtMethod>* methods) {
7745 if (kIsDebugBuild) {
7746 CHECK(methods != nullptr);
7747 // Put some random garbage in old methods to help find stale pointers.
7748 if (methods != old_methods && old_methods != nullptr) {
7749 // Need to make sure the GC is not running since it could be scanning the methods we are
7750 // about to overwrite.
7751 ScopedThreadStateChange tsc(self_, kSuspended);
7752 gc::ScopedGCCriticalSection gcs(self_,
7753 gc::kGcCauseClassLinker,
7754 gc::kCollectorTypeClassLinker);
7755 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7756 method_size_,
7757 method_alignment_);
7758 memset(old_methods, 0xFEu, old_size);
7759 }
7760 }
7761 }
7762
7763 private:
7764 size_t NumberOfNewVirtuals() const {
7765 return miranda_methods_.size() +
7766 default_methods_.size() +
7767 overriding_default_conflict_methods_.size() +
7768 overriding_default_methods_.size() +
7769 default_conflict_methods_.size();
7770 }
7771
7772 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7773 return !klass_->IsInterface();
7774 }
7775
7776 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7777 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7778 << "Interfaces should only have default-conflict methods appended to them.";
7779 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7780 << miranda_methods_.size()
7781 << " default_methods=" << default_methods_.size()
7782 << " overriding_default_methods=" << overriding_default_methods_.size()
7783 << " default_conflict_methods=" << default_conflict_methods_.size()
7784 << " overriding_default_conflict_methods="
7785 << overriding_default_conflict_methods_.size();
7786 }
7787
7788 ClassLinker* class_linker_;
7789 Handle<mirror::Class> klass_;
7790 size_t method_alignment_;
7791 size_t method_size_;
7792 Thread* const self_;
7793
7794 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7795 // the virtual methods array.
7796 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7797 // during cross compilation.
7798 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7799 ArenaStack stack_;
7800 ScopedArenaAllocator allocator_;
7801
7802 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7803 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7804 ScopedArenaVector<ArtMethod*> miranda_methods_;
7805 ScopedArenaVector<ArtMethod*> default_methods_;
7806 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7807
7808 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7809};
7810
7811ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7812 ArtMethod* interface_method,
7813 MethodNameAndSignatureComparator& interface_name_comparator,
7814 ArtMethod* vtable_impl) {
7815 ArtMethod* current_method = nullptr;
7816 switch (class_linker_->FindDefaultMethodImplementation(self_,
7817 interface_method,
7818 klass_,
7819 /*out*/&current_method)) {
7820 case DefaultMethodSearchResult::kDefaultConflict: {
7821 // Default method conflict.
7822 DCHECK(current_method == nullptr);
7823 ArtMethod* default_conflict_method = nullptr;
7824 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7825 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7826 default_conflict_method = vtable_impl;
7827 } else {
7828 // See if we already have a conflict method for this method.
7829 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7830 interface_name_comparator,
7831 default_conflict_methods_,
7832 overriding_default_conflict_methods_);
7833 if (LIKELY(preexisting_conflict != nullptr)) {
7834 // We already have another conflict we can reuse.
7835 default_conflict_method = preexisting_conflict;
7836 } else {
7837 // Note that we do this even if we are an interface since we need to create this and
7838 // cannot reuse another classes.
7839 // Create a new conflict method for this to use.
7840 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7841 new(default_conflict_method) ArtMethod(interface_method,
7842 class_linker_->GetImagePointerSize());
7843 if (vtable_impl == nullptr) {
7844 // Save the conflict method. We need to add it to the vtable.
7845 default_conflict_methods_.push_back(default_conflict_method);
7846 } else {
7847 // Save the conflict method but it is already in the vtable.
7848 overriding_default_conflict_methods_.push_back(default_conflict_method);
7849 }
7850 }
7851 }
7852 current_method = default_conflict_method;
7853 break;
7854 } // case kDefaultConflict
7855 case DefaultMethodSearchResult::kDefaultFound: {
7856 DCHECK(current_method != nullptr);
7857 // Found a default method.
7858 if (vtable_impl != nullptr &&
7859 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7860 // We found a default method but it was the same one we already have from our
7861 // superclass. Don't bother adding it to our vtable again.
7862 current_method = vtable_impl;
7863 } else if (LIKELY(FillTables())) {
7864 // Interfaces don't need to copy default methods since they don't have vtables.
7865 // Only record this default method if it is new to save space.
7866 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7867 // would make lookup for interface super much faster. (We would only need to scan
7868 // the iftable to find if there is a NSME or AME.)
7869 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7870 default_methods_,
7871 overriding_default_methods_);
7872 if (old == nullptr) {
7873 // We found a default method implementation and there were no conflicts.
7874 if (vtable_impl == nullptr) {
7875 // Save the default method. We need to add it to the vtable.
7876 default_methods_.push_back(current_method);
7877 } else {
7878 // Save the default method but it is already in the vtable.
7879 overriding_default_methods_.push_back(current_method);
7880 }
7881 } else {
7882 CHECK(old == current_method) << "Multiple default implementations selected!";
7883 }
7884 }
7885 break;
7886 } // case kDefaultFound
7887 case DefaultMethodSearchResult::kAbstractFound: {
7888 DCHECK(current_method == nullptr);
7889 // Abstract method masks all defaults.
7890 if (vtable_impl != nullptr &&
7891 vtable_impl->IsAbstract() &&
7892 !vtable_impl->IsDefaultConflicting()) {
7893 // We need to make this an abstract method but the version in the vtable already is so
7894 // don't do anything.
7895 current_method = vtable_impl;
7896 }
7897 break;
7898 } // case kAbstractFound
7899 }
7900 return current_method;
7901}
7902
7903ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7904 ArtMethod* interface_method,
7905 MethodNameAndSignatureComparator& interface_name_comparator) {
7906 // Find out if there is already a miranda method we can use.
7907 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7908 miranda_methods_);
7909 if (miranda_method == nullptr) {
7910 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7911 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7912 CHECK(miranda_method != nullptr);
7913 // Point the interface table at a phantom slot.
7914 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7915 miranda_methods_.push_back(miranda_method);
7916 }
7917 return miranda_method;
7918}
7919
7920void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7921 LogNewVirtuals();
7922
7923 const size_t old_method_count = klass_->NumMethods();
7924 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7925 DCHECK_NE(old_method_count, new_method_count);
7926
7927 // Attempt to realloc to save RAM if possible.
7928 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7929 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7930 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7931 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7932 // CopyFrom has internal read barriers.
7933 //
7934 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7935 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7936 method_size_,
7937 method_alignment_);
7938 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7939 method_size_,
7940 method_alignment_);
7941 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7942 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007943 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007944 self_, old_methods, old_methods_ptr_size, new_size));
7945 CHECK(methods != nullptr); // Native allocation failure aborts.
7946
7947 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7948 if (methods != old_methods) {
7949 // Maps from heap allocated miranda method to linear alloc miranda method.
7950 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7951 // Copy over the old methods.
7952 for (auto& m : klass_->GetMethods(pointer_size)) {
7953 move_table_.emplace(&m, &*out);
7954 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7955 // barriers when it copies.
7956 out->CopyFrom(&m, pointer_size);
7957 ++out;
7958 }
7959 }
7960 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7961 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7962 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007963 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7964 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007965 ArtMethod& new_method = *out;
7966 new_method.CopyFrom(mir_method, pointer_size);
7967 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7968 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7969 << "Miranda method should be abstract!";
7970 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007971 // Update the entry in the method array, as the array will be used for future lookups,
7972 // where thread suspension is allowed.
7973 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7974 // would not see them.
7975 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007976 ++out;
7977 }
7978 // We need to copy the default methods into our own method table since the runtime requires that
7979 // every method on a class's vtable be in that respective class's virtual method table.
7980 // NOTE This means that two classes might have the same implementation of a method from the same
7981 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7982 // default method found on a class with one found on the declaring interface directly and must
7983 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007984 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7985 &overriding_default_methods_}) {
7986 for (size_t i = 0; i < methods_vec->size(); ++i) {
7987 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007988 ArtMethod& new_method = *out;
7989 new_method.CopyFrom(def_method, pointer_size);
7990 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7991 // verified yet it shouldn't have methods that are skipping access checks.
7992 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7993 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007994 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007995 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7996 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7997 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7998 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007999 // Update the entry in the method array, as the array will be used for future lookups,
8000 // where thread suspension is allowed.
8001 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
8002 // would not see them.
8003 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00008004 ++out;
8005 }
8006 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008007 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
8008 &overriding_default_conflict_methods_}) {
8009 for (size_t i = 0; i < methods_vec->size(); ++i) {
8010 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00008011 ArtMethod& new_method = *out;
8012 new_method.CopyFrom(conf_method, pointer_size);
8013 // This is a type of default method (there are default method impls, just a conflict) so
8014 // mark this as a default, non-abstract method, since thats what it is. Also clear the
8015 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
8016 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01008017 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
8018 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01008019 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00008020 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01008021 constexpr uint32_t kMaskFlags =
8022 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00008023 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
8024 DCHECK(new_method.IsDefaultConflicting());
8025 // The actual method might or might not be marked abstract since we just copied it from a
8026 // (possibly default) interface method. We need to set it entry point to be the bridge so
8027 // that the compiler will not invoke the implementation of whatever method we copied from.
8028 EnsureThrowsInvocationError(class_linker_, &new_method);
8029 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008030 // Update the entry in the method array, as the array will be used for future lookups,
8031 // where thread suspension is allowed.
8032 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
8033 // would not see them.
8034 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00008035 ++out;
8036 }
8037 }
8038 methods->SetSize(new_method_count);
8039 class_linker_->UpdateClassMethods(klass_.Get(), methods);
8040}
8041
8042ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
8043 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01008044 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008045 // Update the vtable to the new method structures. We can skip this for interfaces since they
8046 // do not have vtables.
8047 const size_t old_vtable_count = old_vtable->GetLength();
8048 const size_t new_vtable_count = old_vtable_count +
8049 miranda_methods_.size() +
8050 default_methods_.size() +
8051 default_conflict_methods_.size();
8052
Vladimir Marko3068d582019-05-28 16:39:29 +01008053 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
8054 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00008055 if (UNLIKELY(vtable == nullptr)) {
8056 self_->AssertPendingOOMException();
8057 return nullptr;
8058 }
8059
8060 size_t vtable_pos = old_vtable_count;
8061 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8062 // Update all the newly copied method's indexes so they denote their placement in the vtable.
8063 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
8064 default_conflict_methods_,
8065 miranda_methods_}) {
8066 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008067 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008068 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
8069 // fields are references into the dex file the method was defined in. Since the ArtMethod
8070 // does not store that information it uses declaring_class_->dex_cache_.
8071 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
8072 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
8073 ++vtable_pos;
8074 }
8075 }
8076 DCHECK_EQ(vtable_pos, new_vtable_count);
8077
8078 // Update old vtable methods. We use the default_translations map to figure out what each
8079 // vtable entry should be updated to, if they need to be at all.
8080 for (size_t i = 0; i < old_vtable_count; ++i) {
8081 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
8082 // Try and find what we need to change this method to.
8083 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008084 if (translation_it != default_translations.end()) {
8085 if (translation_it->second.IsInConflict()) {
8086 // Find which conflict method we are to use for this method.
8087 MethodNameAndSignatureComparator old_method_comparator(
8088 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8089 // We only need to look through overriding_default_conflict_methods since this is an
8090 // overridden method we are fixing up here.
8091 ArtMethod* new_conflict_method = FindSameNameAndSignature(
8092 old_method_comparator, overriding_default_conflict_methods_);
8093 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
8094 translated_method = new_conflict_method;
8095 } else if (translation_it->second.IsAbstract()) {
8096 // Find which miranda method we are to use for this method.
8097 MethodNameAndSignatureComparator old_method_comparator(
8098 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8099 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
8100 miranda_methods_);
8101 DCHECK(miranda_method != nullptr);
8102 translated_method = miranda_method;
8103 } else {
8104 // Normal default method (changed from an older default or abstract interface method).
8105 DCHECK(translation_it->second.IsTranslation());
8106 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008107 auto it = move_table_.find(translated_method);
8108 DCHECK(it != move_table_.end());
8109 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00008110 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008111 } else {
8112 auto it = move_table_.find(translated_method);
8113 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008114 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008115
8116 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008117 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008118 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008119 if (kIsDebugBuild) {
8120 auto* methods = klass_->GetMethodsPtr();
8121 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008122 reinterpret_cast<uintptr_t>(translated_method));
8123 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008124 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8125 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008126 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008127 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008128 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008129 }
8130 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008131 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008132 return vtable;
8133}
8134
8135void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8136 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8137 const size_t ifcount = klass_->GetIfTableCount();
8138 // Go fix up all the stale iftable pointers.
8139 for (size_t i = 0; i < ifcount; ++i) {
8140 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008141 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8142 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008143 DCHECK(m != nullptr) << klass_->PrettyClass();
8144 auto it = move_table_.find(m);
8145 if (it != move_table_.end()) {
8146 auto* new_m = it->second;
8147 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8148 method_array->SetElementPtrSize(j, new_m, pointer_size);
8149 }
8150 }
8151 }
8152}
8153
8154void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8155 // Fix up IMT next.
8156 for (size_t i = 0; i < ImTable::kSize; ++i) {
8157 auto it = move_table_.find(out_imt[i]);
8158 if (it != move_table_.end()) {
8159 out_imt[i] = it->second;
8160 }
8161 }
8162}
8163
Alex Light705ad492015-09-21 11:36:30 -07008164// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008165bool ClassLinker::LinkInterfaceMethods(
8166 Thread* self,
8167 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07008168 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008169 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008170 ArtMethod** out_imt) {
8171 StackHandleScope<3> hs(self);
8172 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008173
8174 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008175 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008176 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008177 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008178 const size_t ifcount = klass->GetIfTableCount();
8179
Vladimir Marko921094a2017-01-12 18:37:06 +00008180 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008181
8182 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8183 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008184 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008185 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008186 const bool extend_super_iftable = has_superclass;
8187 if (has_superclass && fill_tables) {
8188 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008189 unimplemented_method,
8190 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008191 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008192 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008193 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008194 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8195 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008196 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008197 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8198 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008199 }
8200 }
8201
Vladimir Marko921094a2017-01-12 18:37:06 +00008202 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8203
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008204 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008205 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008206 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8207 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8208 // they will already be null. This has the additional benefit that the declarer of a miranda
8209 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008210 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008211 --i;
Alex Light9139e002015-10-09 15:59:48 -07008212 DCHECK_LT(i, ifcount);
8213
Alex Light705ad492015-09-21 11:36:30 -07008214 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008215 if (num_methods > 0) {
8216 StackHandleScope<2> hs2(self);
8217 const bool is_super = i < super_ifcount;
8218 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008219 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8220 // conflict methods. Just set this as nullptr in those cases.
8221 Handle<mirror::PointerArray> method_array(fill_tables
8222 ? hs2.NewHandle(iftable->GetMethodArray(i))
8223 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008224
Alex Lighte64300b2015-12-15 15:02:47 -08008225 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008226 ScopedNullHandle<mirror::PointerArray> null_handle;
8227 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008228 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008229
Alex Light9139e002015-10-09 15:59:48 -07008230 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8231 // and confusing. Default methods should always look through all the superclasses
8232 // because they are the last choice of an implementation. We get around this by looking
8233 // at the super-classes iftable methods (copied into method_array previously) when we are
8234 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008235 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008236 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008237 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008238 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008239 using_virtuals = true;
8240 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
8241 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008242 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008243 // For a new interface, however, we need the whole vtable in case a new
8244 // interface method is implemented in the whole superclass.
8245 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008246 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008247 input_vtable_array = vtable;
8248 input_array_length = input_vtable_array->GetLength();
8249 }
Alex Lighte64300b2015-12-15 15:02:47 -08008250
Alex Lighteb7c1442015-08-31 13:17:42 -07008251 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008252 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008253 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008254 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008255 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008256 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008257 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008258 // For each method listed in the interface's method list, find the
8259 // matching method in our class's method list. We want to favor the
8260 // subclass over the superclass, which just requires walking
8261 // back from the end of the vtable. (This only matters if the
8262 // superclass defines a private method and this class redefines
8263 // it -- otherwise it would use the same vtable slot. In .dex files
8264 // those don't end up in the virtual method table, so it shouldn't
8265 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008266 //
8267 // To find defaults we need to do the same but also go over interfaces.
8268 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008269 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008270 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008271 ArtMethod* vtable_method = using_virtuals ?
8272 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008273 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8274 ArtMethod* vtable_method_for_name_comparison =
8275 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008276 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008277 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008278 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008279 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8280 // allocations.
8281 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008282 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008283 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008284 vtable_method->PrettyMethod().c_str(),
8285 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008286 return false;
Alex Light9139e002015-10-09 15:59:48 -07008287 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008288 // We might have a newer, better, default method for this, so we just skip it. If we
8289 // are still using this we will select it again when scanning for default methods. To
8290 // obviate the need to copy the method again we will make a note that we already found
8291 // a default here.
8292 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008293 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008294 break;
8295 } else {
8296 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008297 if (LIKELY(fill_tables)) {
8298 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8299 // Place method in imt if entry is empty, place conflict otherwise.
8300 SetIMTRef(unimplemented_method,
8301 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008302 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008303 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008304 /*out*/imt_ptr);
8305 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008306 break;
8307 }
8308 }
Alex Light9139e002015-10-09 15:59:48 -07008309 }
8310 // Continue on to the next method if we are done.
8311 if (LIKELY(found_impl)) {
8312 continue;
8313 } else if (LIKELY(super_interface)) {
8314 // Don't look for a default implementation when the super-method is implemented directly
8315 // by the class.
8316 //
8317 // See if we can use the superclasses method and skip searching everything else.
8318 // Note: !found_impl && super_interface
8319 CHECK(extend_super_iftable);
8320 // If this is a super_interface method it is possible we shouldn't override it because a
8321 // superclass could have implemented it directly. We get the method the superclass used
8322 // to implement this to know if we can override it with a default method. Doing this is
8323 // safe since we know that the super_iftable is filled in so we can simply pull it from
8324 // there. We don't bother if this is not a super-classes interface since in that case we
8325 // have scanned the entire vtable anyway and would have found it.
8326 // TODO This is rather dirty but it is faster than searching through the entire vtable
8327 // every time.
8328 ArtMethod* supers_method =
8329 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8330 DCHECK(supers_method != nullptr);
8331 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008332 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008333 // The method is not overridable by a default method (i.e. it is directly implemented
8334 // in some class). Therefore move onto the next interface method.
8335 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008336 } else {
8337 // If the super-classes method is override-able by a default method we need to keep
8338 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8339 // 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 -07008340 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8341 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8342 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008343 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008344 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8345 << " and not 'nullptr' or "
8346 << supers_method->PrettyMethod()
8347 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008348 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008349 }
8350 }
8351 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008352 ArtMethod* current_method = helper.FindMethod(interface_method,
8353 interface_name_comparator,
8354 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008355 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008356 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008357 // We could not find an implementation for this method and since it is a brand new
8358 // interface we searched the entire vtable (and all default methods) for an
8359 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008360 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8361 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008362 }
8363
8364 if (current_method != nullptr) {
8365 // We found a default method implementation. Record it in the iftable and IMT.
8366 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8367 SetIMTRef(unimplemented_method,
8368 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008369 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008370 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008371 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008372 }
8373 }
Alex Light705ad492015-09-21 11:36:30 -07008374 } // For each method in interface end.
8375 } // if (num_methods > 0)
8376 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008377 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008378 if (helper.HasNewVirtuals()) {
8379 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8380 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8381 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8382
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008383 // 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 -07008384 // suspension assert.
8385 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008386
Alex Light705ad492015-09-21 11:36:30 -07008387 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008388 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008389 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008390 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008391 return false;
8392 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008393 helper.UpdateIfTable(iftable);
8394 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008395 }
Alex Light705ad492015-09-21 11:36:30 -07008396
Vladimir Marko921094a2017-01-12 18:37:06 +00008397 helper.CheckNoStaleMethodsInDexCache();
8398 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008399 } else {
8400 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008401 }
Alex Light705ad492015-09-21 11:36:30 -07008402 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008403 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008404 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008405 return true;
8406}
8407
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008408bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008409 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008410 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008411}
8412
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008413bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008414 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008415 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008416}
8417
Brian Carlstromdbc05252011-09-09 01:59:59 -07008418struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008419 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008420 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008421 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008422 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008423 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008424 // 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 -07008425 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8426 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008427 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008428 if (type1 == Primitive::kPrimNot) {
8429 // Reference always goes first.
8430 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008431 }
Vladimir Markod5777482014-11-12 17:02:02 +00008432 if (type2 == Primitive::kPrimNot) {
8433 // Reference always goes first.
8434 return false;
8435 }
8436 size_t size1 = Primitive::ComponentSize(type1);
8437 size_t size2 = Primitive::ComponentSize(type2);
8438 if (size1 != size2) {
8439 // Larger primitive types go first.
8440 return size1 > size2;
8441 }
8442 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8443 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008444 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008445 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8446 // by name and for equal names by type id index.
8447 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8448 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008449 }
8450};
8451
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008452bool ClassLinker::LinkFields(Thread* self,
8453 Handle<mirror::Class> klass,
8454 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008455 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008456 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008457 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008458 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8459 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008460
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008461 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008462 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008463 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008464 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008465 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008466 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008467 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008468 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008469 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008470 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008471 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008472 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008473
David Sehr709b0702016-10-13 09:12:37 -07008474 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008475
Brian Carlstromdbc05252011-09-09 01:59:59 -07008476 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008477 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008478 //
8479 // The overall sort order order is:
8480 // 1) All object reference fields, sorted alphabetically.
8481 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8482 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8483 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8484 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8485 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8486 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8487 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8488 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8489 //
8490 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8491 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008492 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008493 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008494 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008495 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008496 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008497 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008498 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8499 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008500
Fred Shih381e4ca2014-08-25 17:24:27 -07008501 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008502 size_t current_field = 0;
8503 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008504 FieldGaps gaps;
8505
Brian Carlstromdbc05252011-09-09 01:59:59 -07008506 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008507 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008508 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008509 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008510 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008511 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008512 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008513 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8514 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008515 MemberOffset old_offset = field_offset;
8516 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8517 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8518 }
Roland Levillain14d90572015-07-16 10:52:26 +01008519 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008520 grouped_and_sorted_fields.pop_front();
8521 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008522 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008523 field_offset = MemberOffset(field_offset.Uint32Value() +
8524 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008525 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008526 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8527 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008528 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8529 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8530 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8531 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008532 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8533 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008534 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008535
Elliott Hughesadb460d2011-10-05 17:02:34 -07008536 // 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 -07008537 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008538 // We know there are no non-reference fields in the Reference classes, and we know
8539 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008540 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008541 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008542 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008543 --num_reference_fields;
8544 }
8545
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008546 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008547 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008548 if (is_static) {
8549 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008550 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008551 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008552 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008553 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008554 if (num_reference_fields == 0 || super_class == nullptr) {
8555 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008556 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008557 if (super_class == nullptr ||
8558 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8559 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008560 }
8561 }
8562 if (kIsDebugBuild) {
8563 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8564 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008565 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008566 while (cur_super != nullptr) {
8567 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8568 cur_super = cur_super->GetSuperClass();
8569 }
8570 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008571 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008572 } else {
8573 // Check that there is at least num_reference_fields other than Object.class.
8574 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008575 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008576 }
8577 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008578 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008579 std::string temp;
8580 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8581 size_t previous_size = klass->GetObjectSize();
8582 if (previous_size != 0) {
8583 // Make sure that we didn't originally have an incorrect size.
8584 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008585 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008586 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008587 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008588 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008589
8590 if (kIsDebugBuild) {
8591 // Make sure that the fields array is ordered by name but all reference
8592 // offsets are at the beginning as far as alignment allows.
8593 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008594 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008595 : klass->GetFirstReferenceInstanceFieldOffset();
8596 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8597 num_reference_fields *
8598 sizeof(mirror::HeapReference<mirror::Object>));
8599 MemberOffset current_ref_offset = start_ref_offset;
8600 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008601 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008602 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008603 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8604 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008605 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008606 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008607 // NOTE: The field names can be the same. This is not possible in the Java language
8608 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008609 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008610 }
8611 Primitive::Type type = field->GetTypeAsPrimitiveType();
8612 bool is_primitive = type != Primitive::kPrimNot;
8613 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8614 strcmp("referent", field->GetName()) == 0) {
8615 is_primitive = true; // We lied above, so we have to expect a lie here.
8616 }
8617 MemberOffset offset = field->GetOffsetDuringLinking();
8618 if (is_primitive) {
8619 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8620 // Shuffled before references.
8621 size_t type_size = Primitive::ComponentSize(type);
8622 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8623 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8624 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8625 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8626 }
8627 } else {
8628 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8629 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8630 sizeof(mirror::HeapReference<mirror::Object>));
8631 }
8632 }
8633 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8634 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008635 return true;
8636}
8637
Vladimir Marko76649e82014-11-10 18:32:59 +00008638// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008639void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008640 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008641 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008642 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008643 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008644 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008645 // Compute reference offsets unless our superclass overflowed.
8646 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8647 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008648 if (num_reference_fields != 0u) {
8649 // All of the fields that contain object references are guaranteed be grouped in memory
8650 // starting at an appropriately aligned address after super class object data.
8651 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8652 sizeof(mirror::HeapReference<mirror::Object>));
8653 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008654 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008655 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008656 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008657 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008658 reference_offsets |= (0xffffffffu << start_bit) &
8659 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008660 }
8661 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008662 }
8663 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008664 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008665}
8666
Vladimir Marko18090d12018-06-01 16:53:12 +01008667ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8668 ObjPtr<mirror::DexCache> dex_cache) {
8669 StackHandleScope<1> hs(Thread::Current());
8670 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8671 return DoResolveString(string_idx, h_dex_cache);
8672}
8673
8674ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8675 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008676 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008677 uint32_t utf16_length;
8678 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008679 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008680 if (string != nullptr) {
8681 dex_cache->SetResolvedString(string_idx, string);
8682 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008683 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008684}
8685
Vladimir Marko18090d12018-06-01 16:53:12 +01008686ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8687 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008688 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008689 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008690 uint32_t utf16_length;
8691 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008692 ObjPtr<mirror::String> string =
8693 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008694 if (string != nullptr) {
8695 dex_cache->SetResolvedString(string_idx, string);
8696 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008697 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008698}
8699
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008700ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008701 ObjPtr<mirror::Class> referrer) {
8702 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8703}
8704
8705ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008706 ObjPtr<mirror::DexCache> dex_cache,
8707 ObjPtr<mirror::ClassLoader> class_loader) {
8708 const DexFile& dex_file = *dex_cache->GetDexFile();
8709 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8710 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8711 ObjPtr<mirror::Class> type = nullptr;
8712 if (descriptor[1] == '\0') {
8713 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8714 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008715 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008716 } else {
8717 Thread* const self = Thread::Current();
8718 DCHECK(self != nullptr);
8719 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8720 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008721 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008722 }
8723 if (type != nullptr) {
8724 if (type->IsResolved()) {
8725 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008726 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008727 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008728 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008729 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008730 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008731}
8732
Andreas Gampeb0625e02019-05-01 12:43:31 -07008733template <typename RefType>
8734ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008735 StackHandleScope<2> hs(Thread::Current());
8736 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8737 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8738 return DoResolveType(type_idx, dex_cache, class_loader);
8739}
8740
Andreas Gampe4835d212018-11-21 14:55:10 -08008741// Instantiate the above.
8742template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8743 ArtField* referrer);
8744template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8745 ArtMethod* referrer);
8746template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8747 ObjPtr<mirror::Class> referrer);
8748
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008749ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008750 Handle<mirror::DexCache> dex_cache,
8751 Handle<mirror::ClassLoader> class_loader) {
8752 Thread* self = Thread::Current();
8753 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8754 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8755 if (resolved != nullptr) {
8756 // TODO: we used to throw here if resolved's class loader was not the
8757 // boot class loader. This was to permit different classes with the
8758 // same name to be loaded simultaneously by different loaders
8759 dex_cache->SetResolvedType(type_idx, resolved);
8760 } else {
8761 CHECK(self->IsExceptionPending())
8762 << "Expected pending exception for failed resolution of: " << descriptor;
8763 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8764 StackHandleScope<1> hs(self);
8765 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008766 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008767 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8768 self->ClearException();
8769 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8770 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008771 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008772 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008773 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008774 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008775 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008776}
8777
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008778ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8779 ObjPtr<mirror::DexCache> dex_cache,
8780 ObjPtr<mirror::ClassLoader> class_loader,
8781 uint32_t method_idx) {
8782 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8783 // functions can optimize the search if the dex_cache is the same as the DexCache
8784 // of the class, with fall-back to name and signature search otherwise.
8785 ArtMethod* resolved = nullptr;
8786 if (klass->IsInterface()) {
8787 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8788 } else {
8789 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8790 }
8791 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008792 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008793 hiddenapi::ShouldDenyAccessToMember(resolved,
8794 hiddenapi::AccessContext(class_loader, dex_cache),
8795 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008796 resolved = nullptr;
8797 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008798 if (resolved != nullptr) {
8799 // In case of jmvti, the dex file gets verified before being registered, so first
8800 // check if it's registered before checking class tables.
8801 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008802 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8803 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008804 << "DexFile referrer: " << dex_file.GetLocation()
8805 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8806 // Be a good citizen and update the dex cache to speed subsequent calls.
8807 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008808 // Disable the following invariant check as the verifier breaks it. b/73760543
8809 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8810 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8811 // << "Method: " << resolved->PrettyMethod() << ", "
8812 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8813 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008814 }
8815 return resolved;
8816}
8817
David Brazdil4525e0b2018-04-05 16:57:32 +01008818// Returns true if `method` is either null or hidden.
8819// Does not print any warnings if it is hidden.
8820static bool CheckNoSuchMethod(ArtMethod* method,
8821 ObjPtr<mirror::DexCache> dex_cache,
8822 ObjPtr<mirror::ClassLoader> class_loader)
8823 REQUIRES_SHARED(Locks::mutator_lock_) {
8824 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008825 hiddenapi::ShouldDenyAccessToMember(method,
8826 hiddenapi::AccessContext(class_loader, dex_cache),
8827 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008828}
8829
8830ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8831 ObjPtr<mirror::DexCache> dex_cache,
8832 ObjPtr<mirror::ClassLoader> class_loader,
8833 uint32_t method_idx) {
8834 if (klass->IsInterface()) {
8835 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8836 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8837 } else {
8838 // If there was an interface method with the same signature, we would have
8839 // found it in the "copied" methods. Only DCHECK that the interface method
8840 // really does not exist.
8841 if (kIsDebugBuild) {
8842 ArtMethod* method =
8843 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8844 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8845 }
8846 return nullptr;
8847 }
8848}
8849
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008850template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008851ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008852 Handle<mirror::DexCache> dex_cache,
8853 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008854 ArtMethod* referrer,
8855 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008856 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008857 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008858 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008859 PointerSize pointer_size = image_pointer_size_;
8860 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008861 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008862 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8863 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008864 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8865 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008866 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008867 return resolved;
8868 }
Vladimir Marko89011192017-12-11 13:45:05 +00008869 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008870 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008871 ObjPtr<mirror::Class> klass = nullptr;
8872 if (valid_dex_cache_method) {
8873 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8874 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008875 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008876 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008877 // We normaly should not end up here. However the verifier currently doesn't guarantee
8878 // the invariant of having the klass in the class table. b/73760543
8879 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008880 }
Vladimir Markoba118822017-06-12 15:41:56 +01008881 } else {
8882 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008883 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008884 if (klass == nullptr) {
8885 DCHECK(Thread::Current()->IsExceptionPending());
8886 return nullptr;
8887 }
8888 }
8889
8890 // Check if the invoke type matches the class type.
8891 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008892 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008893 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008894 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008895 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008896 }
Vladimir Markoba118822017-06-12 15:41:56 +01008897
8898 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008899 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008900 }
Vladimir Markoba118822017-06-12 15:41:56 +01008901
8902 // Note: We can check for IllegalAccessError only if we have a referrer.
8903 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8904 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8905 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8906 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8907 resolved,
8908 dex_cache.Get(),
8909 method_idx,
8910 type)) {
8911 DCHECK(Thread::Current()->IsExceptionPending());
8912 return nullptr;
8913 }
8914 }
8915
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008916 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008917 if (LIKELY(resolved != nullptr) &&
8918 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8919 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008920 return resolved;
8921 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008922 // If we had a method, or if we can find one with another lookup type,
8923 // it's an incompatible-class-change error.
8924 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008925 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008926 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008927 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008928 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008929 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008930 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008931 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8932 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008933 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008934 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008935 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008936 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008937 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008938}
8939
Vladimir Marko89011192017-12-11 13:45:05 +00008940ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008941 Handle<mirror::DexCache> dex_cache,
8942 Handle<mirror::ClassLoader> class_loader) {
8943 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008944 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008945 if (resolved != nullptr) {
8946 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008947 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8948 return resolved;
8949 }
8950 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008951 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008952 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008953 if (klass == nullptr) {
8954 Thread::Current()->AssertPendingException();
8955 return nullptr;
8956 }
8957 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008958 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8959 } else {
8960 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008961 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008962 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008963 hiddenapi::ShouldDenyAccessToMember(
8964 resolved,
8965 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8966 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008967 resolved = nullptr;
8968 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008969 return resolved;
8970}
8971
Vladimir Markof44d36c2017-03-14 14:18:46 +00008972ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8973 ObjPtr<mirror::DexCache> dex_cache,
8974 ObjPtr<mirror::ClassLoader> class_loader,
8975 bool is_static) {
8976 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008977 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008978 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8979 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008980 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008981 }
8982 if (klass == nullptr) {
8983 // The class has not been resolved yet, so the field is also unresolved.
8984 return nullptr;
8985 }
8986 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008987
David Brazdil1ab0fa82018-05-04 11:28:03 +01008988 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008989}
8990
Vladimir Markoe11dd502017-12-08 14:09:45 +00008991ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008992 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008993 Handle<mirror::ClassLoader> class_loader,
8994 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008995 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008996 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008997 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008998 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008999 return resolved;
9000 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009001 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009002 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009003 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009004 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08009005 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07009006 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009007 }
9008
David Brazdil1ab0fa82018-05-04 11:28:03 +01009009 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07009010 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08009011 const char* name = dex_file.GetFieldName(field_id);
9012 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009013 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009014 }
Ian Rogersb067ac22011-12-13 18:05:09 -08009015 return resolved;
9016}
9017
Vladimir Markoe11dd502017-12-08 14:09:45 +00009018ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009019 Handle<mirror::DexCache> dex_cache,
9020 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009021 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009022 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009023 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009024 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009025 return resolved;
9026 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009027 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009028 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009029 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009030 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009031 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009032 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009033 }
9034
David Brazdil1ab0fa82018-05-04 11:28:03 +01009035 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9036 if (resolved == nullptr) {
9037 const char* name = dex_file.GetFieldName(field_id);
9038 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009039 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009040 }
9041 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009042}
9043
David Brazdil1ab0fa82018-05-04 11:28:03 +01009044ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9045 ObjPtr<mirror::DexCache> dex_cache,
9046 ObjPtr<mirror::ClassLoader> class_loader,
9047 uint32_t field_idx,
9048 bool is_static) {
9049 ArtField* resolved = nullptr;
9050 Thread* self = is_static ? Thread::Current() : nullptr;
9051 const DexFile& dex_file = *dex_cache->GetDexFile();
9052
9053 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
9054 : klass->FindInstanceField(dex_cache, field_idx);
9055
9056 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009057 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009058 const char* name = dex_file.GetFieldName(field_id);
9059 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9060 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
9061 : klass->FindInstanceField(name, type);
9062 }
9063
9064 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009065 hiddenapi::ShouldDenyAccessToMember(resolved,
9066 hiddenapi::AccessContext(class_loader, dex_cache),
9067 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009068 resolved = nullptr;
9069 }
9070
9071 if (resolved != nullptr) {
9072 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9073 }
9074
9075 return resolved;
9076}
9077
9078ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9079 ObjPtr<mirror::DexCache> dex_cache,
9080 ObjPtr<mirror::ClassLoader> class_loader,
9081 uint32_t field_idx) {
9082 ArtField* resolved = nullptr;
9083 Thread* self = Thread::Current();
9084 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009085 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009086
9087 const char* name = dex_file.GetFieldName(field_id);
9088 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9089 resolved = mirror::Class::FindField(self, klass, name, type);
9090
9091 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009092 hiddenapi::ShouldDenyAccessToMember(resolved,
9093 hiddenapi::AccessContext(class_loader, dex_cache),
9094 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009095 resolved = nullptr;
9096 }
9097
9098 if (resolved != nullptr) {
9099 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9100 }
9101
9102 return resolved;
9103}
9104
Vladimir Markoaf940202017-12-08 15:01:18 +00009105ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9106 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009107 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009108 Handle<mirror::DexCache> dex_cache,
9109 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009110 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009111 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009112
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009113 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009114 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009115 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009116 }
9117
Narayan Kamath25352fc2016-08-03 12:46:58 +01009118 StackHandleScope<4> hs(self);
9119
9120 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009121 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009122 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009123 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009124 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009125 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009126 DCHECK(self->IsExceptionPending());
9127 return nullptr;
9128 }
9129
9130 // Then resolve the argument types.
9131 //
9132 // TODO: Is there a better way to figure out the number of method arguments
9133 // other than by looking at the shorty ?
9134 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9135
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009136 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009137 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9138 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009139 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009140 DCHECK(self->IsExceptionPending());
9141 return nullptr;
9142 }
9143
9144 DexFileParameterIterator it(dex_file, proto_id);
9145 int32_t i = 0;
9146 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9147 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009148 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009149 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009150 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009151 DCHECK(self->IsExceptionPending());
9152 return nullptr;
9153 }
9154
9155 method_params->Set(i++, param_class.Get());
9156 }
9157
9158 DCHECK(!it.HasNext());
9159
9160 Handle<mirror::MethodType> type = hs.NewHandle(
9161 mirror::MethodType::Create(self, return_type, method_params));
9162 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9163
9164 return type.Get();
9165}
9166
Vladimir Markoaf940202017-12-08 15:01:18 +00009167ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009168 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009169 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009170 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009171 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9172 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009173 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009174}
9175
Vladimir Marko5aead702019-03-27 11:00:36 +00009176ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009177 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009178 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009179 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009180 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009181 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9182 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009183 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009184 bool is_static;
9185 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009186 switch (handle_type) {
9187 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009188 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009189 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009190 is_static = true;
9191 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009192 break;
9193 }
9194 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009195 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009196 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009197 is_static = true;
9198 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009199 break;
9200 }
9201 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009202 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009203 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009204 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009205 num_params = 2;
9206 break;
9207 }
9208 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009209 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009210 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009211 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009212 num_params = 1;
9213 break;
9214 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009215 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009216 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009217 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009218 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009219 case DexFile::MethodHandleType::kInvokeInterface:
9220 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009221 }
9222
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009223 ArtField* target_field =
9224 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9225 if (LIKELY(target_field != nullptr)) {
9226 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9227 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9228 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9229 ThrowIllegalAccessErrorField(referring_class, target_field);
9230 return nullptr;
9231 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009232 if (UNLIKELY(is_put && target_field->IsFinal())) {
9233 ThrowIllegalAccessErrorField(referring_class, target_field);
9234 return nullptr;
9235 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009236 } else {
9237 DCHECK(Thread::Current()->IsExceptionPending());
9238 return nullptr;
9239 }
9240
9241 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009242 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009243 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9244 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009245 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009246 DCHECK(self->IsExceptionPending());
9247 return nullptr;
9248 }
9249
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009250 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009251 Handle<mirror::Class> return_type;
9252 switch (handle_type) {
9253 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009254 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009255 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009256 break;
9257 }
9258 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009259 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009260 break;
9261 }
9262 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009263 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009264 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009265 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009266 break;
9267 }
9268 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009269 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009270 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009271 break;
9272 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009273 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009274 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009275 case DexFile::MethodHandleType::kInvokeConstructor:
9276 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009277 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009278 UNREACHABLE();
9279 }
9280
9281 for (int32_t i = 0; i < num_params; ++i) {
9282 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9283 DCHECK(self->IsExceptionPending());
9284 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009285 }
9286 }
9287
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009288 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009289 DCHECK(self->IsExceptionPending());
9290 return nullptr;
9291 }
9292
9293 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009294 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9295 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009296 DCHECK(self->IsExceptionPending());
9297 return nullptr;
9298 }
Orion Hodson631827d2017-04-10 14:53:47 +01009299
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009300 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9301 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9302}
9303
Vladimir Marko5aead702019-03-27 11:00:36 +00009304ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009305 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009306 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009307 ArtMethod* referrer) {
9308 DexFile::MethodHandleType handle_type =
9309 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9310 mirror::MethodHandle::Kind kind;
9311 uint32_t receiver_count = 0;
9312 ArtMethod* target_method = nullptr;
9313 switch (handle_type) {
9314 case DexFile::MethodHandleType::kStaticPut:
9315 case DexFile::MethodHandleType::kStaticGet:
9316 case DexFile::MethodHandleType::kInstancePut:
9317 case DexFile::MethodHandleType::kInstanceGet:
9318 UNREACHABLE();
9319 case DexFile::MethodHandleType::kInvokeStatic: {
9320 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9321 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009322 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9323 method_handle.field_or_method_idx_,
9324 referrer,
9325 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009326 break;
9327 }
9328 case DexFile::MethodHandleType::kInvokeInstance: {
9329 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9330 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009331 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9332 method_handle.field_or_method_idx_,
9333 referrer,
9334 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009335 break;
9336 }
9337 case DexFile::MethodHandleType::kInvokeConstructor: {
9338 // Constructors are currently implemented as a transform. They
9339 // are special cased later in this method.
9340 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9341 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009342 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9343 method_handle.field_or_method_idx_,
9344 referrer,
9345 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009346 break;
9347 }
9348 case DexFile::MethodHandleType::kInvokeDirect: {
9349 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9350 receiver_count = 1;
9351 StackHandleScope<2> hs(self);
9352 // A constant method handle with type kInvokeDirect can refer to
9353 // a method that is private or to a method in a super class. To
9354 // disambiguate the two options, we resolve the method ignoring
9355 // the invocation type to determine if the method is private. We
9356 // then resolve again specifying the intended invocation type to
9357 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009358 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009359 hs.NewHandle(referrer->GetDexCache()),
9360 hs.NewHandle(referrer->GetClassLoader()));
9361 if (UNLIKELY(target_method == nullptr)) {
9362 break;
9363 }
9364
9365 if (target_method->IsPrivate()) {
9366 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009367 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9368 method_handle.field_or_method_idx_,
9369 referrer,
9370 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009371 } else {
9372 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009373 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9374 method_handle.field_or_method_idx_,
9375 referrer,
9376 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009377 if (UNLIKELY(target_method == nullptr)) {
9378 break;
9379 }
9380 // Find the method specified in the parent in referring class
9381 // so invoke-super invokes the method in the parent of the
9382 // referrer.
9383 target_method =
9384 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9385 kRuntimePointerSize);
9386 }
9387 break;
9388 }
9389 case DexFile::MethodHandleType::kInvokeInterface: {
9390 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9391 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009392 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9393 method_handle.field_or_method_idx_,
9394 referrer,
9395 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009396 break;
9397 }
Orion Hodson631827d2017-04-10 14:53:47 +01009398 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009399
9400 if (UNLIKELY(target_method == nullptr)) {
9401 DCHECK(Thread::Current()->IsExceptionPending());
9402 return nullptr;
9403 }
9404
9405 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9406 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9407 uint32_t access_flags = target_method->GetAccessFlags();
9408 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9409 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9410 return nullptr;
9411 }
9412
9413 // Calculate the number of parameters from the method shorty. We add the
9414 // receiver count (0 or 1) and deduct one for the return value.
9415 uint32_t shorty_length;
9416 target_method->GetShorty(&shorty_length);
9417 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9418
Orion Hodsonecd58562018-09-24 11:27:33 +01009419 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009420 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009421 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9422 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9423 if (method_params.Get() == nullptr) {
9424 DCHECK(self->IsExceptionPending());
9425 return nullptr;
9426 }
9427
Orion Hodsonecd58562018-09-24 11:27:33 +01009428 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009429 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009430 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009431 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009432 // Insert receiver. Use the class identified in the method handle rather than the declaring
9433 // class of the resolved method which may be super class or default interface method
9434 // (b/115964401).
9435 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9436 // receiver_class should have been resolved when resolving the target method.
9437 DCHECK(receiver_class != nullptr);
9438 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009439 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009440
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009441 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009442 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009443 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009444 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009445 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009446 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009447 if (nullptr == klass) {
9448 DCHECK(self->IsExceptionPending());
9449 return nullptr;
9450 }
9451 method_params->Set(index++, klass);
9452 it.Next();
9453 }
9454
Orion Hodsonecd58562018-09-24 11:27:33 +01009455 Handle<mirror::Class> return_type =
9456 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009457 if (UNLIKELY(return_type.IsNull())) {
9458 DCHECK(self->IsExceptionPending());
9459 return nullptr;
9460 }
9461
9462 Handle<mirror::MethodType>
9463 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9464 if (UNLIKELY(method_type.IsNull())) {
9465 DCHECK(self->IsExceptionPending());
9466 return nullptr;
9467 }
9468
9469 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9470 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9471 Handle<mirror::MethodHandlesLookup> lookup =
9472 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9473 return lookup->FindConstructor(self, constructor_class, method_type);
9474 }
9475
9476 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9477 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9478}
9479
Vladimir Markoaf940202017-12-08 15:01:18 +00009480ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9481 uint32_t method_handle_idx,
9482 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009483 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009484 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009485 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009486 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9487 case DexFile::MethodHandleType::kStaticPut:
9488 case DexFile::MethodHandleType::kStaticGet:
9489 case DexFile::MethodHandleType::kInstancePut:
9490 case DexFile::MethodHandleType::kInstanceGet:
9491 return ResolveMethodHandleForField(self, method_handle, referrer);
9492 case DexFile::MethodHandleType::kInvokeStatic:
9493 case DexFile::MethodHandleType::kInvokeInstance:
9494 case DexFile::MethodHandleType::kInvokeConstructor:
9495 case DexFile::MethodHandleType::kInvokeDirect:
9496 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009497 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009498 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009499}
9500
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009501bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9502 return (entry_point == GetQuickResolutionStub()) ||
9503 (quick_resolution_trampoline_ == entry_point);
9504}
9505
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009506bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9507 return (entry_point == GetQuickToInterpreterBridge()) ||
9508 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9509}
9510
9511bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9512 return (entry_point == GetQuickGenericJniStub()) ||
9513 (quick_generic_jni_trampoline_ == entry_point);
9514}
9515
David Sehra49e0532017-08-25 08:05:29 -07009516bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9517 return entry_point == GetJniDlsymLookupStub();
9518}
9519
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009520const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9521 return GetQuickGenericJniStub();
9522}
9523
Mathieu Chartiere401d142015-04-22 13:56:20 -07009524void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009525 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009526 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9527 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009528 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009529 }
9530}
9531
Alex Lightdb01a092017-04-03 15:39:55 -07009532void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9533 DCHECK(method->IsObsolete());
9534 // We cannot mess with the entrypoints of native methods because they are used to determine how
9535 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9536 if (!method->IsNative()) {
9537 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9538 }
9539}
9540
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009541void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009542 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009543 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009544 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9545 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009546 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9547 os << "Dumping registered class loaders\n";
9548 size_t class_loader_index = 0;
9549 for (const ClassLoaderData& class_loader : class_loaders_) {
9550 ObjPtr<mirror::ClassLoader> loader =
9551 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9552 if (loader != nullptr) {
9553 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9554 bool saw_one_dex_file = false;
9555 for (const DexCacheData& dex_cache : dex_caches_) {
9556 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9557 if (saw_one_dex_file) {
9558 os << ":";
9559 }
9560 saw_one_dex_file = true;
9561 os << dex_cache.dex_file->GetLocation();
9562 }
9563 }
9564 os << "]";
9565 bool found_parent = false;
9566 if (loader->GetParent() != nullptr) {
9567 size_t parent_index = 0;
9568 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9569 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9570 soa.Self()->DecodeJObject(class_loader2.weak_root));
9571 if (loader2 == loader->GetParent()) {
9572 os << ", parent #" << parent_index;
9573 found_parent = true;
9574 break;
9575 }
9576 parent_index++;
9577 }
9578 if (!found_parent) {
9579 os << ", unregistered parent of type "
9580 << loader->GetParent()->GetClass()->PrettyDescriptor();
9581 }
9582 } else {
9583 os << ", no parent";
9584 }
9585 os << "\n";
9586 }
9587 }
9588 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009589 Runtime* runtime = Runtime::Current();
9590 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9591 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009592}
9593
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009594class CountClassesVisitor : public ClassLoaderVisitor {
9595 public:
9596 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9597
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009598 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009599 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009600 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009601 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009602 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9603 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009604 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009605 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009606
9607 size_t num_zygote_classes;
9608 size_t num_non_zygote_classes;
9609};
9610
9611size_t ClassLinker::NumZygoteClasses() const {
9612 CountClassesVisitor visitor;
9613 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009614 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009615}
9616
9617size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009618 CountClassesVisitor visitor;
9619 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009620 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009621}
9622
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009623size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009624 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009625 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009626 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009627}
9628
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009629pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009630 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009631}
9632
9633pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009634 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009635}
9636
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009637void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009638 DCHECK(!init_done_);
9639
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009640 DCHECK(klass != nullptr);
9641 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009642
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009643 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009644 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009645 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9646 int32_t index = static_cast<int32_t>(class_root);
9647 DCHECK(class_roots->Get(index) == nullptr);
9648 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009649}
9650
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009651ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9652 Thread* self,
9653 const std::vector<const DexFile*>& dex_files,
9654 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009655 Handle<mirror::ClassLoader> parent_loader,
9656 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009657
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009658 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009659
Mathieu Chartierc7853442015-03-27 14:35:38 -07009660 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009661 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009662
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009663 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009664 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009665 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009666 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009667 mirror::ObjectArray<mirror::Object>::Alloc(self,
9668 dex_elements_class.Get(),
9669 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009670 Handle<mirror::Class> h_dex_element_class =
9671 hs.NewHandle(dex_elements_class->GetComponentType());
9672
Mathieu Chartierc7853442015-03-27 14:35:38 -07009673 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009674 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009675 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009676
Andreas Gampe08883de2016-11-08 13:20:52 -08009677 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009678 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009679
Andreas Gampe08883de2016-11-08 13:20:52 -08009680 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009681 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009682
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009683 // Fill the elements array.
9684 int32_t index = 0;
9685 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009686 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009687
Calin Juravle7865ac72017-06-28 11:03:12 -07009688 // CreateWellKnownClassLoader is only used by gtests and compiler.
9689 // 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 -07009690 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9691 self,
9692 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009693 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009694 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009695
Mathieu Chartier3738e982017-05-12 16:07:28 -07009696 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9697 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009698 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009699 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009700 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009701 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009702
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009703 Handle<mirror::String> h_file_name = hs2.NewHandle(
9704 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009705 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009706 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9707
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009708 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009709 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009710 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009711
9712 h_dex_elements->Set(index, h_element.Get());
9713 index++;
9714 }
9715 DCHECK_EQ(index, h_dex_elements->GetLength());
9716
9717 // Create DexPathList.
9718 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009719 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009720 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009721 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009722 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009723 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9724 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9725 // elements.
9726 {
9727 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9728 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9729 DCHECK(native_lib_dirs != nullptr);
9730 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9731 DCHECK(list_class != nullptr);
9732 {
9733 StackHandleScope<1> h_list_scope(self);
9734 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9735 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9736 DCHECK(list_init);
9737 list_class = h_list_class.Get();
9738 }
9739 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9740 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9741 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9742 // normally never null), as long as one does not try to add elements, this will still
9743 // work.
9744 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9745 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009746
Calin Juravle7865ac72017-06-28 11:03:12 -07009747 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009748 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9749 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009750 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009751 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009752 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009753 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009754 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009755 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009756
9757 // Make a pretend boot-classpath.
9758 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009759 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009760 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009761 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009762 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009763 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009764 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009765 if (parent_loader.Get() == nullptr) {
9766 ScopedObjectAccessUnchecked soa(self);
9767 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9768 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9769 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9770 } else {
9771 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9772 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009773
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009774 ArtField* shared_libraries_field =
9775 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9776 DCHECK(shared_libraries_field != nullptr);
9777 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9778
9779 return h_class_loader.Get();
9780}
9781
9782jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9783 const std::vector<const DexFile*>& dex_files,
9784 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009785 jobject parent_loader,
9786 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009787 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9788 WellKnownClasses::dalvik_system_PathClassLoader) ||
9789 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009790 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9791 self->GetJniEnv()->IsSameObject(loader_class,
9792 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009793
9794 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9795 // We could move the jobject to the callers, but all call-sites do this...
9796 ScopedObjectAccessUnchecked soa(self);
9797
9798 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009799 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009800
9801 Handle<mirror::Class> h_loader_class =
9802 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009803 Handle<mirror::ClassLoader> h_parent =
9804 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9805 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9806 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009807
9808 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9809 self,
9810 dex_files,
9811 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009812 h_parent,
9813 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009814
9815 // Make it a global ref and return.
9816 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009817 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009818 return soa.Env()->NewGlobalRef(local_ref.get());
9819}
9820
Calin Juravle7865ac72017-06-28 11:03:12 -07009821jobject ClassLinker::CreatePathClassLoader(Thread* self,
9822 const std::vector<const DexFile*>& dex_files) {
9823 return CreateWellKnownClassLoader(self,
9824 dex_files,
9825 WellKnownClasses::dalvik_system_PathClassLoader,
9826 nullptr);
9827}
9828
Andreas Gampe8ac75952015-06-02 21:01:45 -07009829void ClassLinker::DropFindArrayClassCache() {
9830 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9831 find_array_class_cache_next_victim_ = 0;
9832}
9833
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009834void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009835 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009836 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009837 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009838 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9839 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009840 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009841 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009842 }
9843 }
9844}
9845
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009846void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9847 for (const ClassLoaderData& data : class_loaders_) {
9848 LinearAlloc* alloc = data.allocator;
9849 if (alloc != nullptr && !visitor->Visit(alloc)) {
9850 break;
9851 }
9852 }
9853}
9854
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009855void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9856 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009857 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009858 Thread* const self = Thread::Current();
9859 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009860 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009861 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009862 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009863 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9864 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009865 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009866 }
9867}
9868
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009869void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009870 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009871 std::vector<ClassLoaderData> to_delete;
9872 // Do the delete outside the lock to avoid lock violation in jit code cache.
9873 {
9874 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9875 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9876 const ClassLoaderData& data = *it;
9877 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009878 ObjPtr<mirror::ClassLoader> class_loader =
9879 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009880 if (class_loader != nullptr) {
9881 ++it;
9882 } else {
9883 VLOG(class_linker) << "Freeing class loader";
9884 to_delete.push_back(data);
9885 it = class_loaders_.erase(it);
9886 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009887 }
9888 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009889 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009890 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009891 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009892 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009893}
9894
Vladimir Marko21300532017-01-24 18:06:55 +00009895class GetResolvedClassesVisitor : public ClassVisitor {
9896 public:
9897 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9898 : result_(result),
9899 ignore_boot_classes_(ignore_boot_classes),
9900 last_resolved_classes_(result->end()),
9901 last_dex_file_(nullptr),
9902 vlog_is_on_(VLOG_IS_ON(class_linker)),
9903 extra_stats_(),
9904 last_extra_stats_(extra_stats_.end()) { }
9905
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009906 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009907 if (!klass->IsProxyClass() &&
9908 !klass->IsArrayClass() &&
9909 klass->IsResolved() &&
9910 !klass->IsErroneousResolved() &&
9911 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9912 const DexFile& dex_file = klass->GetDexFile();
9913 if (&dex_file != last_dex_file_) {
9914 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009915 DexCacheResolvedClasses resolved_classes(
9916 dex_file.GetLocation(),
9917 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9918 dex_file.GetLocationChecksum(),
9919 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009920 last_resolved_classes_ = result_->find(resolved_classes);
9921 if (last_resolved_classes_ == result_->end()) {
9922 last_resolved_classes_ = result_->insert(resolved_classes).first;
9923 }
9924 }
9925 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9926 if (UNLIKELY(vlog_is_on_) && added) {
9927 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9928 if (last_extra_stats_ == extra_stats_.end() ||
9929 last_extra_stats_->first != resolved_classes) {
9930 last_extra_stats_ = extra_stats_.find(resolved_classes);
9931 if (last_extra_stats_ == extra_stats_.end()) {
9932 last_extra_stats_ =
9933 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9934 }
9935 }
9936 }
9937 }
9938 return true;
9939 }
9940
9941 void PrintStatistics() const {
9942 if (vlog_is_on_) {
9943 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9944 auto it = extra_stats_.find(std::addressof(resolved_classes));
9945 DCHECK(it != extra_stats_.end());
9946 const ExtraStats& extra_stats = it->second;
9947 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9948 << " has " << resolved_classes.GetClasses().size() << " / "
9949 << extra_stats.number_of_class_defs_ << " resolved classes";
9950 }
9951 }
9952 }
9953
9954 private:
9955 struct ExtraStats {
9956 explicit ExtraStats(uint32_t number_of_class_defs)
9957 : number_of_class_defs_(number_of_class_defs) {}
9958 uint32_t number_of_class_defs_;
9959 };
9960
9961 std::set<DexCacheResolvedClasses>* result_;
9962 bool ignore_boot_classes_;
9963 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9964 const DexFile* last_dex_file_;
9965
9966 // Statistics.
9967 bool vlog_is_on_;
9968 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9969 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9970};
9971
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009972std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009973 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009974 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009975 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009976 std::set<DexCacheResolvedClasses> ret;
9977 VLOG(class_linker) << "Collecting resolved classes";
9978 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009979 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9980 VisitClasses(&visitor);
9981 if (VLOG_IS_ON(class_linker)) {
9982 visitor.PrintStatistics();
9983 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009984 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009985 return ret;
9986}
9987
Mathieu Chartier65975772016-08-05 10:46:36 -07009988class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9989 public:
9990 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9991 : method_(method),
9992 pointer_size_(pointer_size) {}
9993
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009994 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009995 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9996 holder_ = klass;
9997 }
9998 // Return false to stop searching if holder_ is not null.
9999 return holder_ == nullptr;
10000 }
10001
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010002 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010003 const ArtMethod* const method_;
10004 const PointerSize pointer_size_;
10005};
10006
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010007ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010008 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10009 CHECK(method->IsCopied());
10010 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10011 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010012 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010013}
10014
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010015ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
10016 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010017 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +010010018 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010019 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010020}
10021
Roland Levillain0e840272018-08-23 19:55:30 +010010022// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +010010023template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010024 uint32_t method_idx,
10025 Handle<mirror::DexCache> dex_cache,
10026 Handle<mirror::ClassLoader> class_loader,
10027 ArtMethod* referrer,
10028 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +010010029template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010030 uint32_t method_idx,
10031 Handle<mirror::DexCache> dex_cache,
10032 Handle<mirror::ClassLoader> class_loader,
10033 ArtMethod* referrer,
10034 InvokeType type);
10035
Roland Levillain0e840272018-08-23 19:55:30 +010010036// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010037template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010038 Thread* self,
10039 ObjPtr<mirror::Class> java_lang_Class,
10040 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010041template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010042 Thread* self,
10043 ObjPtr<mirror::Class> java_lang_Class,
10044 uint32_t class_size);
10045
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010046} // namespace art