blob: f3c58d32a3b7bf4026fa5332a90f4f610edd83d5 [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>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070031#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070032#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070033
Andreas Gampe46ee31b2016-12-14 10:11:49 -080034#include "android-base/stringprintf.h"
35
Mathieu Chartierc7853442015-03-27 14:35:38 -070036#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070037#include "art_method-inl.h"
Vladimir Markobf121912019-06-04 13:49:05 +010038#include "barrier.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070039#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080040#include "base/casts.h"
Andreas Gampe19f54162019-05-14 16:16:28 -070041#include "base/file_utils.h"
Vladimir Marko782fb712020-12-23 12:47:31 +000042#include "base/hash_map.h"
43#include "base/hash_set.h"
David Sehr67bf42e2018-02-26 16:43:04 -080044#include "base/leb128.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080045#include "base/logging.h"
Vladimir Markobf121912019-06-04 13:49:05 +010046#include "base/mutex-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080047#include "base/os.h"
48#include "base/quasi_atomic.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070049#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010050#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080051#include "base/stl_util.h"
Vladimir Markob9c29f62019-03-20 14:22:51 +000052#include "base/string_view_cpp20.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080053#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010054#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080055#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080056#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070057#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070058#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070060#include "class_loader_utils.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010061#include "class_root-inl.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070062#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000063#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010064#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080065#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070066#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080067#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080068#include "dex/dex_file-inl.h"
69#include "dex/dex_file_exception_helpers.h"
70#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080071#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000072#include "dex/utf.h"
Vladimir Marko5115a4d2019-10-17 14:56:47 +010073#include "entrypoints/entrypoint_utils-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070074#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070075#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070076#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080077#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000078#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070079#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070080#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070081#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070082#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000083#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070084#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070085#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070086#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080087#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070088#include "imt_conflict_table.h"
89#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070090#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070091#include "interpreter/interpreter.h"
Nicolas Geoffray0315efa2020-06-26 11:42:39 +010092#include "interpreter/mterp/nterp.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000093#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080094#include "jit/jit.h"
95#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010096#include "jni/java_vm_ext.h"
97#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070098#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070099#include "mirror/array-alloc-inl.h"
100#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000101#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -0700102#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800103#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700104#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -0700105#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800106#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -0700107#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700108#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100109#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700110#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800111#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700112#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100113#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000114#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700115#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800116#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000117#include "mirror/object-refvisitor-inl.h"
Alex Lighta9bbc082019-11-14 14:51:41 -0800118#include "mirror/object.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700119#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700120#include "mirror/object_array-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000121#include "mirror/object_array.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700122#include "mirror/object_reference.h"
123#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800124#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700125#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800126#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700127#include "mirror/string-inl.h"
Andreas Gampe501c3b02019-04-17 21:54:27 +0000128#include "mirror/throwable.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100129#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700130#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700131#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700132#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700133#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700134#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700135#include "oat_file_assistant.h"
136#include "oat_file_manager.h"
137#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700138#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700139#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800140#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700141#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700142#include "thread-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000143#include "thread.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700144#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700145#include "trace.h"
Vladimir Markob68bb7a2020-03-17 10:55:25 +0000146#include "transaction.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700147#include "verifier/class_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700148#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700149
Nicolas Geoffray00391822019-12-10 10:17:23 +0000150#include "interpreter/interpreter_mterp_impl.h"
151
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700152namespace art {
153
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800154using android::base::StringPrintf;
155
Orion Hodson5880c772020-07-28 20:12:08 +0100156static constexpr bool kCheckImageObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700157static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700158
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700159static void ThrowNoClassDefFoundError(const char* fmt, ...)
160 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700161 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700162static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700163 va_list args;
164 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800165 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000166 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800167 va_end(args);
168}
169
Andreas Gampe99babb62015-11-02 16:20:00 -0800170static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700171 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700172 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700173 StackHandleScope<1> hs(self);
174 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700175 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700176 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700177
178 if (exception_class == nullptr) {
179 // No exc class ~ no <init>-with-string.
180 CHECK(self->IsExceptionPending());
181 self->ClearException();
182 return false;
183 }
184
Vladimir Markoba118822017-06-12 15:41:56 +0100185 ArtMethod* exception_init_method = exception_class->FindConstructor(
186 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700187 return exception_init_method != nullptr;
188}
189
Vladimir Markobb206de2019-03-28 10:30:32 +0000190static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700191 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700192 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
193 if (ext == nullptr) {
194 return nullptr;
195 } else {
196 return ext->GetVerifyError();
197 }
198}
199
200// Helper for ThrowEarlierClassFailure. Throws the stored error.
201static void HandleEarlierVerifyError(Thread* self,
202 ClassLinker* class_linker,
203 ObjPtr<mirror::Class> c)
204 REQUIRES_SHARED(Locks::mutator_lock_) {
205 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800206 DCHECK(obj != nullptr);
207 self->AssertNoPendingException();
208 if (obj->IsClass()) {
209 // Previous error has been stored as class. Create a new exception of that type.
210
211 // It's possible the exception doesn't have a <init>(String).
212 std::string temp;
213 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
214
215 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700216 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800217 } else {
218 self->ThrowNewException(descriptor, nullptr);
219 }
220 } else {
221 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100222 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700223 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800224 CHECK(throwable_class->IsAssignableFrom(error_class));
225 self->SetException(obj->AsThrowable());
226 }
227 self->AssertPendingException();
228}
229
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000230static void ChangeInterpreterBridgeToNterp(ArtMethod* method, ClassLinker* class_linker)
231 REQUIRES_SHARED(Locks::mutator_lock_) {
232 Runtime* runtime = Runtime::Current();
233 if (class_linker->IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode()) &&
234 interpreter::CanMethodUseNterp(method)) {
235 if (method->GetDeclaringClass()->IsVisiblyInitialized() ||
236 !NeedsClinitCheckBeforeCall(method)) {
237 runtime->GetInstrumentation()->UpdateMethodsCode(method, interpreter::GetNterpEntryPoint());
238 } else {
239 // Put the resolution stub, which will initialize the class and then
240 // call the method with nterp.
241 runtime->GetInstrumentation()->UpdateMethodsCode(method, GetQuickResolutionStub());
242 }
243 }
244}
245
Andreas Gampe5b20b352018-10-11 19:03:20 -0700246// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
247// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
248// before.
Andreas Gampe5b20b352018-10-11 19:03:20 -0700249static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
250 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000251 Runtime* runtime = Runtime::Current();
252 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampe5b20b352018-10-11 19:03:20 -0700253 if (!klass->WasVerificationAttempted()) {
254 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
255 klass->SetVerificationAttempted();
Nicolas Geoffray00391822019-12-10 10:17:23 +0000256 // Now that the class has passed verification, try to set nterp entrypoints
257 // to methods that currently use the switch interpreter.
258 if (interpreter::CanRuntimeUseNterp()) {
259 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000260 ChangeInterpreterBridgeToNterp(&m, class_linker);
Nicolas Geoffray00391822019-12-10 10:17:23 +0000261 }
262 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700263 }
264}
265
Vladimir Markobf121912019-06-04 13:49:05 +0100266// Callback responsible for making a batch of classes visibly initialized
267// after all threads have called it from a checkpoint, ensuring visibility.
268class ClassLinker::VisiblyInitializedCallback final
269 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
270 public:
271 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
272 : class_linker_(class_linker),
273 num_classes_(0u),
274 thread_visibility_counter_(0),
275 barriers_() {
276 std::fill_n(classes_, kMaxClasses, nullptr);
277 }
278
279 bool IsEmpty() const {
280 DCHECK_LE(num_classes_, kMaxClasses);
281 return num_classes_ == 0u;
282 }
283
284 bool IsFull() const {
285 DCHECK_LE(num_classes_, kMaxClasses);
286 return num_classes_ == kMaxClasses;
287 }
288
289 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
290 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
291 DCHECK(!IsFull());
292 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
293 ++num_classes_;
294 }
295
296 void AddBarrier(Barrier* barrier) {
297 barriers_.push_front(barrier);
298 }
299
300 std::forward_list<Barrier*> GetAndClearBarriers() {
301 std::forward_list<Barrier*> result;
302 result.swap(barriers_);
303 result.reverse(); // Return barriers in insertion order.
304 return result;
305 }
306
307 void MakeVisible(Thread* self) {
308 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
309 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
310 AdjustThreadVisibilityCounter(self, count);
311 }
312
313 void Run(Thread* self) override {
314 self->ClearMakeVisiblyInitializedCounter();
315 AdjustThreadVisibilityCounter(self, -1);
316 }
317
318 private:
319 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
320 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
321 if (old + adjustment == 0) {
322 // All threads passed the checkpoint. Mark classes as visibly initialized.
323 {
324 ScopedObjectAccess soa(self);
325 StackHandleScope<1u> hs(self);
326 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
327 JavaVMExt* vm = self->GetJniEnv()->GetVm();
328 for (size_t i = 0, num = num_classes_; i != num; ++i) {
329 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
330 vm->DeleteWeakGlobalRef(self, classes_[i]);
331 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100332 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100333 class_linker_->FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100334 }
335 }
336 num_classes_ = 0u;
337 }
338 class_linker_->VisiblyInitializedCallbackDone(self, this);
339 }
340 }
341
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100342 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100343
344 ClassLinker* const class_linker_;
345 size_t num_classes_;
346 jweak classes_[kMaxClasses];
347
348 // The thread visibility counter starts at 0 and it is incremented by the number of
349 // threads that need to run this callback (by the thread that request the callback
350 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
351 // whether after the increment or after a decrement, we know that `Run()` was executed
352 // for all threads and therefore we can mark the classes as visibly initialized.
353 std::atomic<ssize_t> thread_visibility_counter_;
354
355 // List of barries to `Pass()` for threads that wait for the callback to complete.
356 std::forward_list<Barrier*> barriers_;
357};
358
359void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
360 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
361 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
362 }
363 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
364 if (wait) {
365 maybe_barrier.emplace(0);
366 }
367 int wait_count = 0;
368 VisiblyInitializedCallback* callback = nullptr;
369 {
370 MutexLock lock(self, visibly_initialized_callback_lock_);
371 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
372 callback = visibly_initialized_callback_.release();
373 running_visibly_initialized_callbacks_.push_front(*callback);
374 }
375 if (wait) {
376 DCHECK(maybe_barrier.has_value());
377 Barrier* barrier = std::addressof(*maybe_barrier);
378 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
379 cb.AddBarrier(barrier);
380 ++wait_count;
381 }
382 }
383 }
384 if (callback != nullptr) {
385 callback->MakeVisible(self);
386 }
387 if (wait_count != 0) {
388 DCHECK(maybe_barrier.has_value());
389 maybe_barrier->Increment(self, wait_count);
390 }
391}
392
393void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
394 VisiblyInitializedCallback* callback) {
395 MutexLock lock(self, visibly_initialized_callback_lock_);
396 // Pass the barriers if requested.
397 for (Barrier* barrier : callback->GetAndClearBarriers()) {
398 barrier->Pass(self);
399 }
400 // Remove the callback from the list of running callbacks.
401 auto before = running_visibly_initialized_callbacks_.before_begin();
402 auto it = running_visibly_initialized_callbacks_.begin();
403 DCHECK(it != running_visibly_initialized_callbacks_.end());
404 while (std::addressof(*it) != callback) {
405 before = it;
406 ++it;
407 DCHECK(it != running_visibly_initialized_callbacks_.end());
408 }
409 running_visibly_initialized_callbacks_.erase_after(before);
410 // Reuse or destroy the callback object.
411 if (visibly_initialized_callback_ == nullptr) {
412 visibly_initialized_callback_.reset(callback);
413 } else {
414 delete callback;
415 }
416}
417
Alex Lightfb119572019-09-18 15:04:53 -0700418void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
419 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
420 if (cb != nullptr) {
421 cb->MakeVisible(self);
422 }
423 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
424 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
425}
426
Vladimir Markobf121912019-06-04 13:49:05 +0100427ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
428 Thread* self, Handle<mirror::Class> klass) {
429 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
430 // Thanks to the x86 memory model, we do not need any memory fences and
431 // we can immediately mark the class as visibly initialized.
432 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100433 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100434 return nullptr;
435 }
436 if (Runtime::Current()->IsActiveTransaction()) {
437 // Transactions are single-threaded, so we can mark the class as visibly intialized.
438 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
439 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100440 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100441 return nullptr;
442 }
443 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
444 MutexLock lock(self, visibly_initialized_callback_lock_);
445 if (visibly_initialized_callback_ == nullptr) {
446 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
447 }
448 DCHECK(!visibly_initialized_callback_->IsFull());
449 visibly_initialized_callback_->AddClass(self, klass.Get());
450
451 if (visibly_initialized_callback_->IsFull()) {
452 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
453 running_visibly_initialized_callbacks_.push_front(*callback);
454 return callback;
455 } else {
456 return nullptr;
457 }
458}
459
Vladimir Marko86c87522020-05-11 16:55:55 +0100460const void* ClassLinker::RegisterNative(
461 Thread* self, ArtMethod* method, const void* native_method) {
462 CHECK(method->IsNative()) << method->PrettyMethod();
463 CHECK(native_method != nullptr) << method->PrettyMethod();
464 void* new_native_method = nullptr;
465 Runtime* runtime = Runtime::Current();
466 runtime->GetRuntimeCallbacks()->RegisterNativeMethod(method,
467 native_method,
468 /*out*/&new_native_method);
469 if (method->IsCriticalNative()) {
470 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
471 // Remove old registered method if any.
472 auto it = critical_native_code_with_clinit_check_.find(method);
473 if (it != critical_native_code_with_clinit_check_.end()) {
474 critical_native_code_with_clinit_check_.erase(it);
475 }
476 // To ensure correct memory visibility, we need the class to be visibly
477 // initialized before we can set the JNI entrypoint.
478 if (method->GetDeclaringClass()->IsVisiblyInitialized()) {
479 method->SetEntryPointFromJni(new_native_method);
480 } else {
481 critical_native_code_with_clinit_check_.emplace(method, new_native_method);
482 }
483 } else {
484 method->SetEntryPointFromJni(new_native_method);
485 }
486 return new_native_method;
487}
488
489void ClassLinker::UnregisterNative(Thread* self, ArtMethod* method) {
490 CHECK(method->IsNative()) << method->PrettyMethod();
491 // Restore stub to lookup native pointer via dlsym.
492 if (method->IsCriticalNative()) {
493 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
494 auto it = critical_native_code_with_clinit_check_.find(method);
495 if (it != critical_native_code_with_clinit_check_.end()) {
496 critical_native_code_with_clinit_check_.erase(it);
497 }
498 method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
499 } else {
500 method->SetEntryPointFromJni(GetJniDlsymLookupStub());
501 }
502}
503
504const void* ClassLinker::GetRegisteredNative(Thread* self, ArtMethod* method) {
505 if (method->IsCriticalNative()) {
506 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
507 auto it = critical_native_code_with_clinit_check_.find(method);
508 if (it != critical_native_code_with_clinit_check_.end()) {
509 return it->second;
510 }
511 const void* native_code = method->GetEntryPointFromJni();
512 return IsJniDlsymLookupCriticalStub(native_code) ? nullptr : native_code;
513 } else {
514 const void* native_code = method->GetEntryPointFromJni();
515 return IsJniDlsymLookupStub(native_code) ? nullptr : native_code;
516 }
517}
518
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800519void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
520 bool wrap_in_no_class_def,
521 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700522 // The class failed to initialize on a previous attempt, so we want to throw
523 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
524 // failed in verification, in which case v2 5.4.1 says we need to re-throw
525 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800526 Runtime* const runtime = Runtime::Current();
527 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700528 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000529 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
530 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800531 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700532 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800533 } else {
534 extra = verify_error->AsThrowable()->Dump();
535 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700536 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800537 if (log) {
538 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
539 << ": " << extra;
540 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700541 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700542
David Sehr709b0702016-10-13 09:12:37 -0700543 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800544 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800545 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700546 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700547 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000548 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700549 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000550 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
551 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800552 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800553 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800554 }
Alex Lightd6251582016-10-31 11:12:30 -0700555 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
556 // might have meant to go down the earlier if statement with the original error but it got
557 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000558 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800559 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
560 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
561 // exception will be a cause.
562 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700563 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700564 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700565 }
566}
567
Brian Carlstromb23eab12014-10-08 17:55:21 -0700568static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700569 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700570 if (VLOG_IS_ON(class_linker)) {
571 std::string temp;
572 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000573 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700574 }
575}
576
577static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700578 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700579 Thread* self = Thread::Current();
580 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700581
582 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700583 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700584
David Srbecky346fd962020-07-27 16:51:00 +0100585 // Boot classpath classes should not fail initialization. This is a consistency debug check.
586 // This cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800587 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800588 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800589 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
590 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
591 // could have caused the error.
592 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
593 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
594 << " failed initialization: "
595 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800596 }
597
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700598 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700599 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
600 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700601
Elliott Hughesa4f94742012-05-29 16:28:38 -0700602 // We only wrap non-Error exceptions; an Error can just be used as-is.
603 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000604 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700605 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700606 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700607}
608
Fred Shih381e4ca2014-08-25 17:24:27 -0700609// Gap between two fields in object layout.
610struct FieldGap {
611 uint32_t start_offset; // The offset from the start of the object.
612 uint32_t size; // The gap size of 1, 2, or 4 bytes.
613};
614struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800615 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700616 }
617 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
618 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800619 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700620 // Note that the priority queue returns the largest element, so operator()
621 // should return true if lhs is less than rhs.
622 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700623 }
624};
Andreas Gampec55bb392018-09-21 00:02:02 +0000625using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700626
627// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800628static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700629 DCHECK(gaps != nullptr);
630
631 uint32_t current_offset = gap_start;
632 while (current_offset != gap_end) {
633 size_t remaining = gap_end - current_offset;
634 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
635 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
636 current_offset += sizeof(uint32_t);
637 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
638 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
639 current_offset += sizeof(uint16_t);
640 } else {
641 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
642 current_offset += sizeof(uint8_t);
643 }
644 DCHECK_LE(current_offset, gap_end) << "Overran gap";
645 }
646}
647// Shuffle fields forward, making use of gaps whenever possible.
648template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000649static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700650 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700651 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700652 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700653 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700654 DCHECK(current_field_idx != nullptr);
655 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700656 DCHECK(gaps != nullptr);
657 DCHECK(field_offset != nullptr);
658
659 DCHECK(IsPowerOfTwo(n));
660 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700661 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700662 Primitive::Type type = field->GetTypeAsPrimitiveType();
663 if (Primitive::ComponentSize(type) < n) {
664 break;
665 }
666 if (!IsAligned<n>(field_offset->Uint32Value())) {
667 MemberOffset old_offset = *field_offset;
668 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
669 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
670 }
David Sehr709b0702016-10-13 09:12:37 -0700671 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700672 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700673 if (!gaps->empty() && gaps->top().size >= n) {
674 FieldGap gap = gaps->top();
675 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100676 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700677 field->SetOffset(MemberOffset(gap.start_offset));
678 if (gap.size > n) {
679 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
680 }
681 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100682 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700683 field->SetOffset(*field_offset);
684 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
685 }
686 ++(*current_field_idx);
687 }
688}
689
Andreas Gampe87658f32019-04-18 18:39:02 +0000690ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700691 : boot_class_table_(new ClassTable()),
692 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800693 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800694 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700695 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000696 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700697 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000698 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000699 jni_dlsym_lookup_trampoline_(nullptr),
Vladimir Markofa458ac2020-02-12 14:08:07 +0000700 jni_dlsym_lookup_critical_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800701 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800702 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100703 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800704 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700705 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100706 visibly_initialized_callback_lock_("visibly initialized callback lock"),
707 visibly_initialized_callback_(nullptr),
Vladimir Marko86c87522020-05-11 16:55:55 +0100708 critical_native_code_with_clinit_check_lock_("critical native code with clinit check lock"),
709 critical_native_code_with_clinit_check_(),
Andreas Gampe7dface32017-07-25 21:32:59 -0700710 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
711 // For CHA disabled during Aot, see b/34193647.
712
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700713 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700714 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
715 "Array cache size wrong.");
716 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700717}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700718
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800719void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700720 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800721 if (c2 == nullptr) {
722 LOG(FATAL) << "Could not find class " << descriptor;
723 UNREACHABLE();
724 }
725 if (c1.Get() != c2) {
726 std::ostringstream os1, os2;
727 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
728 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
729 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
730 << ". This is most likely the result of a broken build. Make sure that "
731 << "libcore and art projects match.\n\n"
732 << os1.str() << "\n\n" << os2.str();
733 UNREACHABLE();
734 }
735}
736
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800737bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
738 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800739 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700740
Mathieu Chartiere401d142015-04-22 13:56:20 -0700741 Thread* const self = Thread::Current();
742 Runtime* const runtime = Runtime::Current();
743 gc::Heap* const heap = runtime->GetHeap();
744
Jeff Haodcdc85b2015-12-04 14:06:18 -0800745 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700746 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700747
Mathieu Chartiere401d142015-04-22 13:56:20 -0700748 // Use the pointer size from the runtime since we are probably creating the image.
749 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
750
Elliott Hughes30646832011-10-13 16:59:46 -0700751 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700752 // 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 -0800753 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700754 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700755 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700756 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
757 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000758 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100759 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800760 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100761 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700762 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700763 if (kUseBakerReadBarrier) {
764 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800765 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700766 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700767 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800768 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700769 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700770
Elliott Hughes418d20f2011-09-22 14:00:39 -0700771 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700772 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700773 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700774 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700775 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700776
Ian Rogers23435d02012-09-24 11:23:12 -0700777 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700778 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700779 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800780 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700781 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700782 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000783 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700784
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700785 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800786 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
787 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100788 runtime->SetSentinel(heap->AllocNonMovableObject(self,
789 java_lang_Object.Get(),
790 java_lang_Object->GetObjectSize(),
791 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700792
Igor Murashkin86083f72017-10-27 10:59:04 -0700793 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000794 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700795 // It might seem the lock here is unnecessary, however all the SubtypeCheck
796 // functions are annotated to require locks all the way down.
797 //
798 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
799 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000800 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
801 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700802 }
803
Ian Rogers23435d02012-09-24 11:23:12 -0700804 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700805 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700806 AllocClass(self, java_lang_Class.Get(),
807 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700808 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700809
Roland Levillain0e840272018-08-23 19:55:30 +0100810 // Setup java.lang.String.
811 //
812 // We make this class non-movable for the unlikely case where it were to be
813 // moved by a sticky-bit (minor) collection when using the Generational
814 // Concurrent Copying (CC) collector, potentially creating a stale reference
815 // in the `klass_` field of one of its instances allocated in the Large-Object
816 // Space (LOS) -- see the comment about the dirty card scanning logic in
817 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700818 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700819 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100820 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700821 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000822 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400823
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700824 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700825 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700826 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700827 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000828 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700829
Ian Rogers23435d02012-09-24 11:23:12 -0700830 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700831 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100832 mirror::ObjectArray<mirror::Class>::Alloc(self,
833 object_array_class.Get(),
834 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700835 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100836 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
837 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
838 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
839 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100840 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
841 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700842
Mathieu Chartier6beced42016-11-15 15:51:31 -0800843 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
844 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
845
Vladimir Marko02610552018-06-04 14:38:00 +0100846 // Create array interface entries to populate once we can load system classes.
847 object_array_class->SetIfTable(AllocIfTable(self, 2));
848 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
849
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700850 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100851 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
852 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
853 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
854 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
855 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
856 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
857 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
858 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
859 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700860
Vladimir Marko70e2a762019-07-12 16:49:00 +0100861 // Allocate the primitive array classes. We need only the native pointer
862 // array at this point (int[] or long[], depending on architecture) but
863 // we shall perform the same setup steps for all primitive array classes.
864 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
865 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
866 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
867 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
868 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
869 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
870 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
871 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700872
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700873 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700874
Ian Rogers52813c92012-10-11 11:50:38 -0700875 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700876 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700877 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100878 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100879 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700880 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000881 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700882
Alex Lightd6251582016-10-31 11:12:30 -0700883
884 // Setup dalvik.system.ClassExt
885 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
886 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100887 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000888 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700889
Mathieu Chartier66f19252012-09-18 08:57:04 -0700890 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700891 Handle<mirror::Class> object_array_string(hs.NewHandle(
892 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700893 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700894 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100895 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700896
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000897 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700898 // Create runtime resolution and imt conflict methods.
899 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000900 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
901 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700902
Ian Rogers23435d02012-09-24 11:23:12 -0700903 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
904 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
905 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800906 if (boot_class_path.empty()) {
907 *error_msg = "Boot classpath is empty.";
908 return false;
909 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800910 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800911 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800912 *error_msg = "Null dex file.";
913 return false;
914 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800915 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800916 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700917 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700918
919 // now we can use FindSystemClass
920
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700921 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
922 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700923 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800924 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700925 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000926 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Vladimir Markofa458ac2020-02-12 14:08:07 +0000927 jni_dlsym_lookup_critical_trampoline_ = GetJniDlsymLookupCriticalStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700928 quick_resolution_trampoline_ = GetQuickResolutionStub();
929 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000930 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700931 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700932 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700933
Alex Lightd6251582016-10-31 11:12:30 -0700934 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000935 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800936 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700937 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000938 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800939 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000940 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800941 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700942 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000943 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700944 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
945 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700946
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800947 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
948 // in class_table_.
949 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700950
Vladimir Marko70e2a762019-07-12 16:49:00 +0100951 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
952 // arrays - can't be done until Object has a vtable and component classes are loaded.
953 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
954 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
955 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
956 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
957 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
958 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
959 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
960 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
961 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
962 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
963 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700964
Ian Rogers23435d02012-09-24 11:23:12 -0700965 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700966 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800967 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700968 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800969 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700970 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
971 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100972 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
973 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700974
David Srbecky346fd962020-07-27 16:51:00 +0100975 // Check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread suspension.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700976 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000977 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700978 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000979 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700980 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000981 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700982 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000983 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700984
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700985 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100986 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700987
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800988 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700989
Ian Rogers23435d02012-09-24 11:23:12 -0700990 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100991 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
992 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700993
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700994 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100995 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700996 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100997 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700998
999 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001000 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
1001 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001002 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001003
1004 // Create java.lang.reflect.Constructor.class root and array root.
1005 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
1006 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001007 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001008 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
1009 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001010 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001011
1012 // Create java.lang.reflect.Method.class root and array root.
1013 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
1014 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001015 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001016 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
1017 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001018 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001019
Orion Hodson005ac512017-10-24 15:43:43 +01001020 // Create java.lang.invoke.CallSite.class root
1021 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
1022 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001023 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001024
Narayan Kamathafa48272016-08-03 12:46:58 +01001025 // Create java.lang.invoke.MethodType.class root
1026 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
1027 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001028 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +01001029
1030 // Create java.lang.invoke.MethodHandleImpl.class root
1031 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
1032 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001033 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01001034 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +01001035
Orion Hodsonc069a302017-01-18 09:23:12 +00001036 // Create java.lang.invoke.MethodHandles.Lookup.class root
1037 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
1038 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001039 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +00001040
Orion Hodson005ac512017-10-24 15:43:43 +01001041 // Create java.lang.invoke.VarHandle.class root
1042 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +00001043 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001044 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001045
1046 // Create java.lang.invoke.FieldVarHandle.class root
1047 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
1048 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001049 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001050
1051 // Create java.lang.invoke.ArrayElementVarHandle.class root
1052 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
1053 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001054 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001055
1056 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
1057 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
1058 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001059 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +01001060
1061 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
1062 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
1063 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001064 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +00001065
Narayan Kamath000e1882016-10-24 17:14:25 +01001066 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
1067 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001068 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +01001069
Brian Carlstrom1f870082011-08-23 16:02:11 -07001070 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -07001071 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +00001072 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -08001073 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -07001074 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001075 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
1076 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001077 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001078 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001079 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001080 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001081 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001082 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001083 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001084 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001085 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001086 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001087 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001088 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001089
Ian Rogers23435d02012-09-24 11:23:12 -07001090 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001091 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001092 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001093 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001094 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001095
jeffhao8cd6dda2012-02-22 10:15:34 -08001096 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -07001097 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001098 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001099 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -07001100 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001101 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
1102 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
1103 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001104 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001105 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1106 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001107
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001108 // Create conflict tables that depend on the class linker.
1109 runtime->FixupConflictTables();
1110
Ian Rogers98379392014-02-24 16:53:16 -08001111 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001112
Brian Carlstroma004aa92012-02-08 18:05:09 -08001113 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001114
1115 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001116}
1117
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001118static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1119 REQUIRES_SHARED(Locks::mutator_lock_) {
1120 // Find String.<init> -> StringFactory bindings.
1121 ObjPtr<mirror::Class> string_factory_class =
1122 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1123 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001124 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001125 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1126 // Update the primordial thread.
1127 self->InitStringEntryPoints();
1128}
1129
Ian Rogers98379392014-02-24 16:53:16 -08001130void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001131 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001132
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001133 CreateStringInitBindings(self, this);
1134
Brian Carlstrom16192862011-09-12 17:50:06 -07001135 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001136 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001137 // as the types of the field can't be resolved prior to the runtime being
1138 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001139 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001140 Handle<mirror::Class> java_lang_ref_Reference =
1141 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001142 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1143 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001144
Mathieu Chartierc7853442015-03-27 14:35:38 -07001145 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001146 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1147 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001148
Mathieu Chartierc7853442015-03-27 14:35:38 -07001149 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001150 CHECK_STREQ(queue->GetName(), "queue");
1151 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001152
Mathieu Chartierc7853442015-03-27 14:35:38 -07001153 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001154 CHECK_STREQ(queueNext->GetName(), "queueNext");
1155 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001156
Mathieu Chartierc7853442015-03-27 14:35:38 -07001157 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001158 CHECK_STREQ(referent->GetName(), "referent");
1159 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001160
Mathieu Chartierc7853442015-03-27 14:35:38 -07001161 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001162 CHECK_STREQ(zombie->GetName(), "zombie");
1163 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001164
Brian Carlstroma663ea52011-08-19 23:33:41 -07001165 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001166 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001167 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001168 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001169 CHECK(klass != nullptr);
1170 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001171 // note SetClassRoot does additional validation.
1172 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001173 }
1174
Vladimir Marko02610552018-06-04 14:38:00 +01001175 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001176
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001177 // disable the slow paths in FindClass and CreatePrimitiveClass now
1178 // that Object, Class, and Object[] are setup
1179 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001180
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001181 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1182 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1183 // ensure that the class will be initialized.
1184 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001185 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001186
1187 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1188 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1189 // Strange, but don't crash.
1190 LOG(WARNING) << "Could not prepare StackOverflowError.";
1191 self->ClearException();
1192 }
1193 }
1194
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001195 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001196}
1197
Vladimir Markodcfcce42018-06-27 10:00:28 +00001198void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001199 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1200 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001201 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001202 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001203 Handle<mirror::Class> h_class(hs.NewHandle(c));
David Srbecky08110ef2020-05-20 19:33:43 +01001204 if (!EnsureInitialized(self, h_class, true, true)) {
1205 LOG(FATAL) << "Exception when initializing " << h_class->PrettyClass()
1206 << ": " << self->GetException()->Dump();
1207 }
Vladimir Markodcfcce42018-06-27 10:00:28 +00001208 } else {
1209 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001210 }
1211 }
1212}
1213
Jeff Haodcdc85b2015-12-04 14:06:18 -08001214struct TrampolineCheckData {
1215 const void* quick_resolution_trampoline;
1216 const void* quick_imt_conflict_trampoline;
1217 const void* quick_generic_jni_trampoline;
1218 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001219 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001220 ArtMethod* m;
1221 bool error;
1222};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001223
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001224bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1225 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001226 CHECK(!init_done_);
1227
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001228 Runtime* const runtime = Runtime::Current();
1229 Thread* const self = Thread::Current();
1230 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001231 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1232 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001233 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1234 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001235 if (!ValidPointerSize(pointer_size_unchecked)) {
1236 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001237 return false;
1238 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001239 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001240 if (!runtime->IsAotCompiler()) {
1241 // Only the Aot compiler supports having an image with a different pointer size than the
1242 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1243 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001244 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001245 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001246 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001247 sizeof(void*));
1248 return false;
1249 }
1250 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001251 DCHECK(!runtime->HasResolutionMethod());
1252 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1253 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1254 runtime->SetImtUnimplementedMethod(
1255 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1256 runtime->SetCalleeSaveMethod(
1257 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1258 CalleeSaveType::kSaveAllCalleeSaves);
1259 runtime->SetCalleeSaveMethod(
1260 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1261 CalleeSaveType::kSaveRefsOnly);
1262 runtime->SetCalleeSaveMethod(
1263 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1264 CalleeSaveType::kSaveRefsAndArgs);
1265 runtime->SetCalleeSaveMethod(
1266 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1267 CalleeSaveType::kSaveEverything);
1268 runtime->SetCalleeSaveMethod(
1269 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1270 CalleeSaveType::kSaveEverythingForClinit);
1271 runtime->SetCalleeSaveMethod(
1272 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1273 CalleeSaveType::kSaveEverythingForSuspendCheck);
1274
Jeff Haodcdc85b2015-12-04 14:06:18 -08001275 std::vector<const OatFile*> oat_files =
1276 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1277 DCHECK(!oat_files.empty());
1278 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001279 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001280 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001281 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1282 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1283 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1284 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1285 if (kIsDebugBuild) {
1286 // Check that the other images use the same trampoline.
1287 for (size_t i = 1; i < oat_files.size(); ++i) {
1288 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001289 const void* ith_jni_dlsym_lookup_trampoline_ =
1290 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001291 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1292 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001293 const void* ith_quick_resolution_trampoline =
1294 ith_oat_header.GetQuickResolutionTrampoline();
1295 const void* ith_quick_imt_conflict_trampoline =
1296 ith_oat_header.GetQuickImtConflictTrampoline();
1297 const void* ith_quick_generic_jni_trampoline =
1298 ith_oat_header.GetQuickGenericJniTrampoline();
1299 const void* ith_quick_to_interpreter_bridge_trampoline =
1300 ith_oat_header.GetQuickToInterpreterBridge();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001301 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001302 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001303 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001304 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1305 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1306 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1307 // Make sure that all methods in this image do not contain those trampolines as
1308 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1309 TrampolineCheckData data;
1310 data.error = false;
1311 data.pointer_size = GetImagePointerSize();
1312 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1313 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1314 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1315 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1316 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001317 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1318 if (obj->IsClass()) {
1319 ObjPtr<mirror::Class> klass = obj->AsClass();
1320 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1321 const void* entrypoint =
1322 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1323 if (entrypoint == data.quick_resolution_trampoline ||
1324 entrypoint == data.quick_imt_conflict_trampoline ||
1325 entrypoint == data.quick_generic_jni_trampoline ||
1326 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1327 data.m = &m;
1328 data.error = true;
1329 return;
1330 }
1331 }
1332 }
1333 };
1334 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001335 if (data.error) {
1336 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001337 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001338 *error_msg = "Found an ArtMethod with a bad entrypoint";
1339 return false;
1340 }
1341 }
1342 }
1343 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001344
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001345 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001346 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001347 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001348 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001349
Vladimir Marko024d69f2019-06-13 10:52:32 +01001350 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1351 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1352 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1353 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1354 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1355 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001356
Vladimir Markod1908512018-11-22 14:57:28 +00001357 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001358 // Boot class loader, use a null handle.
1359 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001360 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001361 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001362 /*out*/&dex_files,
1363 error_msg)) {
1364 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001365 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001366 // Append opened dex files at the end.
1367 boot_dex_files_.insert(boot_dex_files_.end(),
1368 std::make_move_iterator(dex_files.begin()),
1369 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001370 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001371 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1372 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1373 }
Ian Rogers98379392014-02-24 16:53:16 -08001374 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001375
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001376 VLOG(startup) << __FUNCTION__ << " exiting";
1377 return true;
1378}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001379
Vladimir Marko4433c432018-12-04 14:57:47 +00001380void ClassLinker::AddExtraBootDexFiles(
1381 Thread* self,
1382 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1383 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001384 AppendToBootClassPath(self, dex_file.get());
Vladimir Marko4433c432018-12-04 14:57:47 +00001385 boot_dex_files_.push_back(std::move(dex_file));
1386 }
1387}
1388
Jeff Hao5872d7c2016-04-27 11:07:41 -07001389bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001390 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001391 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001392 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1393 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001394}
1395
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001396class CHAOnDeleteUpdateClassVisitor {
1397 public:
1398 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1399 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1400 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1401 self_(Thread::Current()) {}
1402
1403 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1404 // This class is going to be unloaded. Tell CHA about it.
1405 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1406 return true;
1407 }
1408 private:
1409 const LinearAlloc* allocator_;
1410 const ClassHierarchyAnalysis* cha_;
1411 const PointerSize pointer_size_;
1412 const Thread* self_;
1413};
1414
Chris Wailes0c61be42018-09-26 17:27:34 -07001415/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001416 * A class used to ensure that all references to strings interned in an AppImage have been
1417 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001418 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001419class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001420 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001421 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1422 const InternTable::UnorderedSet& image_interns)
1423 : space_(space),
1424 image_interns_(image_interns),
1425 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001426
Chris Wailes0c61be42018-09-26 17:27:34 -07001427 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001428 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001429 if (referred_obj != nullptr &&
1430 space_.HasAddress(referred_obj.Ptr()) &&
1431 referred_obj->IsString()) {
1432 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001433 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1434 if (it != image_interns_.end() && it->Read() == referred_str) {
1435 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001436 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001437 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001438 }
1439
Chris Wailes0c61be42018-09-26 17:27:34 -07001440 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001441 mirror::CompressedReference<mirror::Object>* root) const
1442 REQUIRES_SHARED(Locks::mutator_lock_) {
1443 if (!root->IsNull()) {
1444 VisitRoot(root);
1445 }
1446 }
1447
Chris Wailes0c61be42018-09-26 17:27:34 -07001448 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001449 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001450 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001451 }
1452
1453 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001454 void operator()(ObjPtr<mirror::Object> obj,
1455 MemberOffset offset,
1456 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001457 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001458 // References within image or across images don't need a read barrier.
1459 ObjPtr<mirror::Object> referred_obj =
1460 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1461 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001462 }
1463
1464 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1465 ObjPtr<mirror::Reference> ref) const
1466 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001467 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001468 }
1469
Vladimir Marko8e05f092019-06-10 11:10:38 +01001470 size_t GetCount() const {
1471 return count_;
1472 }
1473
1474 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001475 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001476 const InternTable::UnorderedSet& image_interns_;
1477 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001478};
1479
Chris Wailes0c61be42018-09-26 17:27:34 -07001480/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001481 * This function counts references to strings interned in the AppImage.
1482 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001483 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001484size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1485 const InternTable::UnorderedSet& image_interns)
1486 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001487 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1488 const ImageHeader& image_header = space.GetImageHeader();
1489 const uint8_t* target_base = space.GetMemMap()->Begin();
1490 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001491
1492 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1493 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001494
Vladimir Marko8e05f092019-06-10 11:10:38 +01001495 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001496 bitmap->VisitMarkedRange(objects_begin,
1497 objects_end,
1498 [&space, &visitor](mirror::Object* obj)
1499 REQUIRES_SHARED(Locks::mutator_lock_) {
1500 if (space.HasAddress(obj)) {
1501 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001502 obj->VisitReferences</* kVisitNativeRoots= */ true,
1503 kVerifyNone,
1504 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001505 } else {
1506 // Don't visit native roots for non-dex-cache as they can't contain
1507 // native references to strings. This is verified during compilation
1508 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001509 obj->VisitReferences</* kVisitNativeRoots= */ false,
1510 kVerifyNone,
1511 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001512 }
1513 }
1514 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001515 return visitor.GetCount();
1516}
1517
1518template <typename Visitor>
1519static void VisitInternedStringReferences(
1520 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001521 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1522 const uint8_t* target_base = space->Begin();
1523 const ImageSection& sro_section =
1524 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1525 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1526
1527 VLOG(image)
1528 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1529 << num_string_offsets;
1530
1531 const auto* sro_base =
1532 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1533
1534 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1535 uint32_t base_offset = sro_base[offset_index].first;
1536
David Srbecky86d6cd52020-12-02 18:13:10 +00001537 uint32_t raw_member_offset = sro_base[offset_index].second;
1538 DCHECK_ALIGNED(base_offset, 2);
1539 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001540
David Srbecky86d6cd52020-12-02 18:13:10 +00001541 ObjPtr<mirror::Object> obj_ptr =
1542 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1543 MemberOffset member_offset(raw_member_offset);
1544 ObjPtr<mirror::String> referred_string =
1545 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001546 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001547 kWithoutReadBarrier,
1548 /* kIsVolatile= */ false>(member_offset);
1549 DCHECK(referred_string != nullptr);
1550
1551 ObjPtr<mirror::String> visited = visitor(referred_string);
1552 if (visited != referred_string) {
1553 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1554 /* kCheckTransaction= */ false,
1555 kVerifyNone,
1556 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001557 }
1558 }
1559}
1560
1561static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1562 REQUIRES_SHARED(Locks::mutator_lock_) {
1563 InternTable::UnorderedSet image_interns;
1564 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1565 if (section.Size() > 0) {
1566 size_t read_count;
1567 const uint8_t* data = space->Begin() + section.Offset();
1568 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1569 image_set.swap(image_interns);
1570 }
1571 size_t num_recorded_refs = 0u;
1572 VisitInternedStringReferences(
1573 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001574 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1575 REQUIRES_SHARED(Locks::mutator_lock_) {
1576 auto it = image_interns.find(GcRoot<mirror::String>(str));
1577 CHECK(it != image_interns.end());
1578 CHECK(it->Read() == str);
1579 ++num_recorded_refs;
1580 return str;
1581 });
1582 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1583 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001584}
1585
Andreas Gampe2af99022017-04-25 08:32:59 -07001586// new_class_set is the set of classes that were read from the class table section in the image.
1587// If there was no class table section, it is null.
1588// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001589class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001590 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001591 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001592 ClassLinker* class_linker,
1593 gc::space::ImageSpace* space,
1594 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001595 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001596 REQUIRES(!Locks::dex_lock_)
1597 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001598
Chris Wailesfbeef462018-10-19 14:16:35 -07001599 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001600 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001601};
1602
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001603void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001604 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001605 gc::space::ImageSpace* space,
1606 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001607 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001608 REQUIRES(!Locks::dex_lock_)
1609 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001610 ScopedTrace app_image_timing("AppImage:Updating");
1611
Vladimir Marko8e05f092019-06-10 11:10:38 +01001612 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1613 // In debug build, verify the string references before applying
1614 // the Runtime::LoadAppImageStartupCache() option.
1615 VerifyInternedStringReferences(space);
1616 }
1617
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001618 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001619 Runtime* const runtime = Runtime::Current();
1620 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001621 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001622 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001623 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001624 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001625 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001626 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001627 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001628 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001629 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001630 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001631 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001632 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001633 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001634
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001635 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001636 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001637 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001638
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001639 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001640 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001641 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001642 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1643 header.VisitPackedArtMethods([&](ArtMethod& method)
1644 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1645 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1646 if (klass != nullptr) {
1647 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1648 }
1649 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001650 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001651}
1652
Chris Wailesfbeef462018-10-19 14:16:35 -07001653void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001654 // Iterate over the string reference offsets stored in the image and intern
1655 // the strings they point to.
1656 ScopedTrace timing("AppImage:InternString");
1657
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001658 Runtime* const runtime = Runtime::Current();
1659 InternTable* const intern_table = runtime->GetInternTable();
1660
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001661 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1662 // for faster lookup.
1663 // TODO: Optimize with a bitmap or bloom filter
1664 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001665 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001666 REQUIRES_SHARED(Locks::mutator_lock_)
1667 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001668 const size_t non_boot_image_strings = intern_table->CountInterns(
1669 /*visit_boot_images=*/false,
1670 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001671 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001672 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1673 // Visit the smaller of the two sets to compute the intersection.
1674 if (interns.size() < non_boot_image_strings) {
1675 for (auto it = interns.begin(); it != interns.end(); ) {
1676 ObjPtr<mirror::String> string = it->Read();
1677 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1678 if (existing == nullptr) {
1679 existing = intern_table->LookupStrongLocked(string);
1680 }
1681 if (existing != nullptr) {
1682 intern_remap.Put(string.Ptr(), existing.Ptr());
1683 it = interns.erase(it);
1684 } else {
1685 ++it;
1686 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001687 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001688 } else {
1689 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1690 REQUIRES_SHARED(Locks::mutator_lock_)
1691 REQUIRES(Locks::intern_table_lock_) {
1692 auto it = interns.find(root);
1693 if (it != interns.end()) {
1694 ObjPtr<mirror::String> existing = root.Read();
1695 intern_remap.Put(it->Read(), existing.Ptr());
1696 it = interns.erase(it);
1697 }
1698 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1699 }
David Srbecky346fd962020-07-27 16:51:00 +01001700 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001701 if (kIsDebugBuild) {
1702 for (GcRoot<mirror::String>& root : interns) {
1703 ObjPtr<mirror::String> string = root.Read();
1704 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1705 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001706 }
1707 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001708 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001709 intern_table->AddImageStringsToTable(space, func);
1710 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001711 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001712 VisitInternedStringReferences(
1713 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001714 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1715 auto it = intern_remap.find(str.Ptr());
1716 if (it != intern_remap.end()) {
1717 return ObjPtr<mirror::String>(it->second);
1718 }
1719 return str;
1720 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001721 }
1722}
1723
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001724static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1725 const char* location,
1726 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001727 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001728 DCHECK(error_msg != nullptr);
1729 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001730 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001731 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001732 return std::unique_ptr<const DexFile>();
1733 }
1734 std::string inner_error_msg;
1735 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1736 if (dex_file == nullptr) {
1737 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1738 location,
1739 oat_file->GetLocation().c_str(),
1740 inner_error_msg.c_str());
1741 return std::unique_ptr<const DexFile>();
1742 }
1743
1744 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1745 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1746 location,
1747 dex_file->GetLocationChecksum(),
1748 oat_dex_file->GetDexFileLocationChecksum());
1749 return std::unique_ptr<const DexFile>();
1750 }
1751 return dex_file;
1752}
1753
1754bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1755 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1756 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001757 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001758 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001759 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001760 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001761 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001762 dex_caches_object->AsObjectArray<mirror::DexCache>();
1763 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001764 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001765 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1766 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1767 dex_file_location.c_str(),
1768 error_msg);
1769 if (dex_file == nullptr) {
1770 return false;
1771 }
1772 dex_cache->SetDexFile(dex_file.get());
1773 out_dex_files->push_back(std::move(dex_file));
1774 }
1775 return true;
1776}
1777
Andreas Gampe0793bec2016-12-01 11:37:33 -08001778// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1779// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001780class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001781 public:
1782 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1783 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001784 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001785 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1786 DCHECK(obj != nullptr);
1787 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1788 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1789 if (obj->IsClass()) {
1790 auto klass = obj->AsClass();
1791 for (ArtField& field : klass->GetIFields()) {
1792 CHECK_EQ(field.GetDeclaringClass(), klass);
1793 }
1794 for (ArtField& field : klass->GetSFields()) {
1795 CHECK_EQ(field.GetDeclaringClass(), klass);
1796 }
Orion Hodson5880c772020-07-28 20:12:08 +01001797 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001798 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001799 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001800 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001801 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001802 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001803 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001804 }
1805 if (klass->ShouldHaveImt()) {
1806 ImTable* imt = klass->GetImt(pointer_size);
1807 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001808 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001809 }
1810 }
1811 if (klass->ShouldHaveEmbeddedVTable()) {
1812 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001813 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001814 }
1815 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001816 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001817 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1818 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001819 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001820 }
1821 }
1822 }
1823 };
1824 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001825 }
1826
Andreas Gampe0793bec2016-12-01 11:37:33 -08001827 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001828 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001829 : spaces_(heap->GetBootImageSpaces()),
1830 pointer_size_(class_linker->GetImagePointerSize()) {
1831 space_begin_.reserve(spaces_.size());
1832 method_sections_.reserve(spaces_.size());
1833 runtime_method_sections_.reserve(spaces_.size());
1834 for (gc::space::ImageSpace* space : spaces_) {
1835 space_begin_.push_back(space->Begin());
1836 auto& header = space->GetImageHeader();
1837 method_sections_.push_back(&header.GetMethodsSection());
1838 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1839 }
1840 }
1841
Orion Hodson5880c772020-07-28 20:12:08 +01001842 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001843 REQUIRES_SHARED(Locks::mutator_lock_) {
1844 if (m->IsRuntimeMethod()) {
1845 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1846 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1847 } else if (m->IsCopied()) {
1848 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1849 } else if (expected_class != nullptr) {
1850 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1851 }
1852 if (!spaces_.empty()) {
1853 bool contains = false;
1854 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1855 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1856 contains = method_sections_[i]->Contains(offset) ||
1857 runtime_method_sections_[i]->Contains(offset);
1858 }
1859 CHECK(contains) << m << " not found";
1860 }
1861 }
1862
Orion Hodson5880c772020-07-28 20:12:08 +01001863 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1864 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001865 REQUIRES_SHARED(Locks::mutator_lock_) {
1866 CHECK(arr != nullptr);
1867 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1868 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1869 // expected_class == null means we are a dex cache.
1870 if (expected_class != nullptr) {
1871 CHECK(method != nullptr);
1872 }
1873 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001874 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001875 }
1876 }
1877 }
1878
Andreas Gampe0793bec2016-12-01 11:37:33 -08001879 const std::vector<gc::space::ImageSpace*>& spaces_;
1880 const PointerSize pointer_size_;
1881
1882 // Cached sections from the spaces.
1883 std::vector<const uint8_t*> space_begin_;
1884 std::vector<const ImageSection*> method_sections_;
1885 std::vector<const ImageSection*> runtime_method_sections_;
1886};
1887
Andreas Gampebe7af222017-07-25 09:57:28 -07001888static void VerifyAppImage(const ImageHeader& header,
1889 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001890 ClassTable* class_table,
1891 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001892 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001893 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1894 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1895 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1896 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1897 << mirror::Class::PrettyClass(klass);
1898 }
1899 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001900 {
1901 // Verify that all direct interfaces of classes in the class table are also resolved.
1902 std::vector<ObjPtr<mirror::Class>> classes;
1903 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1904 REQUIRES_SHARED(Locks::mutator_lock_) {
1905 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1906 classes.push_back(klass);
1907 }
1908 return true;
1909 };
1910 class_table->Visit(verify_direct_interfaces_in_table);
1911 Thread* self = Thread::Current();
1912 for (ObjPtr<mirror::Class> klass : classes) {
1913 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1914 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1915 << klass->PrettyDescriptor() << " iface #" << i;
1916 }
1917 }
1918 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001919}
1920
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001921bool ClassLinker::AddImageSpace(
1922 gc::space::ImageSpace* space,
1923 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001924 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1925 std::string* error_msg) {
1926 DCHECK(out_dex_files != nullptr);
1927 DCHECK(error_msg != nullptr);
1928 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001929 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001930 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001931 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001932 DCHECK(dex_caches_object != nullptr);
1933 Runtime* const runtime = Runtime::Current();
1934 gc::Heap* const heap = runtime->GetHeap();
1935 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001936 // Check that the image is what we are expecting.
1937 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1938 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1939 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1940 image_pointer_size_);
1941 return false;
1942 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001943 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1944 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1945 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1946 expected_image_roots,
1947 header.GetImageRoots()->GetLength());
1948 return false;
1949 }
1950 StackHandleScope<3> hs(self);
1951 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1952 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1953 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1954 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001955 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001956 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1957 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001958 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001959 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001960 *error_msg = StringPrintf("Expected %d class roots but got %d",
1961 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001962 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 return false;
1964 }
1965 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001966 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1967 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1968 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001969 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1970 return false;
1971 }
1972 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001973 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001974 if (oat_file->GetOatHeader().GetDexFileCount() !=
1975 static_cast<uint32_t>(dex_caches->GetLength())) {
1976 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1977 "image";
1978 return false;
1979 }
1980
Alex Lighta9bbc082019-11-14 14:51:41 -08001981 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001982 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001983 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1984 dex_file_location.c_str(),
1985 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001986 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001987 return false;
1988 }
1989
David Srbecky86d6cd52020-12-02 18:13:10 +00001990 LinearAlloc* linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader.Get());
1991 DCHECK(linear_alloc != nullptr);
1992 DCHECK_EQ(linear_alloc == Runtime::Current()->GetLinearAlloc(), !app_image);
1993 {
1994 // Native fields are all null. Initialize them and allocate native memory.
1995 WriterMutexLock mu(self, *Locks::dex_lock_);
1996 dex_cache->InitializeNativeFields(dex_file.get(), linear_alloc);
1997 }
1998 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001999 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002000 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002001 }
2002 out_dex_files->push_back(std::move(dex_file));
2003 }
2004
2005 if (app_image) {
2006 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002007 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002008 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2009 *error_msg = "Unexpected BootClassLoader in app image";
2010 return false;
2011 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002012 }
2013
Orion Hodson5880c772020-07-28 20:12:08 +01002014 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002015 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01002016 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002017 }
2018 }
2019
2020 // Set entry point to interpreter if in InterpretOnly mode.
2021 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002022 // Set image methods' entry point to interpreter.
2023 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2024 if (!method.IsRuntimeMethod()) {
2025 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01002026 if (!method.IsNative() && !method.IsResolutionMethod()) {
2027 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2028 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002029 }
2030 }
2031 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002032 }
2033
Nicolas Geoffray47171752020-08-31 15:03:20 +01002034 if (!runtime->IsAotCompiler()) {
2035 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002036 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01002037 // In the image, the `data` pointer field of the ArtMethod contains the code
2038 // item offset. Change this to the actual pointer to the code item.
2039 if (method.HasCodeItem()) {
2040 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
2041 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01002042 method.SetCodeItem(code_item);
Nicolas Geoffray47171752020-08-31 15:03:20 +01002043 }
2044 // Set image methods' entry point that point to the interpreter bridge to the
2045 // nterp entry point.
2046 if (can_use_nterp) {
2047 ChangeInterpreterBridgeToNterp(&method, this);
2048 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002049 }, space->Begin(), image_pointer_size_);
2050 }
2051
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00002052 if (runtime->IsVerificationSoftFail()) {
2053 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2054 if (!method.IsNative() && method.IsInvokable()) {
2055 method.ClearSkipAccessChecks();
2056 }
2057 }, space->Begin(), image_pointer_size_);
2058 }
2059
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002060 ClassTable* class_table = nullptr;
2061 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002062 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002063 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002064 }
2065 // If we have a class table section, read it and use it for verification in
2066 // UpdateAppImageClassLoadersAndDexCaches.
2067 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002068 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002069 const bool added_class_table = class_table_section.Size() > 0u;
2070 if (added_class_table) {
2071 const uint64_t start_time2 = NanoTime();
2072 size_t read_count = 0;
2073 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2074 /*make copy*/false,
2075 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002076 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002077 }
2078 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002079 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002080
2081 {
2082 ScopedTrace trace("AppImage:UpdateClassLoaders");
2083 // Update class loader and resolved strings. If added_class_table is false, the resolved
2084 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002085 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002086 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002087 // Note: We probably don't need the read barrier unless we copy the app image objects into
2088 // the region space.
2089 ObjPtr<mirror::Class> klass(root.Read());
2090 // Do not update class loader for boot image classes where the app image
2091 // class loader is only the initiating loader but not the defining loader.
2092 // Avoid read barrier since we are comparing against null.
2093 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002094 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002095 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002096 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002097 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002098
Vladimir Marko305c38b2018-02-14 11:50:07 +00002099 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002100 // Every class in the app image has initially SubtypeCheckInfo in the
2101 // Uninitialized state.
2102 //
2103 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2104 // after class initialization is complete. The app image ClassStatus as-is
2105 // are almost all ClassStatus::Initialized, and being in the
2106 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2107 //
2108 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2109 //
2110 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002111 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002112 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2113 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002114 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002115 }
2116 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002117 }
2118 if (!oat_file->GetBssGcRoots().empty()) {
2119 // Insert oat file to class table for visiting .bss GC roots.
2120 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002121 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002122
Mathieu Chartier69731002016-03-02 16:08:31 -08002123 if (added_class_table) {
2124 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2125 class_table->AddClassSet(std::move(temp_set));
2126 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002127
Mathieu Chartier69731002016-03-02 16:08:31 -08002128 if (kIsDebugBuild && app_image) {
2129 // This verification needs to happen after the classes have been added to the class loader.
2130 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002131 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002132 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002133 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002134
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002135 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002136 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002137}
2138
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002139bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002140 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2141 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002142}
2143
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002144void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002145 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2146 // enabling tracing requires the mutator lock, there are no race conditions here.
2147 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002148 Thread* const self = Thread::Current();
2149 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002150 if (kUseReadBarrier) {
2151 // We do not track new roots for CC.
2152 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2153 kVisitRootFlagClearRootLog |
2154 kVisitRootFlagStartLoggingNewRoots |
2155 kVisitRootFlagStopLoggingNewRoots));
2156 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002157 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002158 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2159 // There is 3 GC cases to handle:
2160 // Non moving concurrent:
2161 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002162 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002163 //
2164 // Moving non-concurrent:
2165 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2166 // To prevent missing roots, this case needs to ensure that there is no
2167 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2168 // class which is in the class table.
2169 //
2170 // Moving concurrent:
2171 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2172 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002173 //
2174 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2175 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2176 // these objects.
2177 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002178 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002179 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002180 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002181 for (const ClassLoaderData& data : class_loaders_) {
2182 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2183 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2184 }
2185 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002186 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002187 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002188 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002189 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002190 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002191 // Concurrent moving GC marked new roots through the to-space invariant.
2192 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002193 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002194 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2195 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2196 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2197 if (old_ref != nullptr) {
2198 DCHECK(old_ref->IsClass());
2199 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2200 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2201 // Concurrent moving GC marked new roots through the to-space invariant.
2202 CHECK_EQ(new_ref, old_ref);
2203 }
2204 }
2205 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002206 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002207 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002208 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002209 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002210 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002211 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002212 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002213 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002214 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002215 }
2216 // We deliberately ignore the class roots in the image since we
2217 // handle image roots by using the MS/CMS rescanning of dirty cards.
2218}
2219
Brian Carlstroma663ea52011-08-19 23:33:41 -07002220// Keep in sync with InitCallback. Anything we visit, we need to
2221// reinit references to when reinitializing a ClassLinker from a
2222// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002223void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002224 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002225 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002226 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2227 // unloading if we are marking roots.
2228 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002229}
2230
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002231class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2232 public:
2233 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2234 : visitor_(visitor),
2235 done_(false) {}
2236
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002237 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002238 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002239 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002240 if (!done_ && class_table != nullptr) {
2241 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2242 if (!class_table->Visit(visitor)) {
2243 // If the visitor ClassTable returns false it means that we don't need to continue.
2244 done_ = true;
2245 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002246 }
2247 }
2248
2249 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002250 // Class visitor that limits the class visits from a ClassTable to the classes with
2251 // the provided defining class loader. This filter is used to avoid multiple visits
2252 // of the same class which can be recorded for multiple initiating class loaders.
2253 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2254 public:
2255 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2256 ClassVisitor* visitor)
2257 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2258
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002259 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002260 if (klass->GetClassLoader() != defining_class_loader_) {
2261 return true;
2262 }
2263 return (*visitor_)(klass);
2264 }
2265
Vladimir Marko0984e482019-03-27 16:41:41 +00002266 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002267 ClassVisitor* const visitor_;
2268 };
2269
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002270 ClassVisitor* const visitor_;
2271 // If done is true then we don't need to do any more visiting.
2272 bool done_;
2273};
2274
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002275void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002276 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002277 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2278 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002279 }
2280}
2281
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002282void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002283 Thread* const self = Thread::Current();
2284 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2285 // Not safe to have thread suspension when we are holding a lock.
2286 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002287 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002288 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002289 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002290 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002291 }
2292}
2293
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002294class GetClassesInToVector : public ClassVisitor {
2295 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002296 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002297 classes_.push_back(klass);
2298 return true;
2299 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002300 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002301};
2302
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002303class GetClassInToObjectArray : public ClassVisitor {
2304 public:
2305 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2306 : arr_(arr), index_(0) {}
2307
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002308 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002309 ++index_;
2310 if (index_ <= arr_->GetLength()) {
2311 arr_->Set(index_ - 1, klass);
2312 return true;
2313 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002314 return false;
2315 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002316
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002317 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002318 return index_ <= arr_->GetLength();
2319 }
2320
2321 private:
2322 mirror::ObjectArray<mirror::Class>* const arr_;
2323 int32_t index_;
2324};
2325
2326void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002327 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2328 // is avoiding duplicates.
2329 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002330 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002331 GetClassesInToVector accumulator;
2332 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002333 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002334 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002335 return;
2336 }
2337 }
2338 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002339 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002340 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002341 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002342 // We size the array assuming classes won't be added to the class table during the visit.
2343 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002344 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002345 size_t class_table_size;
2346 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002347 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002348 // Add 100 in case new classes get loaded when we are filling in the object array.
2349 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002350 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002351 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002352 classes.Assign(
2353 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002354 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002355 GetClassInToObjectArray accumulator(classes.Get());
2356 VisitClasses(&accumulator);
2357 if (accumulator.Succeeded()) {
2358 break;
2359 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002360 }
2361 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2362 // If the class table shrank during creation of the clases array we expect null elements. If
2363 // the class table grew then the loop repeats. If classes are created after the loop has
2364 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002365 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002366 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002367 return;
2368 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002369 }
2370 }
2371}
2372
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002373ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002374 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002375 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002376 // CHA unloading analysis is not needed. No negative consequences are expected because
2377 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002378 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002379 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002380 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002381 while (!running_visibly_initialized_callbacks_.empty()) {
2382 std::unique_ptr<VisiblyInitializedCallback> callback(
2383 std::addressof(running_visibly_initialized_callbacks_.front()));
2384 running_visibly_initialized_callbacks_.pop_front();
2385 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002386}
2387
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002388void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002389 Runtime* const runtime = Runtime::Current();
2390 JavaVMExt* const vm = runtime->GetJavaVM();
2391 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002392 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002393 if (runtime->GetJit() != nullptr) {
2394 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2395 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002396 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002397 code_cache->RemoveMethodsIn(self, *data.allocator);
2398 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002399 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002400 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002401 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002402 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002403 // Cleanup references to single implementation ArtMethods that will be deleted.
2404 if (cleanup_cha) {
2405 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2406 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2407 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002408 {
2409 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2410 auto end = critical_native_code_with_clinit_check_.end();
2411 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2412 if (data.allocator->ContainsUnsafe(it->first)) {
2413 it = critical_native_code_with_clinit_check_.erase(it);
2414 } else {
2415 ++it;
2416 }
2417 }
2418 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002419
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002420 delete data.allocator;
2421 delete data.class_table;
2422}
2423
Vladimir Markobcf17522018-06-01 13:14:32 +01002424ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2425 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002426 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002427 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2428 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002429}
2430
David Srbecky86d6cd52020-12-02 18:13:10 +00002431ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002432 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002433 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002434 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002435 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002436 self->AssertPendingOOMException();
2437 return nullptr;
2438 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002439 // Use InternWeak() so that the location String can be collected when the ClassLoader
2440 // with this DexCache is collected.
2441 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002442 if (location == nullptr) {
2443 self->AssertPendingOOMException();
2444 return nullptr;
2445 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002446 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002447 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002448}
2449
Vladimir Markobcf17522018-06-01 13:14:32 +01002450ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2451 const DexFile& dex_file,
2452 LinearAlloc* linear_alloc) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002453 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002454 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002455 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky86d6cd52020-12-02 18:13:10 +00002456 dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002457 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002458 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002459}
2460
Vladimir Marko70e2a762019-07-12 16:49:00 +01002461template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002462ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2463 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002464 uint32_t class_size,
2465 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002466 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002467 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002468 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002469 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2470 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002471 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002472 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002473 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002474 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002475 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002476}
2477
Vladimir Marko70e2a762019-07-12 16:49:00 +01002478template <bool kMovable>
2479ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2480 ObjPtr<mirror::Class> java_lang_Class,
2481 uint32_t class_size) {
2482 mirror::Class::InitializeClassVisitor visitor(class_size);
2483 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2484}
2485
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002486ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002487 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002488}
2489
Vladimir Marko70e2a762019-07-12 16:49:00 +01002490void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2491 ClassRoot primitive_root,
2492 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002493 // We make this class non-movable for the unlikely case where it were to be
2494 // moved by a sticky-bit (minor) collection when using the Generational
2495 // Concurrent Copying (CC) collector, potentially creating a stale reference
2496 // in the `klass_` field of one of its instances allocated in the Large-Object
2497 // Space (LOS) -- see the comment about the dirty card scanning logic in
2498 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002499 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2500 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2501 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2502 DCHECK(component_type->IsPrimitive());
2503 array_class->SetComponentType(component_type);
2504 SetClassRoot(array_root, array_class);
2505}
2506
2507void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2508 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2509 array_class->SetSuperClass(java_lang_Object);
2510 array_class->SetVTable(java_lang_Object->GetVTable());
2511 array_class->SetPrimitiveType(Primitive::kPrimNot);
2512 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2513 array_class->SetClassFlags(component_type->IsPrimitive()
2514 ? mirror::kClassFlagNoReferenceFields
2515 : mirror::kClassFlagObjectArray);
2516 array_class->SetClassLoader(component_type->GetClassLoader());
2517 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2518 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2519 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2520 array_class->SetImt(object_imt, image_pointer_size_);
2521 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2522 // the kAccVerificationAttempted flag is added below, and there are no
2523 // methods that need the kAccSkipAccessChecks flag.
2524 DCHECK_EQ(array_class->NumMethods(), 0u);
2525
2526 // don't need to set new_class->SetObjectSize(..)
2527 // because Object::SizeOf delegates to Array::SizeOf
2528
2529 // All arrays have java/lang/Cloneable and java/io/Serializable as
2530 // interfaces. We need to set that up here, so that stuff like
2531 // "instanceof" works right.
2532
2533 // Use the single, global copies of "interfaces" and "iftable"
2534 // (remember not to free them for arrays).
2535 {
2536 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2537 CHECK(array_iftable != nullptr);
2538 array_class->SetIfTable(array_iftable);
2539 }
2540
2541 // Inherit access flags from the component type.
2542 int access_flags = component_type->GetAccessFlags();
2543 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2544 access_flags &= kAccJavaFlagsMask;
2545 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2546 // and remove "interface".
2547 access_flags |= kAccAbstract | kAccFinal;
2548 access_flags &= ~kAccInterface;
2549 // Arrays are access-checks-clean and preverified.
2550 access_flags |= kAccVerificationAttempted;
2551
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002552 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002553
Vladimir Markobf121912019-06-04 13:49:05 +01002554 // Array classes are fully initialized either during single threaded startup,
2555 // or from a pre-fence visitor, so visibly initialized.
2556 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002557}
2558
2559void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2560 // Do not hold lock on the array class object, the initialization of
2561 // core array classes is done while the process is still single threaded.
2562 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2563 FinishArrayClassSetup(array_class);
2564
2565 std::string temp;
2566 const char* descriptor = array_class->GetDescriptor(&temp);
2567 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2568 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2569 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002570}
2571
Vladimir Markobcf17522018-06-01 13:14:32 +01002572ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002573 Thread* self,
2574 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002575 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002576 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002577}
2578
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002579ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2580 const char* descriptor,
2581 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002582 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002583 if (kIsDebugBuild) {
2584 StackHandleScope<1> hs(self);
2585 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2586 Thread::PoisonObjectPointersIfDebug();
2587 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002588
2589 // For temporary classes we must wait for them to be retired.
2590 if (init_done_ && klass->IsTemp()) {
2591 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002592 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002593 ThrowEarlierClassFailure(klass);
2594 return nullptr;
2595 }
2596 StackHandleScope<1> hs(self);
2597 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2598 ObjectLock<mirror::Class> lock(self, h_class);
2599 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002600 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002601 lock.WaitIgnoringInterrupts();
2602 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002603 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002604 ThrowEarlierClassFailure(h_class.Get());
2605 return nullptr;
2606 }
2607 CHECK(h_class->IsRetired());
2608 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002609 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002610 }
2611
Brian Carlstromaded5f72011-10-07 17:15:04 -07002612 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002613 size_t index = 0;
2614 // Maximum number of yield iterations until we start sleeping.
2615 static const size_t kNumYieldIterations = 1000;
2616 // How long each sleep is in us.
2617 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002618 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002619 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002620 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002621 {
2622 ObjectTryLock<mirror::Class> lock(self, h_class);
2623 // Can not use a monitor wait here since it may block when returning and deadlock if another
2624 // thread has locked klass.
2625 if (lock.Acquired()) {
2626 // Check for circular dependencies between classes, the lock is required for SetStatus.
2627 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2628 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002629 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002630 return nullptr;
2631 }
2632 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002633 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002634 {
2635 // Handle wrapper deals with klass moving.
2636 ScopedThreadSuspension sts(self, kSuspended);
2637 if (index < kNumYieldIterations) {
2638 sched_yield();
2639 } else {
2640 usleep(kSleepDurationUS);
2641 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002642 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002643 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002644 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002645
Vladimir Marko72ab6842017-01-20 19:32:50 +00002646 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002647 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002648 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002649 }
2650 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002651 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002652 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002653 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002654}
2655
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002656using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002657
2658// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002659ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002660 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002661 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002662 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002663 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002664 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002665 return ClassPathEntry(dex_file, dex_class_def);
2666 }
2667 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002668 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002669}
2670
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002671bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2672 Thread* self,
2673 const char* descriptor,
2674 size_t hash,
2675 Handle<mirror::ClassLoader> class_loader,
2676 /*out*/ ObjPtr<mirror::Class>* result) {
2677 ArtField* field =
2678 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2679 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2680 if (raw_shared_libraries == nullptr) {
2681 return true;
2682 }
2683
2684 StackHandleScope<2> hs(self);
2685 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2686 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2687 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002688 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2689 temp_loader.Assign(loader);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002690 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2691 return false; // One of the shared libraries is not supported.
2692 }
2693 if (*result != nullptr) {
2694 return true; // Found the class up the chain.
2695 }
2696 }
2697 return true;
2698}
2699
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002700bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2701 Thread* self,
2702 const char* descriptor,
2703 size_t hash,
2704 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002705 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002706 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002707 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002708 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002709 return true;
2710 }
2711
David Brazdil05909d82018-12-06 16:25:16 +00002712 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002713 // For regular path or dex class loader the search order is:
2714 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002715 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002716 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002717
Calin Juravlecdd49122017-07-05 20:09:53 -07002718 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2719 StackHandleScope<1> hs(self);
2720 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2721 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2722 return false; // One of the parents is not supported.
2723 }
2724 if (*result != nullptr) {
2725 return true; // Found the class up the chain.
2726 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002727
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002728 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2729 return false; // One of the shared library loader is not supported.
2730 }
2731 if (*result != nullptr) {
2732 return true; // Found the class in a shared library.
2733 }
2734
Calin Juravlecdd49122017-07-05 20:09:53 -07002735 // Search the current class loader classpath.
2736 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002737 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002738 }
2739
Calin Juravlecdd49122017-07-05 20:09:53 -07002740 if (IsDelegateLastClassLoader(soa, class_loader)) {
2741 // For delegate last, the search order is:
2742 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002743 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002744 // - class loader dex files
2745 // - parent
2746 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2747 if (*result != nullptr) {
2748 return true; // The class is part of the boot class path.
2749 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002750 if (self->IsExceptionPending()) {
2751 // Pending exception means there was an error other than ClassNotFound that must be returned
2752 // to the caller.
2753 return false;
2754 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002755
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002756 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2757 return false; // One of the shared library loader is not supported.
2758 }
2759 if (*result != nullptr) {
2760 return true; // Found the class in a shared library.
2761 }
2762
Calin Juravlecdd49122017-07-05 20:09:53 -07002763 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2764 if (*result != nullptr) {
2765 return true; // Found the class in the current class loader
2766 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002767 if (self->IsExceptionPending()) {
2768 // Pending exception means there was an error other than ClassNotFound that must be returned
2769 // to the caller.
2770 return false;
2771 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002772
2773 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2774 StackHandleScope<1> hs(self);
2775 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2776 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2777 }
2778
2779 // Unsupported class loader.
2780 *result = nullptr;
2781 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002782}
2783
Andreas Gampe501c3b02019-04-17 21:54:27 +00002784namespace {
2785
2786// Matches exceptions caught in DexFile.defineClass.
2787ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2788 ClassLinker* class_linker)
2789 REQUIRES_SHARED(Locks::mutator_lock_) {
2790 return
2791 // ClassNotFoundException.
2792 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2793 class_linker))
2794 ||
2795 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2796 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2797}
2798
2799// Clear exceptions caught in DexFile.defineClass.
2800ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2801 REQUIRES_SHARED(Locks::mutator_lock_) {
2802 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2803 self->ClearException();
2804 }
2805}
2806
2807} // namespace
2808
Calin Juravle415dc3d2017-06-28 11:03:12 -07002809// Finds the class in the boot class loader.
2810// If the class is found the method returns the resolved class. Otherwise it returns null.
2811ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2812 const char* descriptor,
2813 size_t hash) {
2814 ObjPtr<mirror::Class> result = nullptr;
2815 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2816 if (pair.second != nullptr) {
2817 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2818 if (klass != nullptr) {
2819 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002820 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002821 result = DefineClass(self,
2822 descriptor,
2823 hash,
2824 ScopedNullHandle<mirror::ClassLoader>(),
2825 *pair.first,
2826 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002827 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002828 if (result == nullptr) {
2829 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002830 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002831 }
2832 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002833 return result;
2834}
Andreas Gampef865ea92015-04-13 22:14:19 -07002835
Calin Juravle415dc3d2017-06-28 11:03:12 -07002836ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2837 ScopedObjectAccessAlreadyRunnable& soa,
2838 const char* descriptor,
2839 size_t hash,
2840 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002841 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2842 IsInMemoryDexClassLoader(soa, class_loader) ||
2843 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002844 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002845
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002846 ObjPtr<mirror::Class> ret;
2847 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002848 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002849 if (dex_class_def != nullptr) {
2850 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2851 descriptor,
2852 hash,
2853 class_loader,
2854 *cp_dex_file,
2855 *dex_class_def);
2856 if (klass == nullptr) {
2857 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002858 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002859 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00002860 } else {
2861 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002862 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002863 ret = klass;
2864 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002865 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002866 return true; // Continue with the next DexFile.
2867 };
2868
2869 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2870 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002871}
2872
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002873ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2874 const char* descriptor,
2875 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002876 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002877 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002878 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002879 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002880 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002881 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2882 // for primitive classes that aren't backed by dex files.
2883 return FindPrimitiveClass(descriptor[0]);
2884 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002885 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002886 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002887 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002888 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002889 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002890 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002891 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002892 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002893 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002894 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002895 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002896 return DefineClass(self,
2897 descriptor,
2898 hash,
2899 ScopedNullHandle<mirror::ClassLoader>(),
2900 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002901 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002902 } else {
2903 // The boot class loader is searched ahead of the application class loader, failures are
2904 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2905 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002906 ObjPtr<mirror::Throwable> pre_allocated =
2907 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002908 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002909 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002910 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002911 }
2912 ObjPtr<mirror::Class> result_ptr;
2913 bool descriptor_equals;
2914 if (descriptor[0] == '[') {
2915 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2916 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2917 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2918 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002919 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002920 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002921 bool known_hierarchy =
2922 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2923 if (result_ptr != nullptr) {
2924 // The chain was understood and we found the class. We still need to add the class to
2925 // the class table to protect from racy programs that can try and redefine the path list
2926 // which would change the Class<?> returned for subsequent evaluation of const-class.
2927 DCHECK(known_hierarchy);
2928 DCHECK(result_ptr->DescriptorEquals(descriptor));
2929 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002930 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002931 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002932 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2933 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002934 //
2935 // If the chain was understood but we did not find the class, let the Java-side
2936 // rediscover all this and throw the exception with the right stack trace. Note that
2937 // the Java-side could still succeed for racy programs if another thread is actively
2938 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002939
Alex Light185a4612018-10-04 15:54:25 -07002940 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002941 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002942 // Oops, we can't call into java so we can't run actual class-loader code.
2943 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002944 ObjPtr<mirror::Throwable> pre_allocated =
2945 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2946 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002947 return nullptr;
2948 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002949
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002950 // Inlined DescriptorToDot(descriptor) with extra validation.
2951 //
2952 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2953 // the DescriptorEquals() check below and give a confusing error message. For example,
2954 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2955 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2956 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2957 size_t descriptor_length = strlen(descriptor);
2958 if (UNLIKELY(descriptor[0] != 'L') ||
2959 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2960 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2961 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2962 return nullptr;
2963 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002964
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002965 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2966 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002967 if (known_hierarchy &&
2968 fast_class_not_found_exceptions_ &&
2969 !Runtime::Current()->IsJavaDebuggable()) {
2970 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2971 // debuggable, optimize this path by throwing directly here without going back to Java
2972 // language. This reduces how many ClassNotFoundExceptions happen.
2973 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2974 "%s",
2975 class_name_string.c_str());
2976 } else {
2977 ScopedLocalRef<jobject> class_loader_object(
2978 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2979 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2980 {
2981 ScopedThreadStateChange tsc(self, kNative);
2982 ScopedLocalRef<jobject> class_name_object(
2983 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2984 if (class_name_object.get() == nullptr) {
2985 DCHECK(self->IsExceptionPending()); // OOME.
2986 return nullptr;
2987 }
2988 CHECK(class_loader_object.get() != nullptr);
2989 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2990 WellKnownClasses::java_lang_ClassLoader_loadClass,
2991 class_name_object.get()));
2992 }
2993 if (result.get() == nullptr && !self->IsExceptionPending()) {
2994 // broken loader - throw NPE to be compatible with Dalvik
2995 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2996 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002997 return nullptr;
2998 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002999 result_ptr = soa.Decode<mirror::Class>(result.get());
3000 // Check the name of the returned class.
3001 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00003002 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00003003 } else {
3004 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003005 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003006 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003007
3008 if (self->IsExceptionPending()) {
3009 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3010 // However, to comply with the RI behavior, first check if another thread succeeded.
3011 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3012 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3013 self->ClearException();
3014 return EnsureResolved(self, descriptor, result_ptr);
3015 }
3016 return nullptr;
3017 }
3018
3019 // Try to insert the class to the class table, checking for mismatch.
3020 ObjPtr<mirror::Class> old;
3021 {
3022 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3023 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3024 old = class_table->Lookup(descriptor, hash);
3025 if (old == nullptr) {
3026 old = result_ptr; // For the comparison below, after releasing the lock.
3027 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003028 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003029 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003030 } // else throw below, after releasing the lock.
3031 }
3032 }
3033 if (UNLIKELY(old != result_ptr)) {
3034 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3035 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003036 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003037 const char* loader_class_name =
3038 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3039 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3040 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3041 << DescriptorToDot(descriptor) << "\").";
3042 return EnsureResolved(self, descriptor, old);
3043 }
3044 if (UNLIKELY(!descriptor_equals)) {
3045 std::string result_storage;
3046 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3047 std::string loader_storage;
3048 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3049 ThrowNoClassDefFoundError(
3050 "Initiating class loader of type %s returned class %s instead of %s.",
3051 DescriptorToDot(loader_class_name).c_str(),
3052 DescriptorToDot(result_name).c_str(),
3053 DescriptorToDot(descriptor).c_str());
3054 return nullptr;
3055 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003056 // Success.
3057 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003058}
3059
Alex Light270db1c2019-12-03 12:20:01 +00003060// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3061// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3062// like pausing class definition.
3063struct ScopedDefiningClass {
3064 public:
3065 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3066 : self_(self), returned_(false) {
3067 Locks::mutator_lock_->AssertSharedHeld(self_);
3068 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3069 self_->IncrDefineClassCount();
3070 }
3071 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3072 Locks::mutator_lock_->AssertSharedHeld(self_);
3073 CHECK(returned_);
3074 }
3075
3076 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3077 REQUIRES_SHARED(Locks::mutator_lock_) {
3078 CHECK(!returned_);
3079 self_->DecrDefineClassCount();
3080 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3081 Thread::PoisonObjectPointersIfDebug();
3082 returned_ = true;
3083 return h_klass.Get();
3084 }
3085
3086 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3087 REQUIRES_SHARED(Locks::mutator_lock_) {
3088 StackHandleScope<1> hs(self_);
3089 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3090 return Finish(h_klass);
3091 }
3092
3093 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3094 REQUIRES_SHARED(Locks::mutator_lock_) {
3095 ScopedNullHandle<mirror::Class> snh;
3096 return Finish(snh);
3097 }
3098
3099 private:
3100 Thread* self_;
3101 bool returned_;
3102};
3103
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003104ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3105 const char* descriptor,
3106 size_t hash,
3107 Handle<mirror::ClassLoader> class_loader,
3108 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003109 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003110 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003111 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003112 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003113
Brian Carlstromaded5f72011-10-07 17:15:04 -07003114 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003115 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003116 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003117 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003118 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003119 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003120 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003121 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003122 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003123 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003124 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003125 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003126 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003127 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003128 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003129 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003130 }
3131
Vladimir Markob9c29f62019-03-20 14:22:51 +00003132 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3133 // some runtime modules. Prevent definition of classes in app class loader that could clash
3134 // with these modules as these classes could be resolved differently during execution.
3135 if (class_loader != nullptr &&
3136 Runtime::Current()->IsAotCompiler() &&
Vladimir Markod1f73512020-04-02 10:50:35 +01003137 IsUpdatableBootClassPathDescriptor(descriptor)) {
Vladimir Markob9c29f62019-03-20 14:22:51 +00003138 ObjPtr<mirror::Throwable> pre_allocated =
3139 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3140 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003141 return sdc.Finish(nullptr);
Vladimir Markob9c29f62019-03-20 14:22:51 +00003142 }
3143
Calin Juravle33787682019-07-26 14:27:18 -07003144 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3145 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3146 // public class path then we prevent the definition of the class.
3147 //
3148 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3149 // classpath is not checked.
3150 if (class_loader == nullptr &&
3151 Runtime::Current()->IsAotCompiler() &&
3152 DenyAccessBasedOnPublicSdk(descriptor)) {
3153 ObjPtr<mirror::Throwable> pre_allocated =
3154 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3155 self->SetException(pre_allocated);
3156 return sdc.Finish(nullptr);
3157 }
3158
Alex Lighte9f61032018-09-24 16:04:51 -07003159 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3160 // code to be executed. We put it up here so we can avoid all the allocations associated with
3161 // creating the class. This can happen with (eg) jit threads.
3162 if (!self->CanLoadClasses()) {
3163 // Make sure we don't try to load anything, potentially causing an infinite loop.
3164 ObjPtr<mirror::Throwable> pre_allocated =
3165 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3166 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003167 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003168 }
3169
Andreas Gampefa4333d2017-02-14 11:10:34 -08003170 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003171 // Allocate a class with the status of not ready.
3172 // Interface object should get the right size here. Regular class will
3173 // figure out the right size later and be replaced with one of the right
3174 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003175 if (CanAllocClass()) {
3176 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3177 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003178 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003179 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003180 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003181 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003182 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003183 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003184 }
Alex Lightb0f11922017-01-23 14:25:17 -08003185 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3186 // nothing.
3187 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003188 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003189 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3190 // will only be called once.
3191 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3192 klass,
3193 class_loader,
3194 dex_file,
3195 dex_class_def,
3196 &new_dex_file,
3197 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003198 // Check to see if an exception happened during runtime callbacks. Return if so.
3199 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003200 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003201 }
Alex Lightb0f11922017-01-23 14:25:17 -08003202 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003203 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003204 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003205 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003206 }
3207 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003208 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003209
Jeff Hao848f70a2014-01-15 13:49:50 -08003210 // Mark the string class by setting its access flag.
3211 if (UNLIKELY(!init_done_)) {
3212 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3213 klass->SetStringClass();
3214 }
3215 }
3216
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003217 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003218 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003219 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003220 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003221
Mathieu Chartier590fee92013-09-13 13:46:47 -07003222 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003223 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003224 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003225 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3226 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003227 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003228 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003229
Mathieu Chartierc7853442015-03-27 14:35:38 -07003230 // Load the fields and other things after we are inserted in the table. This is so that we don't
3231 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3232 // other reason is that the field roots are only visited from the class table. So we need to be
3233 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003234 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003235 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003236 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003237 // An exception occured during load, set status to erroneous while holding klass' lock in case
3238 // notification is necessary.
3239 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003240 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003241 }
Alex Light270db1c2019-12-03 12:20:01 +00003242 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003243 }
3244
Brian Carlstromaded5f72011-10-07 17:15:04 -07003245 // Finish loading (if necessary) by finding parents
3246 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003247 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003248 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003249 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003250 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003251 }
Alex Light270db1c2019-12-03 12:20:01 +00003252 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003253 }
3254 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003255
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003256 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003257 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003258 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003259
Brian Carlstromaded5f72011-10-07 17:15:04 -07003260 // Link the class (if necessary)
3261 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003262 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003263 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003264
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003265 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003266 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003267 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003268 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003269 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003270 }
Alex Light270db1c2019-12-03 12:20:01 +00003271 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003272 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003273 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003274 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003275 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003276
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003277 // Instrumentation may have updated entrypoints for all methods of all
3278 // classes. However it could not update methods of this class while we
3279 // were loading it. Now the class is resolved, we can update entrypoints
3280 // as required by instrumentation.
3281 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3282 // We must be in the kRunnable state to prevent instrumentation from
3283 // suspending all threads to update entrypoints while we are doing it
3284 // for this class.
3285 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003286 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003287 }
3288
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003289 /*
3290 * We send CLASS_PREPARE events to the debugger from here. The
3291 * definition of "preparation" is creating the static fields for a
3292 * class and initializing them to the standard default values, but not
3293 * executing any code (that comes later, during "initialization").
3294 *
3295 * We did the static preparation in LinkClass.
3296 *
3297 * The class has been prepared and resolved but possibly not yet verified
3298 * at this point.
3299 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003300 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003301
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003302 // Notify native debugger of the new class and its layout.
3303 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3304
Alex Light270db1c2019-12-03 12:20:01 +00003305 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003306}
3307
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003308uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003309 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003310 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003311 size_t num_8 = 0;
3312 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003313 size_t num_32 = 0;
3314 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003315 ClassAccessor accessor(dex_file, dex_class_def);
3316 // We allow duplicate definitions of the same field in a class_data_item
3317 // but ignore the repeated indexes here, b/21868015.
3318 uint32_t last_field_idx = dex::kDexNoIndex;
3319 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3320 uint32_t field_idx = field.GetIndex();
3321 // Ordering enforced by DexFileVerifier.
3322 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3323 if (UNLIKELY(field_idx == last_field_idx)) {
3324 continue;
3325 }
3326 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003327 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003328 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3329 char c = descriptor[0];
3330 switch (c) {
3331 case 'L':
3332 case '[':
3333 num_ref++;
3334 break;
3335 case 'J':
3336 case 'D':
3337 num_64++;
3338 break;
3339 case 'I':
3340 case 'F':
3341 num_32++;
3342 break;
3343 case 'S':
3344 case 'C':
3345 num_16++;
3346 break;
3347 case 'B':
3348 case 'Z':
3349 num_8++;
3350 break;
3351 default:
3352 LOG(FATAL) << "Unknown descriptor: " << c;
3353 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003354 }
3355 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003356 return mirror::Class::ComputeClassSize(false,
3357 0,
3358 num_8,
3359 num_16,
3360 num_32,
3361 num_64,
3362 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003363 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003364}
3365
Alex Lightfc49fec2018-01-16 22:28:36 +00003366// Special case to get oat code without overwriting a trampoline.
3367const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003368 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003369 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003370 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003371 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003372 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003373 if (code != nullptr) {
3374 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003375 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003376
3377 jit::Jit* jit = Runtime::Current()->GetJit();
3378 if (jit != nullptr) {
3379 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3380 if (code != nullptr) {
3381 return code;
3382 }
3383 }
3384
Alex Lightfc49fec2018-01-16 22:28:36 +00003385 if (method->IsNative()) {
3386 // No code and native? Use generic trampoline.
3387 return GetQuickGenericJniStub();
3388 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003389
3390 if (interpreter::CanRuntimeUseNterp() && interpreter::CanMethodUseNterp(method)) {
3391 return interpreter::GetNterpEntryPoint();
3392 }
3393
Alex Lightfc49fec2018-01-16 22:28:36 +00003394 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003395}
3396
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003397bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003398 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003399 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3400 return false;
3401 }
3402
Elliott Hughes956af0f2014-12-11 14:34:28 -08003403 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003404 return true;
3405 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003406
3407 Runtime* runtime = Runtime::Current();
3408 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3409 if (instr->InterpretOnly()) {
3410 return true;
3411 }
3412
3413 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3414 // Doing this check avoids doing compiled/interpreter transitions.
3415 return true;
3416 }
3417
Alex Lightfc588092020-01-23 15:39:08 -08003418 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003419 // Force the use of interpreter when it is required by the debugger.
3420 return true;
3421 }
3422
Alex Light8f34aba2017-10-09 13:46:32 -07003423 if (Thread::Current()->IsAsyncExceptionPending()) {
3424 // Force use of interpreter to handle async-exceptions
3425 return true;
3426 }
3427
Alex Light2d441b12018-06-08 15:33:21 -07003428 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3429 const void* instr_target = instr->GetCodeForInvoke(method);
3430 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3431 return ShouldUseInterpreterEntrypoint(method, instr_target);
3432 }
3433
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003434 if (runtime->IsJavaDebuggable()) {
3435 // For simplicity, we ignore precompiled code and go to the interpreter
3436 // assuming we don't already have jitted code.
3437 // We could look at the oat file where `quick_code` is being defined,
3438 // and check whether it's been compiled debuggable, but we decided to
3439 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003440 jit::Jit* jit = Runtime::Current()->GetJit();
3441 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3442 }
3443
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003444 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003445 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003446 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003447 // since we want to JIT it (at first use) with extra stackmaps for native
3448 // debugging. We keep however all AOT code from the boot image,
3449 // since the JIT-at-first-use is blocking and would result in non-negligible
3450 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003451 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003452 }
3453
3454 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003455}
3456
Vladimir Marko86c87522020-05-11 16:55:55 +01003457void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003458 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003459 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003460 size_t num_direct_methods = klass->NumDirectMethods();
3461 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003462 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003463 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003464 if (UNLIKELY(klass->IsProxyClass())) {
3465 return;
3466 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003467 PointerSize pointer_size = image_pointer_size_;
3468 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3469 klass->GetDirectMethods(pointer_size).end(),
3470 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3471 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3472 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3473 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3474 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3475 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3476 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3477 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3478 lb->first->SetEntryPointFromJni(lb->second);
3479 lb = critical_native_code_with_clinit_check_.erase(lb);
3480 }
3481 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003482 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003483 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003484 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003485 return; // OAT file unavailable.
3486 }
Ian Rogers19846512012-02-24 11:42:47 -08003487 }
Alex Light64ad14d2014-08-19 14:23:13 -07003488
Mathieu Chartierf8322842014-05-16 10:59:25 -07003489 const DexFile& dex_file = klass->GetDexFile();
Ian Rogers97b52f82014-08-14 11:34:07 -07003490 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003491 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3492 klass->GetDexClassDefIndex(),
3493 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003494 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003495 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3496 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003497 if (!method->IsStatic()) {
3498 // Only update static methods.
3499 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003500 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003501 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003502
3503 // In order:
3504 // 1) Check if we have AOT Code.
3505 // 2) Check if we have JIT Code.
3506 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003507 if (has_oat_class) {
3508 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003509 quick_code = oat_method.GetQuickCode();
3510 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003511
Vladimir Markocce414f2019-10-07 08:51:33 +01003512 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003513 if (quick_code == nullptr && jit != nullptr) {
3514 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003515 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003516
3517 if (quick_code == nullptr &&
3518 interpreter::CanRuntimeUseNterp() &&
3519 interpreter::CanMethodUseNterp(method)) {
3520 quick_code = interpreter::GetNterpEntryPoint();
3521 }
3522
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003523 // Check whether the method is native, in which case it's generic JNI.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003524 if (quick_code == nullptr && method->IsNative()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003525 quick_code = GetQuickGenericJniStub();
3526 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003527 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003528 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3529 // If we have the trampoline or the bridge already, no need to update.
3530 // This saves in not dirtying boot image memory.
3531 continue;
3532 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003533 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003534 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003535 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003536 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003537 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003538 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003539}
3540
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003541// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3542// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003543inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3544 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003545 DCHECK(method != nullptr);
3546 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003547 method->SetEntryPointFromQuickCompiledCodePtrSize(
3548 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3549 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003550}
3551
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003552static void LinkCode(ClassLinker* class_linker,
3553 ArtMethod* method,
3554 const OatFile::OatClass* oat_class,
3555 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003556 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003557 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003558 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003559 // The following code only applies to a non-compiler runtime.
3560 return;
3561 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003562
Ian Rogers62d6c772013-02-27 08:32:07 -08003563 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003564 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003565
Alex Light9139e002015-10-09 15:59:48 -07003566 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003567 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003568 return;
3569 }
Ian Rogers19846512012-02-24 11:42:47 -08003570
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003571 const void* quick_code = nullptr;
3572 if (oat_class != nullptr) {
3573 // Every kind of method should at least get an invoke stub from the oat_method.
3574 // non-abstract methods also get their code pointers.
3575 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3576 quick_code = oat_method.GetQuickCode();
3577 }
3578
3579 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3580
3581 // Note: this mimics the logic in image_writer.cc that installs the resolution
3582 // stub only if we have compiled code and the method needs a class initialization
3583 // check.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003584 if (quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003585 method->SetEntryPointFromQuickCompiledCode(
3586 method->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge());
3587 } else if (enter_interpreter) {
3588 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003589 } else if (NeedsClinitCheckBeforeCall(method)) {
3590 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3591 // If we do have code but the method needs a class initialization check before calling
3592 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003593 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3594 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003595 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003596 } else {
3597 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003598 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003599
Ian Rogers62d6c772013-02-27 08:32:07 -08003600 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003601 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3602 // as the extra processing for @CriticalNative is not needed yet.
3603 method->SetEntryPointFromJni(
3604 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Andreas Gampe90546832014-03-12 18:07:19 -07003605
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003606 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003607 // We have a native method here without code. Then it should have the generic JNI
3608 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003609 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003610 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003611 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003612 }
3613}
3614
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003615void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003616 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003617 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003618 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003619 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003620 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003621 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003622 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003623 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003624
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003625 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003626 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003627 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003628 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003629 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003630 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003631 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003632
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003633 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003634 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003635}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003636
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003637LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3638 LinearAlloc* allocator,
3639 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003640 if (length == 0) {
3641 return nullptr;
3642 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003643 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3644 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3645 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003646 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003647 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003648 CHECK(ret != nullptr);
3649 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3650 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003651}
3652
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003653LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3654 LinearAlloc* allocator,
3655 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003656 if (length == 0) {
3657 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003658 }
Vladimir Marko14632852015-08-17 12:07:23 +01003659 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3660 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003661 const size_t storage_size =
3662 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003663 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003664 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003665 CHECK(ret != nullptr);
3666 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003667 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003668 }
3669 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003670}
3671
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003672LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003673 if (class_loader == nullptr) {
3674 return Runtime::Current()->GetLinearAlloc();
3675 }
3676 LinearAlloc* allocator = class_loader->GetAllocator();
3677 DCHECK(allocator != nullptr);
3678 return allocator;
3679}
3680
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003681LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003682 if (class_loader == nullptr) {
3683 return Runtime::Current()->GetLinearAlloc();
3684 }
3685 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3686 LinearAlloc* allocator = class_loader->GetAllocator();
3687 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003688 RegisterClassLoader(class_loader);
3689 allocator = class_loader->GetAllocator();
3690 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003691 }
3692 return allocator;
3693}
3694
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003695void ClassLinker::LoadClass(Thread* self,
3696 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003697 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003698 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003699 ClassAccessor accessor(dex_file,
3700 dex_class_def,
3701 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003702 if (!accessor.HasClassData()) {
3703 return;
3704 }
3705 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003706 {
3707 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3708 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003709 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003710 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003711 // We allow duplicate definitions of the same field in a class_data_item
3712 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003713 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003714 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3715 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003716 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003717 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3718 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003719 accessor.NumInstanceFields());
3720 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003721 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003722 uint32_t last_static_field_idx = 0u;
3723 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003724
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003725 // Methods
3726 bool has_oat_class = false;
3727 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3728 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3729 : OatFile::OatClass::Invalid();
3730 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3731 klass->SetMethodsPtr(
3732 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3733 accessor.NumDirectMethods(),
3734 accessor.NumVirtualMethods());
3735 size_t class_def_method_index = 0;
3736 uint32_t last_dex_method_index = dex::kDexNoIndex;
3737 size_t last_class_def_method_index = 0;
3738
3739 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3740 // methods needs to decode all of the fields.
3741 accessor.VisitFieldsAndMethods([&](
3742 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3743 uint32_t field_idx = field.GetIndex();
3744 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3745 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3746 LoadField(field, klass, &sfields->At(num_sfields));
3747 ++num_sfields;
3748 last_static_field_idx = field_idx;
3749 }
3750 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3751 uint32_t field_idx = field.GetIndex();
3752 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3753 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3754 LoadField(field, klass, &ifields->At(num_ifields));
3755 ++num_ifields;
3756 last_instance_field_idx = field_idx;
3757 }
3758 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3759 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3760 image_pointer_size_);
3761 LoadMethod(dex_file, method, klass, art_method);
3762 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3763 uint32_t it_method_index = method.GetIndex();
3764 if (last_dex_method_index == it_method_index) {
3765 // duplicate case
3766 art_method->SetMethodIndex(last_class_def_method_index);
3767 } else {
3768 art_method->SetMethodIndex(class_def_method_index);
3769 last_dex_method_index = it_method_index;
3770 last_class_def_method_index = class_def_method_index;
3771 }
3772 ++class_def_method_index;
3773 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3774 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3775 class_def_method_index - accessor.NumDirectMethods(),
3776 image_pointer_size_);
3777 LoadMethod(dex_file, method, klass, art_method);
3778 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3779 ++class_def_method_index;
3780 });
3781
3782 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003783 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003784 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3785 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3786 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003787 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3788 if (sfields != nullptr) {
3789 sfields->SetSize(num_sfields);
3790 }
3791 if (ifields != nullptr) {
3792 ifields->SetSize(num_ifields);
3793 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003794 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003795 // Set the field arrays.
3796 klass->SetSFieldsPtr(sfields);
3797 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003798 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003799 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003800 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003801 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003802 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003803 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003804}
3805
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003806void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003807 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003808 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003809 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003810 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003811 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003812
David Brazdil85865692018-10-30 17:26:20 +00003813 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3814 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003815}
3816
Mathieu Chartier268764d2016-09-13 12:09:38 -07003817void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003818 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003819 Handle<mirror::Class> klass,
3820 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003821 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003822 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003823 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003824
Mathieu Chartier268764d2016-09-13 12:09:38 -07003825 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003826 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003827 dst->SetDeclaringClass(klass.Get());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003828
David Brazdil85865692018-10-30 17:26:20 +00003829 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3830 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003831
Ian Rogersdfb325e2013-10-30 01:00:44 -07003832 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003833 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003834 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3835 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003836 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003837 klass->SetFinalizable();
3838 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003839 std::string temp;
3840 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003841 // The Enum class declares a "final" finalize() method to prevent subclasses from
3842 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3843 // subclasses, so we exclude it here.
3844 // We also want to avoid setting the flag on Object, where we know that finalize() is
3845 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003846 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3847 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003848 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003849 }
3850 }
3851 }
3852 } else if (method_name[0] == '<') {
3853 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003854 bool is_init = (strcmp("<init>", method_name) == 0);
3855 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003856 if (UNLIKELY(!is_init && !is_clinit)) {
3857 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3858 } else {
3859 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3860 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003861 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003862 access_flags |= kAccConstructor;
3863 }
3864 }
3865 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003866 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3867 // Check if the native method is annotated with @FastNative or @CriticalNative.
3868 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3869 dex_file, dst->GetClassDef(), dex_method_idx);
3870 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003871 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003872 // Must be done after SetAccessFlags since IsAbstract depends on it.
3873 if (klass->IsInterface() && dst->IsAbstract()) {
3874 dst->CalculateAndSetImtIndex();
3875 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01003876 if (dst->HasCodeItem()) {
3877 DCHECK_NE(method.GetCodeItemOffset(), 0u);
3878 if (Runtime::Current()->IsAotCompiler()) {
3879 dst->SetDataPtrSize(reinterpret_cast32<void*>(method.GetCodeItemOffset()), image_pointer_size_);
3880 } else {
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01003881 dst->SetCodeItem(dst->GetDexFile()->GetCodeItem(method.GetCodeItemOffset()));
Nicolas Geoffray47171752020-08-31 15:03:20 +01003882 }
3883 } else {
3884 dst->SetDataPtrSize(nullptr, image_pointer_size_);
3885 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3886 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003887}
3888
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003889void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003890 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003891 self,
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003892 *dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003893 Runtime::Current()->GetLinearAlloc());
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003894 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003895 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003896}
3897
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003898void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003899 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003900 CHECK(dex_file != nullptr);
3901 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3902 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003903 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003904 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003905}
3906
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003907void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003908 ObjPtr<mirror::DexCache> dex_cache,
3909 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003910 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003911 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003912 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003913 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003914 // For app images, the dex cache location may be a suffix of the dex file location since the
3915 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003916 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3917 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003918 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3919 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003920 // The following paths checks don't work on preopt when using boot dex files, where the dex
3921 // cache location is the one on device, and the dex_file's location is the one on host.
3922 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3923 CHECK_GE(dex_file_location.length(), dex_cache_length)
3924 << dex_cache_location << " " << dex_file.GetLocation();
3925 const std::string dex_file_suffix = dex_file_location.substr(
3926 dex_file_location.length() - dex_cache_length,
3927 dex_cache_length);
3928 // Example dex_cache location is SettingsProvider.apk and
3929 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3930 CHECK_EQ(dex_cache_location, dex_file_suffix);
3931 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003932 const OatFile* oat_file =
3933 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003934 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3935 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3936 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3937 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003938 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003939 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3940 DexCacheData data = *it;
3941 if (self->IsJWeakCleared(data.weak_root)) {
3942 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003943 it = dex_caches_.erase(it);
3944 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003945 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003946 it->dex_file->GetOatDexFile() != nullptr &&
3947 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003948 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003949 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003950 ++it;
3951 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003952 }
Vladimir Markob066d432018-01-03 13:14:37 +00003953 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003954 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003955 }
David Brazdila5c3a802019-03-08 14:59:41 +00003956 // Let hiddenapi assign a domain to the newly registered dex file.
3957 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3958
Vladimir Markocd556b02017-02-03 11:47:34 +00003959 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003960 DexCacheData data;
3961 data.weak_root = dex_cache_jweak;
3962 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003963 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003964 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003965 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003966 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3967 // path dex caches without an image.
3968 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003969 // Make sure that the dex cache holds the classloader live.
3970 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003971 if (class_loader != nullptr) {
3972 // Since we added a strong root to the class table, do the write barrier as required for
3973 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003974 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003975 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003976 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003977}
3978
Alex Light725da8f2020-02-19 14:46:33 -08003979ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3980 return data != nullptr
3981 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003982 : nullptr;
3983}
3984
Alex Light725da8f2020-02-19 14:46:33 -08003985bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003986 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003987 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003988 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003989 CHECK(data != nullptr);
3990 DCHECK_EQ(dex_cache->GetDexFile(), data->dex_file);
3991 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003992}
3993
Alex Light07f06212017-06-01 14:01:43 -07003994void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3995 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003996 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003997 Thread* self = Thread::Current();
3998 StackHandleScope<2> hs(self);
3999 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
4000 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
4001 const DexFile* dex_file = dex_cache->GetDexFile();
4002 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
4003 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08004004 ReaderMutexLock mu(self, *Locks::dex_lock_);
4005 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
4006 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07004007 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
4008 << "been registered on dex file " << dex_file->GetLocation();
4009 }
4010 ClassTable* table;
4011 {
4012 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4013 table = InsertClassTableForClassLoader(h_class_loader.Get());
4014 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004015 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4016 // a thread holding the dex lock and blocking on a condition variable regarding
4017 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004018 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07004019 WriterMutexLock mu(self, *Locks::dex_lock_);
4020 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
4021 table->InsertStrongRoot(h_dex_cache.Get());
4022 if (h_class_loader.Get() != nullptr) {
4023 // Since we added a strong root to the class table, do the write barrier as required for
4024 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004025 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07004026 }
4027}
4028
Alex Lightde7f8782020-02-24 10:14:22 -08004029static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
4030 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08004031 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08004032 "Attempt to register dex file %s with multiple class loaders",
4033 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08004034}
4035
Vladimir Markocd556b02017-02-03 11:47:34 +00004036ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
4037 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07004038 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08004039 ObjPtr<mirror::DexCache> old_dex_cache;
4040 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004041 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004042 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004043 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4044 old_dex_cache = DecodeDexCacheLocked(self, old_data);
4045 if (old_dex_cache != nullptr) {
4046 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
4047 return old_dex_cache;
4048 } else {
4049 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
4050 // be thrown when it's safe to do so to simplify this.
4051 registered_with_another_class_loader = true;
4052 }
4053 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004054 }
Alex Light725da8f2020-02-19 14:46:33 -08004055 // We need to have released the dex_lock_ to allocate safely.
4056 if (registered_with_another_class_loader) {
4057 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4058 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07004059 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004060 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004061 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4062 DCHECK(linear_alloc != nullptr);
4063 ClassTable* table;
4064 {
4065 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4066 table = InsertClassTableForClassLoader(class_loader);
4067 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004068 // Don't alloc while holding the lock, since allocation may need to
4069 // suspend all threads and another thread may need the dex_lock_ to
4070 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004071 StackHandleScope<3> hs(self);
4072 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00004073 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004074 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004075 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4076 // a thread holding the dex lock and blocking on a condition variable regarding
4077 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004078 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004079 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004080 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4081 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004082 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
David Srbecky86d6cd52020-12-02 18:13:10 +00004083 // Do InitializeNativeFields while holding dex lock to make sure two threads don't call it
4084 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
4085 // DCHECK that the arrays are null.
4086 h_dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Vladimir Markocd556b02017-02-03 11:47:34 +00004087 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004088 }
Alex Light725da8f2020-02-19 14:46:33 -08004089 if (old_dex_cache != nullptr) {
4090 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4091 // If this thread encountered OOME, ignore it.
4092 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
4093 self->ClearException();
4094 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
4095 // dex_lock_.
4096 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
4097 return old_dex_cache;
4098 } else {
4099 registered_with_another_class_loader = true;
4100 }
4101 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004102 }
Alex Light725da8f2020-02-19 14:46:33 -08004103 if (registered_with_another_class_loader) {
4104 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4105 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004106 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004107 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004108 self->AssertPendingOOMException();
4109 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004110 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004111 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004112 if (h_class_loader.Get() != nullptr) {
4113 // Since we added a strong root to the class table, do the write barrier as required for
4114 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004115 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004116 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004117 PaletteHooks* hooks = nullptr;
4118 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
4119 if (PaletteGetHooks(&hooks) == PaletteStatus::kOkay) {
4120 hooks->NotifyDexFileLoaded(dex_file.GetLocation().c_str());
4121 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004122 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004123}
4124
Vladimir Markocd556b02017-02-03 11:47:34 +00004125bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004126 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004127 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004128}
4129
Vladimir Markocd556b02017-02-03 11:47:34 +00004130ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4131 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004132 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4133 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004134 if (dex_cache != nullptr) {
4135 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004136 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004137 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004138 for (const DexCacheData& data : dex_caches_) {
Alex Light725da8f2020-02-19 14:46:33 -08004139 if (DecodeDexCacheLocked(self, &data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004140 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004141 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004142 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004143 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
Alex Light725da8f2020-02-19 14:46:33 -08004144 << " " << &dex_file << " " << dex_cache_data->dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004145 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004146}
4147
Vladimir Markocd556b02017-02-03 11:47:34 +00004148ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4149 const DexFile* dex_file = dex_cache->GetDexFile();
4150 DCHECK(dex_file != nullptr);
4151 ReaderMutexLock mu(self, *Locks::dex_lock_);
4152 // Search assuming unique-ness of dex file.
4153 for (const DexCacheData& data : dex_caches_) {
4154 // Avoid decoding (and read barriers) other unrelated dex caches.
4155 if (data.dex_file == dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004156 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004157 if (registered_dex_cache != nullptr) {
4158 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4159 return data.class_table;
4160 }
4161 }
4162 }
4163 return nullptr;
4164}
4165
Alex Light725da8f2020-02-19 14:46:33 -08004166const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004167 // Search assuming unique-ness of dex file.
4168 for (const DexCacheData& data : dex_caches_) {
4169 // Avoid decoding (and read barriers) other unrelated dex caches.
4170 if (data.dex_file == &dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004171 return &data;
Vladimir Markocd556b02017-02-03 11:47:34 +00004172 }
4173 }
Alex Light725da8f2020-02-19 14:46:33 -08004174 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004175}
4176
Vladimir Marko70e2a762019-07-12 16:49:00 +01004177void ClassLinker::CreatePrimitiveClass(Thread* self,
4178 Primitive::Type type,
4179 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004180 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004181 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004182 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4183 // Do not hold lock on the primitive class object, the initialization of
4184 // primitive classes is done while the process is still single threaded.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004185 primitive_class->SetAccessFlagsDuringLinking(
Vladimir Marko70e2a762019-07-12 16:49:00 +01004186 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4187 primitive_class->SetPrimitiveType(type);
4188 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4189 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4190 // the kAccVerificationAttempted flag was added above, and there are no
4191 // methods that need the kAccSkipAccessChecks flag.
4192 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004193 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4194 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004195 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004196 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004197 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004198 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004199 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004200 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004201}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004202
Vladimir Marko02610552018-06-04 14:38:00 +01004203inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4204 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4205}
4206
Brian Carlstrombe977852011-07-19 14:54:54 -07004207// Create an array class (i.e. the class object for the array, not the
4208// array itself). "descriptor" looks like "[C" or "[[[[B" or
4209// "[Ljava/lang/String;".
4210//
4211// If "descriptor" refers to an array of primitives, look up the
4212// primitive type's internally-generated class object.
4213//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004214// "class_loader" is the class loader of the class that's referring to
4215// us. It's used to ensure that we're looking for the element type in
4216// the right context. It does NOT become the class loader for the
4217// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004218//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004219// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004220ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4221 const char* descriptor,
4222 size_t hash,
4223 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004224 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004225 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004226 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004227
4228 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4229 // code to be executed. We put it up here so we can avoid all the allocations associated with
4230 // creating the class. This can happen with (eg) jit threads.
4231 if (!self->CanLoadClasses()) {
4232 // Make sure we don't try to load anything, potentially causing an infinite loop.
4233 ObjPtr<mirror::Throwable> pre_allocated =
4234 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4235 self->SetException(pre_allocated);
4236 return nullptr;
4237 }
4238
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004239 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4240 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004241 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004242 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004243 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004244 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4245 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004246 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004247 DCHECK(self->IsExceptionPending());
4248 return nullptr;
4249 } else {
4250 self->ClearException();
4251 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004252 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004253 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4254 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4255 return nullptr;
4256 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004257 // See if the component type is already loaded. Array classes are
4258 // always associated with the class loader of their underlying
4259 // element type -- an array of Strings goes with the loader for
4260 // java/lang/String -- so we need to look for it there. (The
4261 // caller should have checked for the existence of the class
4262 // before calling here, but they did so with *their* class loader,
4263 // not the component type's loader.)
4264 //
4265 // If we find it, the caller adds "loader" to the class' initiating
4266 // loader list, which should prevent us from going through this again.
4267 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004268 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004269 // are the same, because our caller (FindClass) just did the
4270 // lookup. (Even if we get this wrong we still have correct behavior,
4271 // because we effectively do this lookup again when we add the new
4272 // class to the hash table --- necessary because of possible races with
4273 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004274 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004275 ObjPtr<mirror::Class> new_class =
4276 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004277 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004278 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004279 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004280 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004281 // Core array classes, i.e. Object[], Class[], String[] and primitive
4282 // arrays, have special initialization and they should be found above.
4283 DCHECK(!component_type->IsObjectClass() ||
4284 // Guard from false positives for errors before setting superclass.
4285 component_type->IsErroneousUnresolved());
4286 DCHECK(!component_type->IsStringClass());
4287 DCHECK(!component_type->IsClassClass());
4288 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004289
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004290 // Fill out the fields in the Class.
4291 //
4292 // It is possible to execute some methods against arrays, because
4293 // all arrays are subclasses of java_lang_Object_, so we need to set
4294 // up a vtable. We can just point at the one in java_lang_Object_.
4295 //
4296 // Array classes are simple enough that we don't need to do a full
4297 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004298 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4299 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4300 size_t usable_size)
4301 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004302 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004303 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4304 init_class(obj, usable_size);
4305 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4306 klass->SetComponentType(component_type.Get());
4307 // Do not hold lock for initialization, the fence issued after the visitor
4308 // returns ensures memory visibility together with the implicit consume
4309 // semantics (for all supported architectures) for any thread that loads
4310 // the array class reference from any memory locations afterwards.
4311 FinishArrayClassSetup(klass);
4312 };
4313 auto new_class = hs.NewHandle<mirror::Class>(
4314 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004315 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004316 self->AssertPendingOOMException();
4317 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004318 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004319
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004320 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004321 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004322 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4323 // duplicate events in case of races. Array classes don't really follow dedicated
4324 // load and prepare, anyways.
4325 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4326 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4327
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004328 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004329 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004330 }
4331 // Another thread must have loaded the class after we
4332 // started but before we finished. Abandon what we've
4333 // done.
4334 //
4335 // (Yes, this happens.)
4336
Vladimir Markobcf17522018-06-01 13:14:32 +01004337 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004338}
4339
Vladimir Marko9186b182018-11-06 14:55:54 +00004340ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4341 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004342 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004343 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4344 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4345 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4346 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4347 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4348 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4349 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4350 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4351 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004352 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004353 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004354 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004355 return GetClassRoot(class_root, this);
4356}
4357
4358ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4359 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4360 if (UNLIKELY(result == nullptr)) {
4361 std::string printable_type(PrintableChar(type));
4362 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4363 }
4364 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004365}
4366
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004367ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4368 ObjPtr<mirror::Class> klass,
4369 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004370 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004371 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004372 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004373 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004374 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004375 source += " from ";
4376 source += dex_cache->GetLocation()->ToModifiedUtf8();
4377 }
4378 LOG(INFO) << "Loaded class " << descriptor << source;
4379 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004380 {
4381 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004382 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004383 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004384 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004385 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004386 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004387 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004388 VerifyObject(klass);
4389 class_table->InsertWithHash(klass, hash);
4390 if (class_loader != nullptr) {
4391 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004392 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004393 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004394 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004395 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004396 }
4397 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004398 if (kIsDebugBuild) {
4399 // Test that copied methods correctly can find their holder.
4400 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4401 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4402 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004403 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004404 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004405}
4406
Vladimir Marko1998cd02017-01-13 13:02:58 +00004407void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004408 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4409 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4410 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4411 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004412 }
4413}
4414
Alex Lighte64300b2015-12-15 15:02:47 -08004415// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004416void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004417 LengthPrefixedArray<ArtMethod>* new_methods) {
4418 klass->SetMethodsPtrUnchecked(new_methods,
4419 klass->NumDirectMethods(),
4420 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004421 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004422 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004423}
4424
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004425ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4426 const char* descriptor,
4427 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004428 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4429}
4430
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004431ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4432 const char* descriptor,
4433 size_t hash,
4434 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004435 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4436 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4437 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004438 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004439 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004440 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004441 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004442 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004443 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004444}
4445
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004446class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4447 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004448 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004449
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004450 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004451 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004452 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004453 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004454 if (class_table != nullptr) {
4455 class_table->FreezeSnapshot();
4456 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004457 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004458};
4459
4460void ClassLinker::MoveClassTableToPreZygote() {
4461 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004462 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004463 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004464 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004465}
4466
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004467// Look up classes by hash and descriptor and put all matching ones in the result array.
4468class LookupClassesVisitor : public ClassLoaderVisitor {
4469 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004470 LookupClassesVisitor(const char* descriptor,
4471 size_t hash,
4472 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004473 : descriptor_(descriptor),
4474 hash_(hash),
4475 result_(result) {}
4476
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004477 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004478 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004479 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004480 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004481 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4482 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004483 result_->push_back(klass);
4484 }
4485 }
4486
4487 private:
4488 const char* const descriptor_;
4489 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004490 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004491};
4492
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004493void ClassLinker::LookupClasses(const char* descriptor,
4494 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004495 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004496 Thread* const self = Thread::Current();
4497 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004498 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004499 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004500 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004501 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004502 result.push_back(klass);
4503 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004504 LookupClassesVisitor visitor(descriptor, hash, &result);
4505 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004506}
4507
Alex Lightf1f10492015-10-07 16:08:36 -07004508bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4509 Handle<mirror::Class> klass,
4510 Handle<mirror::Class> supertype) {
4511 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004512 DCHECK(klass != nullptr);
4513 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004514
Alex Lightf1f10492015-10-07 16:08:36 -07004515 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4516 VerifyClass(self, supertype);
4517 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004518
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004519 if (supertype->IsVerified()
4520 || supertype->ShouldVerifyAtRuntime()
4521 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004522 // The supertype is either verified, or we soft failed at AOT time.
4523 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004524 return true;
4525 }
4526 // If we got this far then we have a hard failure.
4527 std::string error_msg =
4528 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004529 klass->PrettyDescriptor().c_str(),
4530 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004531 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004532 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004533 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004534 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004535 // Set during VerifyClass call (if at all).
4536 self->ClearException();
4537 }
4538 // Change into a verify error.
4539 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004540 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004541 self->GetException()->SetCause(cause.Get());
4542 }
4543 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4544 if (Runtime::Current()->IsAotCompiler()) {
4545 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4546 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004547 // Need to grab the lock to change status.
4548 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004549 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004550 return false;
4551}
4552
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004553verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004554 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004555 {
4556 // TODO: assert that the monitor on the Class is held
4557 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004558
Andreas Gampe884f3b82016-03-30 19:52:58 -07004559 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004560 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004561 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004562 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004563 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4564 // case we may see the same status again. b/62912904. This is why the check is
4565 // greater or equal.
4566 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004567 << "Class '" << klass->PrettyClass()
4568 << "' performed an illegal verification state transition from " << old_status
4569 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004570 old_status = klass->GetStatus();
4571 }
jeffhao98eacac2011-09-14 16:11:53 -07004572
Andreas Gampe884f3b82016-03-30 19:52:58 -07004573 // The class might already be erroneous, for example at compile time if we attempted to verify
4574 // this class as a parent to another.
4575 if (klass->IsErroneous()) {
4576 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004577 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004578 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004579
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004580 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004581 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004582 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004583 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004584 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004585
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004586 if (klass->IsVerifiedNeedsAccessChecks()) {
4587 if (!Runtime::Current()->IsAotCompiler()) {
4588 // Mark the class as having a verification attempt to avoid re-running
4589 // the verifier and avoid calling EnsureSkipAccessChecksMethods.
4590 klass->SetVerificationAttempted();
4591 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4592 }
4593 return verifier::FailureKind::kAccessChecksFailure;
4594 }
4595
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004596 // For AOT, don't attempt to re-verify if we have already found we should
4597 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004598 if (klass->ShouldVerifyAtRuntime()) {
4599 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004600 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004601 }
jeffhao98eacac2011-09-14 16:11:53 -07004602
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004603 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4604 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004605
4606 // Skip verification if disabled.
4607 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004608 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004609 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004610 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004611 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004612 }
4613
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004614 VLOG(class_linker) << "Beginning verification for class: "
4615 << klass->PrettyDescriptor()
4616 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4617
Ian Rogers9ffb0392012-09-10 11:56:50 -07004618 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004619 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004620 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4621 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004622 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004623 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004624 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004625 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004626
Alex Lightf1f10492015-10-07 16:08:36 -07004627 // Verify all default super-interfaces.
4628 //
4629 // (1) Don't bother if the superclass has already had a soft verification failure.
4630 //
4631 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4632 // recursive initialization by themselves. This is because when an interface is initialized
4633 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4634 // but choose not to for an optimization. If the interfaces is being verified due to a class
4635 // initialization (which would need all the default interfaces to be verified) the class code
4636 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004637 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004638 && !klass->IsInterface()) { // See (2)
4639 int32_t iftable_count = klass->GetIfTableCount();
4640 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4641 // Loop through all interfaces this class has defined. It doesn't matter the order.
4642 for (int32_t i = 0; i < iftable_count; i++) {
4643 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004644 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004645 // We only care if we have default interfaces and can skip if we are already verified...
4646 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4647 continue;
4648 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4649 // We had a hard failure while verifying this interface. Just return immediately.
4650 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004651 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004652 } else if (UNLIKELY(!iface->IsVerified())) {
4653 // We softly failed to verify the iface. Stop checking and clean up.
4654 // Put the iface into the supertype handle so we know what caused us to fail.
4655 supertype.Assign(iface.Get());
4656 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004657 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004658 }
4659 }
4660
Alex Lightf1f10492015-10-07 16:08:36 -07004661 // At this point if verification failed, then supertype is the "first" supertype that failed
4662 // verification (without a specific order). If verification succeeded, then supertype is either
4663 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004664 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004665 supertype.Get() == klass->GetSuperClass() ||
4666 !supertype->IsVerified());
4667
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004668 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004669 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004670 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004671 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004672
4673 VLOG(class_linker) << "Class preverified status for class "
4674 << klass->PrettyDescriptor()
4675 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4676 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004677 << preverified
4678 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004679
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004680 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4681 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004682 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4683 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004684
Ian Rogers62d6c772013-02-27 08:32:07 -08004685 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004686 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004687 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004688 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004689 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004690
4691 // Verification is done, grab the lock again.
4692 ObjectLock<mirror::Class> lock(self, klass);
4693
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004694 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4695 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004696 VLOG(class_linker) << "Soft verification failure in class "
4697 << klass->PrettyDescriptor()
4698 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4699 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004700 }
Ian Rogers1f539342012-10-03 21:09:42 -07004701 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004702 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004703 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004704 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004705 // Even though there were no verifier failures we need to respect whether the super-class and
4706 // super-default-interfaces were verified or requiring runtime reverification.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004707 if (supertype == nullptr
4708 || supertype->IsVerified()
4709 || supertype->IsVerifiedNeedsAccessChecks()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004710 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004711 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004712 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004713 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4714 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004715 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004716 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004717 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004718 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004719 CHECK(verifier_failure == verifier::FailureKind::kSoftFailure ||
4720 verifier_failure == verifier::FailureKind::kAccessChecksFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004721 // Soft failures at compile time should be retried at runtime. Soft
4722 // failures at runtime will be handled by slow paths in the generated
4723 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004724 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004725 if (verifier_failure == verifier::FailureKind::kSoftFailure) {
4726 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4727 } else {
4728 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4729 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004730 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004731 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004732 // As this is a fake verified status, make sure the methods are _not_ marked
4733 // kAccSkipAccessChecks later.
4734 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004735 }
4736 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004737 } else {
David Sehr709b0702016-10-13 09:12:37 -07004738 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004739 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4740 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004741 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004742 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004743 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004744 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004745 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004746 if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks ||
4747 UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
Igor Murashkindf707e42016-02-02 16:56:50 -08004748 // Never skip access checks if the verification soft fail is forced.
4749 // Mark the class as having a verification attempt to avoid re-running the verifier.
4750 klass->SetVerificationAttempted();
4751 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004752 // Class is verified so we don't need to do any access check on its methods.
4753 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
4754 // method.
4755 // Note: we're going here during compilation and at runtime. When we set the
4756 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
4757 // in the image and is set when loading the image.
Andreas Gampecc1b5352016-12-01 16:58:38 -08004758 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004759 }
Andreas Gampe48498592014-09-10 19:48:05 -07004760 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004761 // Done verifying. Notify the compiler about the verification status, in case the class
4762 // was verified implicitly (eg super class of a compiled class).
4763 if (Runtime::Current()->IsAotCompiler()) {
4764 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4765 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4766 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004767 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004768}
4769
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004770verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4771 Handle<mirror::Class> klass,
4772 verifier::HardFailLogMode log_level,
4773 std::string* error_msg) {
4774 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004775 return verifier::ClassVerifier::VerifyClass(self,
4776 klass.Get(),
4777 runtime->GetCompilerCallbacks(),
4778 runtime->IsAotCompiler(),
4779 log_level,
4780 Runtime::Current()->GetTargetSdkVersion(),
4781 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004782}
4783
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004784bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004785 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004786 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004787 // If we're compiling, we can only verify the class using the oat file if
4788 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004789 // the compilation unit (app - dependencies). We will let the compiler callback
4790 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004791 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004792 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004793 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004794 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004795 return false;
4796 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004797 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004798
Andreas Gampeb40d3612018-06-26 15:49:42 -07004799 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004800 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004801 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004802 return false;
4803 }
4804
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004805 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004806 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004807 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004808 return true;
4809 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004810 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4811 // We return that the clas has already been verified, and the caller should
4812 // check the class status to ensure we run with access checks.
4813 return true;
4814 }
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004815 // If we only verified a subset of the classes at compile time, we can end up with classes that
4816 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004817 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004818 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004819 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004820 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4821 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4822 << klass->PrettyClass() << " " << dex_file.GetLocation();
4823
Vladimir Marko72ab6842017-01-20 19:32:50 +00004824 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004825 // Compile time verification failed with a hard error. This is caused by invalid instructions
4826 // in the class. These errors are unrecoverable.
4827 return false;
4828 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004829 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004830 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4831 // not loading the class.
4832 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4833 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004834 return false;
4835 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004836 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004837 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004838 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004839 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004840 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004841}
4842
Alex Light5a559862016-01-29 12:24:48 -08004843void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004844 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004845 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004846 }
4847}
4848
Alex Light5a559862016-01-29 12:24:48 -08004849void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004850 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004851 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004852 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004853 return; // native or abstract method
4854 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004855 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004856 return; // nothing to process
4857 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004858 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004859 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004860 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4861 CatchHandlerIterator iterator(handlers_ptr);
4862 for (; iterator.HasNext(); iterator.Next()) {
4863 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4864 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004865 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004866 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004867 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004868 DCHECK(Thread::Current()->IsExceptionPending());
4869 Thread::Current()->ClearException();
4870 }
4871 }
4872 }
4873 handlers_ptr = iterator.EndDataPointer();
4874 }
4875}
4876
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004877ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4878 jstring name,
4879 jobjectArray interfaces,
4880 jobject loader,
4881 jobjectArray methods,
4882 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004883 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004884
4885 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4886 // code to be executed. We put it up here so we can avoid all the allocations associated with
4887 // creating the class. This can happen with (eg) jit-threads.
4888 if (!self->CanLoadClasses()) {
4889 // Make sure we don't try to load anything, potentially causing an infinite loop.
4890 ObjPtr<mirror::Throwable> pre_allocated =
4891 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4892 self->SetException(pre_allocated);
4893 return nullptr;
4894 }
4895
Alex Light133987d2020-03-26 19:22:12 +00004896 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004897 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004898 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004899 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004900 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004901 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004902 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004903 DCHECK(temp_klass->GetClass() != nullptr);
4904 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004905 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4906 // the methods.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004907 temp_klass->SetAccessFlagsDuringLinking(
4908 kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004909 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4910 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4911 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004912 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004913 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004914 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004915 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004916 std::string storage;
4917 const char* descriptor = temp_klass->GetDescriptor(&storage);
4918 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004919
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004920 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004921 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004922
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004923 // Insert the class before loading the fields as the field roots
4924 // (ArtField::declaring_class_) are only visited from the class
4925 // table. There can't be any suspend points between inserting the
4926 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004927 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004928 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004929
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004930 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004931 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004932 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004933 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004934
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004935 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4936 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004937 ArtField& interfaces_sfield = sfields->At(0);
4938 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004939 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004940 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004941
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004942 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004943 ArtField& throws_sfield = sfields->At(1);
4944 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004945 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004946 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004947
Ian Rogers466bb252011-10-14 03:29:56 -07004948 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004949 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004950
Alex Light133987d2020-03-26 19:22:12 +00004951 // The array we get passed contains all methods, including private and static
4952 // ones that aren't proxied. We need to filter those out since only interface
4953 // methods (non-private & virtual) are actually proxied.
4954 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4955 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004956 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004957 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004958 // List of the actual virtual methods this class will have.
4959 std::vector<ArtMethod*> proxied_methods;
4960 std::vector<size_t> proxied_throws_idx;
4961 proxied_methods.reserve(h_methods->GetLength());
4962 proxied_throws_idx.reserve(h_methods->GetLength());
4963 // Filter out to only the non-private virtual methods.
4964 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4965 ArtMethod* m = mirror->GetArtMethod();
4966 if (!m->IsPrivate() && !m->IsStatic()) {
4967 proxied_methods.push_back(m);
4968 proxied_throws_idx.push_back(idx);
4969 }
4970 }
4971 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004972 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4973 // contains an array of all the classes each function is declared to throw.
4974 // This is used to wrap unexpected exceptions in a
4975 // UndeclaredThrowableException exception. This array is in the same order as
4976 // the methods array and like the methods array must be filtered to remove any
4977 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004978 const bool has_filtered_methods =
4979 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4980 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4981 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4982 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4983 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4984 (has_filtered_methods)
4985 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4986 self, original_proxied_throws->GetClass(), num_virtual_methods)
4987 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004988 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4989 self->AssertPendingOOMException();
4990 return nullptr;
4991 }
Alex Light133987d2020-03-26 19:22:12 +00004992 if (has_filtered_methods) {
4993 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
4994 DCHECK_LE(new_idx, orig_idx);
4995 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
4996 }
4997 }
Alex Lighte64300b2015-12-15 15:02:47 -08004998
4999 // Create the methods array.
5000 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
5001 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005002 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
5003 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08005004 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005005 self->AssertPendingOOMException();
5006 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07005007 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005008 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08005009
5010 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005011 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08005012
5013 // Create virtual method using specified prototypes.
5014 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04005015 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005016 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005017 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005018 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005019 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
5020 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04005021 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005022
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005023 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005024 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005025 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005026 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08005027 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08005028
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005029 // At this point the class is loaded. Publish a ClassLoad event.
5030 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
5031 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
5032
5033 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07005034 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005035 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005036 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005037 // Link the fields and virtual methods, creating vtable and iftables.
5038 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005039 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005040 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00005041 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005042 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005043 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005044 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005045 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005046 CHECK(temp_klass->IsRetired());
5047 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005048
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005049 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005050 interfaces_sfield.SetObject<false>(
5051 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005052 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005053 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5054 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005055 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00005056 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005057
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005058 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5059
Vladimir Marko305c38b2018-02-14 11:50:07 +00005060 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5061 // See also ClassLinker::EnsureInitialized().
5062 if (kBitstringSubtypeCheckEnabled) {
5063 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5064 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5065 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5066 }
5067
Vladimir Markobf121912019-06-04 13:49:05 +01005068 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005069 {
5070 // Lock on klass is released. Lock new class object.
5071 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005072 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005073 // Conservatively go through the ClassStatus::kInitialized state.
5074 callback = MarkClassInitialized(self, klass);
5075 }
5076 if (callback != nullptr) {
5077 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005078 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005079
David Srbecky346fd962020-07-27 16:51:00 +01005080 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07005081 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005082 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005083 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5084
Ian Rogersc2b44472011-12-14 21:17:17 -08005085 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005086 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005087 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08005088 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005089
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005090 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005091 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005092 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005093 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005094 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005095
5096 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005097 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005098 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005099
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005100 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005101 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005102 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005103 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005104 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005105 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005106}
5107
Mathieu Chartiere401d142015-04-22 13:56:20 -07005108void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5109 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005110 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5111 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005112
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005113 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5114 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005115 ArtMethod* proxy_constructor =
5116 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005117 DCHECK(proxy_constructor != nullptr)
5118 << "Could not find <init> method in java.lang.reflect.Proxy";
5119
Jeff Haodb8a6642014-08-14 17:18:52 -07005120 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5121 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005122 DCHECK(out != nullptr);
5123 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005124 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005125 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005126 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005127 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5128 kAccPublic |
5129 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005130 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005131
5132 // Set the original constructor method.
5133 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005134}
5135
Mathieu Chartiere401d142015-04-22 13:56:20 -07005136void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005137 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005138 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5139 CHECK_STREQ(np->GetName(), "<init>");
5140 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005141 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005142}
5143
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005144void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005145 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005146 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005147 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005148 DCHECK(out != nullptr);
5149 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005150
Alex Lighte9dd04f2016-03-16 16:09:45 -07005151 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005152 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005153 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5154 // preference to the invocation handler.
5155 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5156 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005157 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5158 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005159 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5160
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005161 // Set the original interface method.
5162 out->SetDataPtrSize(prototype, image_pointer_size_);
5163
Ian Rogers466bb252011-10-14 03:29:56 -07005164 // At runtime the method looks like a reference and argument saving method, clone the code
5165 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005166 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005167}
Jesse Wilson95caa792011-10-12 18:14:17 -04005168
Mathieu Chartiere401d142015-04-22 13:56:20 -07005169void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005170 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005171 CHECK(!prototype->IsFinal());
5172 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005173 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005174
5175 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5176 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005177 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005178 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005179}
5180
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005181bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005182 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005183 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005184 return true;
5185 }
5186 if (!can_init_statics) {
5187 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005188 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005189 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005190 return false;
5191 }
5192 // Check if there are encoded static values needing initialization.
5193 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005194 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005195 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005196 if (dex_class_def->static_values_off_ != 0) {
5197 return false;
5198 }
5199 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005200 }
5201 // If we are a class we need to initialize all interfaces with default methods when we are
5202 // initialized. Check all of them.
5203 if (!klass->IsInterface()) {
5204 size_t num_interfaces = klass->GetIfTableCount();
5205 for (size_t i = 0; i < num_interfaces; i++) {
5206 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5207 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5208 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005209 return false;
5210 }
5211 }
5212 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005213 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005214 if (klass->IsInterface() || !klass->HasSuperClass()) {
5215 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005216 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005217 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005218 if (super_class->IsInitialized()) {
5219 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005220 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005221 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005222}
5223
Mathieu Chartier23369542020-03-04 08:24:11 -08005224bool ClassLinker::InitializeClass(Thread* self,
5225 Handle<mirror::Class> klass,
5226 bool can_init_statics,
5227 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005228 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5229
5230 // Are we already initialized and therefore done?
5231 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5232 // an initialized class will never change its state.
5233 if (klass->IsInitialized()) {
5234 return true;
5235 }
5236
5237 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005238 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005239 return false;
5240 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005241
Ian Rogers7b078e82014-09-10 14:44:24 -07005242 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005243 Runtime* const runtime = Runtime::Current();
5244 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005245 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005246 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005247 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005248
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005249 // Re-check under the lock in case another thread initialized ahead of us.
5250 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005251 return true;
5252 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005253
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005254 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005255 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005256 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005257 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005258 return false;
5259 }
5260
Vladimir Marko72ab6842017-01-20 19:32:50 +00005261 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5262 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005263
5264 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005265 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005266 if (!klass->IsVerified()) {
5267 // We failed to verify, expect either the klass to be erroneous or verification failed at
5268 // compile time.
5269 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005270 // The class is erroneous. This may be a verifier error, or another thread attempted
5271 // verification and/or initialization and failed. We can distinguish those cases by
5272 // whether an exception is already pending.
5273 if (self->IsExceptionPending()) {
5274 // Check that it's a VerifyError.
5275 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005276 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005277 } else {
5278 // Check that another thread attempted initialization.
5279 DCHECK_NE(0, klass->GetClinitThreadId());
5280 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5281 // Need to rethrow the previous failure now.
5282 ThrowEarlierClassFailure(klass.Get(), true);
5283 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005284 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005285 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005286 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005287 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005288 self->AssertNoPendingException();
5289 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005290 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005291 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005292 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005293 } else {
5294 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005295 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005296
5297 // A separate thread could have moved us all the way to initialized. A "simple" example
5298 // involves a subclass of the current class being initialized at the same time (which
5299 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005300 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005301 if (klass->IsInitialized()) {
5302 return true;
5303 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005304 }
5305
Vladimir Marko2c64a832018-01-04 11:31:56 +00005306 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005307 // initializing higher up the stack or another thread has beat us
5308 // to initializing and we need to wait. Either way, this
5309 // invocation of InitializeClass will not be responsible for
5310 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005311 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005312 // Could have got an exception during verification.
5313 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005314 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005315 return false;
5316 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005317 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005318 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005319 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005320 return true;
5321 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005322 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005323 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005324 }
5325
Jeff Haoe2e40342017-07-19 10:45:18 -07005326 // Try to get the oat class's status for this class if the oat file is present. The compiler
5327 // tries to validate superclass descriptors, and writes the result into the oat file.
5328 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5329 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5330 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005331 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005332 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5333 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5334 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005335 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005336 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005337 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005338 return false;
5339 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005340 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005341
Vladimir Marko2c64a832018-01-04 11:31:56 +00005342 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005343 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005344
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005345 // From here out other threads may observe that we're initializing and so changes of state
5346 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005347 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005348 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005349
Mathieu Chartier23369542020-03-04 08:24:11 -08005350 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005351 }
5352
Andreas Gampeaf864702019-07-23 14:05:35 -07005353 uint64_t t_sub = 0;
5354
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005355 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005356 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005357 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005358 if (!super_class->IsInitialized()) {
5359 CHECK(!super_class->IsInterface());
5360 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005361 StackHandleScope<1> hs(self);
5362 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005363 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005364 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005365 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005366 if (!super_initialized) {
5367 // The super class was verified ahead of entering initializing, we should only be here if
5368 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005369 // For the case of aot compiler, the super class might also be initializing but we don't
5370 // want to process circular dependencies in pre-compile.
5371 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005372 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005373 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005374 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005375 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005376 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005377 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005378 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005379 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005380 return false;
5381 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005382 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005383 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005384 }
5385
Alex Lighteb7c1442015-08-31 13:17:42 -07005386 if (!klass->IsInterface()) {
5387 // Initialize interfaces with default methods for the JLS.
5388 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005389 // Only setup the (expensive) handle scope if we actually need to.
5390 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005391 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005392 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5393 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005394 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005395 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005396 CHECK(handle_scope_iface->IsInterface());
5397 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5398 // We have already done this for this interface. Skip it.
5399 continue;
5400 }
5401 // We cannot just call initialize class directly because we need to ensure that ALL
5402 // interfaces with default methods are initialized. Non-default interface initialization
5403 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005404 // This is not very precise, misses all walking.
5405 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005406 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5407 handle_scope_iface,
5408 can_init_statics,
5409 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005410 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005411 if (!iface_initialized) {
5412 ObjectLock<mirror::Class> lock(self, klass);
5413 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005414 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005415 return false;
5416 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005417 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005418 }
5419 }
5420 }
5421
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005422 const size_t num_static_fields = klass->NumStaticFields();
5423 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005424 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005425 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005426 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005427 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005428 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005429
5430 // Eagerly fill in static fields so that the we don't have to do as many expensive
5431 // Class::FindStaticField in ResolveField.
5432 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005433 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005434 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005435 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005436 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005437 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005438 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5439 field,
5440 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5441 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005442 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005443 } else {
5444 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005445 }
5446 }
5447
Vladimir Markoe11dd502017-12-08 14:09:45 +00005448 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5449 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005450 this,
5451 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005452 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005453
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005454 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005455 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005456 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005457 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5458 if (!value_it.HasNext()) {
5459 break;
5460 }
5461 ArtField* art_field = ResolveField(field.GetIndex(),
5462 dex_cache,
5463 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005464 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005465 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005466 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005467 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005468 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005469 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005470 if (self->IsExceptionPending()) {
5471 break;
5472 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005473 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005474 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005475 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005476 }
5477 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005478
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005479
Mathieu Chartierda595be2016-08-10 13:57:39 -07005480 if (!self->IsExceptionPending()) {
5481 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5482 if (clinit != nullptr) {
5483 CHECK(can_init_statics);
5484 JValue result;
5485 clinit->Invoke(self, nullptr, 0, &result, "V");
5486 }
5487 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005488 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005489 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005490
Vladimir Markobf121912019-06-04 13:49:05 +01005491 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005492 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005493 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005494 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005495
5496 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005497 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005498 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005499 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005500 } else if (Runtime::Current()->IsTransactionAborted()) {
5501 // The exception thrown when the transaction aborted has been caught and cleared
5502 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005503 VLOG(compiler) << "Return from class initializer of "
5504 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005505 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005506 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005507 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005508 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005509 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005510 if (stats_enabled) {
5511 RuntimeStats* global_stats = runtime->GetStats();
5512 RuntimeStats* thread_stats = self->GetStats();
5513 ++global_stats->class_init_count;
5514 ++thread_stats->class_init_count;
5515 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5516 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5517 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005518 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005519 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005520 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005521 std::string temp;
5522 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005523 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005524 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005525 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005526 }
Vladimir Markobf121912019-06-04 13:49:05 +01005527 if (callback != nullptr) {
5528 callback->MakeVisible(self);
5529 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005530 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005531}
5532
Alex Lighteb7c1442015-08-31 13:17:42 -07005533// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5534// and perform the initialization only on those interfaces that contain default methods.
5535bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5536 Handle<mirror::Class> iface,
5537 bool can_init_statics,
5538 bool can_init_parents) {
5539 CHECK(iface->IsInterface());
5540 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005541 // Only create the (expensive) handle scope if we need it.
5542 if (UNLIKELY(num_direct_ifaces > 0)) {
5543 StackHandleScope<1> hs(self);
5544 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5545 // First we initialize all of iface's super-interfaces recursively.
5546 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005547 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005548 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005549 if (!super_iface->HasBeenRecursivelyInitialized()) {
5550 // Recursive step
5551 handle_super_iface.Assign(super_iface);
5552 if (!InitializeDefaultInterfaceRecursive(self,
5553 handle_super_iface,
5554 can_init_statics,
5555 can_init_parents)) {
5556 return false;
5557 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005558 }
5559 }
5560 }
5561
5562 bool result = true;
5563 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5564 // initialize if we don't have default methods.
5565 if (iface->HasDefaultMethods()) {
5566 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5567 }
5568
5569 // Mark that this interface has undergone recursive default interface initialization so we know we
5570 // can skip it on any later class initializations. We do this even if we are not a default
5571 // interface since we can still avoid the traversal. This is purely a performance optimization.
5572 if (result) {
5573 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005574 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5575 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5576 // initialization is a performance optimization (to avoid another idempotent visit
5577 // for other implementing classes/interfaces), and can be revisited later.
5578 ObjectTryLock<mirror::Class> lock(self, iface);
5579 if (lock.Acquired()) {
5580 iface->SetRecursivelyInitialized();
5581 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005582 }
5583 return result;
5584}
5585
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005586bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5587 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005588 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005589 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005590 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005591 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005592 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005593 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005594
5595 // When we wake up, repeat the test for init-in-progress. If
5596 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005597 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005598 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005599 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005600 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005601 return false;
5602 }
5603 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005604 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005605 continue;
5606 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005607 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005608 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005609 // Compile time initialization failed.
5610 return false;
5611 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005612 if (klass->IsErroneous()) {
5613 // The caller wants an exception, but it was thrown in a
5614 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005615 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005616 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005617 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005618 return false;
5619 }
5620 if (klass->IsInitialized()) {
5621 return true;
5622 }
David Sehr709b0702016-10-13 09:12:37 -07005623 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005624 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005625 }
Ian Rogers07140832014-09-30 15:43:59 -07005626 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005627}
5628
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005629static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5630 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005631 ArtMethod* method,
5632 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005633 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005634 DCHECK(Thread::Current()->IsExceptionPending());
5635 DCHECK(!m->IsProxyMethod());
5636 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005637 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5638 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005639 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005640 std::string return_type = dex_file->PrettyType(return_type_idx);
5641 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005642 ThrowWrappedLinkageError(klass.Get(),
5643 "While checking class %s method %s signature against %s %s: "
5644 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005645 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5646 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005647 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005648 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005649 return_type.c_str(), class_loader.c_str());
5650}
5651
5652static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5653 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005654 ArtMethod* method,
5655 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005656 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005657 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005658 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005659 DCHECK(Thread::Current()->IsExceptionPending());
5660 DCHECK(!m->IsProxyMethod());
5661 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005662 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5663 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005664 ThrowWrappedLinkageError(klass.Get(),
5665 "While checking class %s method %s signature against %s %s: "
5666 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005667 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5668 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005669 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005670 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005671 index, arg_type.c_str(), class_loader.c_str());
5672}
5673
5674static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5675 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005676 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005677 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005678 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005679 ThrowLinkageError(klass.Get(),
5680 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005681 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5682 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005683 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005684 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005685 error_msg.c_str());
5686}
5687
Ian Rogersb5fb2072014-12-02 17:22:02 -08005688static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005689 Handle<mirror::Class> klass,
5690 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005691 ArtMethod* method1,
5692 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005693 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005694 {
5695 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005696 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005697 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005698 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005699 return false;
5700 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005701 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005702 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005703 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005704 return false;
5705 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005706 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005707 ThrowSignatureMismatch(klass, super_klass, method1,
5708 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005709 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005710 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005711 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005712 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005713 return false;
5714 }
5715 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005716 const dex::TypeList* types1 = method1->GetParameterTypeList();
5717 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005718 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005719 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005720 ThrowSignatureMismatch(klass, super_klass, method1,
5721 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005722 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005723 return false;
5724 }
5725 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005726 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005727 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005728 ThrowSignatureMismatch(klass, super_klass, method1,
5729 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005730 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005731 return false;
5732 }
5733 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005734 }
5735 uint32_t num_types = types1->Size();
5736 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005737 ThrowSignatureMismatch(klass, super_klass, method1,
5738 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005739 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005740 return false;
5741 }
5742 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005743 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005744 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005745 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005746 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005747 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005748 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005749 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005750 return false;
5751 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005752 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005753 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005754 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005755 if (UNLIKELY(other_param_type == nullptr)) {
5756 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005757 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005758 return false;
5759 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005760 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005761 ThrowSignatureMismatch(klass, super_klass, method1,
5762 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5763 i,
David Sehr709b0702016-10-13 09:12:37 -07005764 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005765 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005766 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005767 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005768 return false;
5769 }
5770 }
5771 return true;
5772}
5773
5774
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005775bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005776 if (klass->IsInterface()) {
5777 return true;
5778 }
Ian Rogers151f2212014-05-06 11:27:27 -07005779 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005780 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005781 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005782 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005783 if (klass->HasSuperClass() &&
5784 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005785 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005786 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005787 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5788 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5789 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005790 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5791 klass,
5792 super_klass,
5793 m,
5794 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005795 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005796 return false;
5797 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005798 }
5799 }
5800 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005801 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005802 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5803 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5804 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005805 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005806 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5807 j, image_pointer_size_);
5808 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5809 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005810 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5811 klass,
5812 super_klass,
5813 m,
5814 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005815 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005816 return false;
5817 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005818 }
5819 }
5820 }
5821 }
5822 return true;
5823}
5824
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005825bool ClassLinker::EnsureInitialized(Thread* self,
5826 Handle<mirror::Class> c,
5827 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005828 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005829 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005830
Mathieu Chartier524507a2014-08-27 15:28:28 -07005831 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005832 // If we've seen an initialized but not visibly initialized class
5833 // many times, request visible initialization.
5834 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5835 // Thanks to the x86 memory model classes skip the initialized status.
5836 DCHECK(c->IsVisiblyInitialized());
5837 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5838 if (self->IncrementMakeVisiblyInitializedCounter()) {
5839 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5840 }
5841 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005842 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005843 return true;
5844 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005845 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5846 //
5847 // Ensure the bitstring is initialized before any of the class initialization
5848 // logic occurs. Once a class initializer starts running, objects can
5849 // escape into the heap and use the subtype checking code.
5850 //
5851 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5852 // can be used as a source for the IsSubClass check, and that all ancestors
5853 // of the class are Assigned (can be used as a target for IsSubClass check)
5854 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005855 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005856 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005857 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005858 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5859 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005860 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005861 if (!success) {
5862 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005863 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005864 }
5865 } else {
5866 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005867 }
5868 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005869}
5870
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005871void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5872 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005873 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005874 for (ArtField& field : new_class->GetIFields()) {
5875 if (field.GetDeclaringClass() == temp_class) {
5876 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005877 }
5878 }
5879
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005880 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005881 for (ArtField& field : new_class->GetSFields()) {
5882 if (field.GetDeclaringClass() == temp_class) {
5883 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005884 }
5885 }
5886
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005887 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005888 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005889 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005890 if (method.GetDeclaringClass() == temp_class) {
5891 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005892 }
5893 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005894
5895 // Make sure the remembered set and mod-union tables know that we updated some of the native
5896 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005897 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005898}
5899
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005900void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005901 CHECK(class_loader->GetAllocator() == nullptr);
5902 CHECK(class_loader->GetClassTable() == nullptr);
5903 Thread* const self = Thread::Current();
5904 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005905 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005906 // Create and set the class table.
5907 data.class_table = new ClassTable;
5908 class_loader->SetClassTable(data.class_table);
5909 // Create and set the linear allocator.
5910 data.allocator = Runtime::Current()->CreateLinearAlloc();
5911 class_loader->SetAllocator(data.allocator);
5912 // Add to the list so that we know to free the data later.
5913 class_loaders_.push_back(data);
5914}
5915
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005916ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005917 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005918 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005919 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005920 ClassTable* class_table = class_loader->GetClassTable();
5921 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005922 RegisterClassLoader(class_loader);
5923 class_table = class_loader->GetClassTable();
5924 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005925 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005926 return class_table;
5927}
5928
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005929ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005930 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005931}
5932
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005933static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005934 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005935 while (klass->HasSuperClass()) {
5936 klass = klass->GetSuperClass();
5937 if (klass->ShouldHaveImt()) {
5938 return klass->GetImt(pointer_size);
5939 }
5940 }
5941 return nullptr;
5942}
5943
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005944bool ClassLinker::LinkClass(Thread* self,
5945 const char* descriptor,
5946 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005947 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005948 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005949 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005950
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005951 if (!LinkSuperClass(klass)) {
5952 return false;
5953 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005954 ArtMethod* imt_data[ImTable::kSize];
5955 // If there are any new conflicts compared to super class.
5956 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005957 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005958 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005959 return false;
5960 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005961 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005962 return false;
5963 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005964 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005965 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005966 return false;
5967 }
5968 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005969 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005970
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005971 ImTable* imt = nullptr;
5972 if (klass->ShouldHaveImt()) {
5973 // If there are any new conflicts compared to the super class we can not make a copy. There
5974 // can be cases where both will have a conflict method at the same slot without having the same
5975 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5976 // will possibly create a table that is incorrect for either of the classes.
5977 // Same IMT with new_conflict does not happen very often.
5978 if (!new_conflict) {
5979 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5980 if (super_imt != nullptr) {
5981 bool imt_equals = true;
5982 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5983 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5984 }
5985 if (imt_equals) {
5986 imt = super_imt;
5987 }
5988 }
5989 }
5990 if (imt == nullptr) {
5991 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5992 imt = reinterpret_cast<ImTable*>(
5993 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5994 if (imt == nullptr) {
5995 return false;
5996 }
5997 imt->Populate(imt_data, image_pointer_size_);
5998 }
5999 }
6000
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006001 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
6002 // We don't need to retire this class as it has no embedded tables or it was created the
6003 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07006004 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006005
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006006 if (klass->ShouldHaveEmbeddedVTable()) {
6007 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006008 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006009 if (klass->ShouldHaveImt()) {
6010 klass->SetImt(imt, image_pointer_size_);
6011 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006012
6013 // Update CHA info based on whether we override methods.
6014 // Have to do this before setting the class as resolved which allows
6015 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006016 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006017 cha_->UpdateAfterLoadingOf(klass);
6018 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00006019
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006020 // This will notify waiters on klass that saw the not yet resolved
6021 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006022 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006023 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006024 } else {
6025 CHECK(!klass->IsResolved());
6026 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006027 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01006028 Handle<mirror::Class> h_new_class =
6029 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07006030 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
6031 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
6032 // may not see any references to the target space and clean the card for a class if another
6033 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08006034 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07006035 klass->SetSFieldsPtrUnchecked(nullptr);
6036 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006037 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006038 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00006039 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006040 return false;
6041 }
6042
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006043 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6044 ObjectLock<mirror::Class> lock(self, h_new_class);
6045 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006046
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006047 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006048 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006049 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006050 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006051 const ObjPtr<mirror::Class> existing =
6052 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006053 if (class_loader != nullptr) {
6054 // We updated the class in the class table, perform the write barrier so that the GC knows
6055 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006056 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006057 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006058 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006059 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006060 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6061 }
6062 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006063
Mingyao Yang063fc772016-08-02 11:02:54 -07006064 // Update CHA info based on whether we override methods.
6065 // Have to do this before setting the class as resolved which allows
6066 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006067 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006068 cha_->UpdateAfterLoadingOf(h_new_class);
6069 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006070
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006071 // This will notify waiters on temp class that saw the not yet resolved class in the
6072 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006073 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006074
Vladimir Marko2c64a832018-01-04 11:31:56 +00006075 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006076 // This will notify waiters on new_class that saw the not yet resolved
6077 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006078 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006079 // Return the new class.
6080 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006081 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006082 return true;
6083}
6084
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006085bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006086 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006087 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006088 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6089 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006090 // Check that a class does not inherit from itself directly.
6091 //
6092 // TODO: This is a cheap check to detect the straightforward case
6093 // of a class extending itself (b/28685551), but we should do a
6094 // proper cycle detection on loaded classes, to detect all cases
6095 // of class circularity errors (b/28830038).
6096 if (super_class_idx == class_def.class_idx_) {
6097 ThrowClassCircularityError(klass.Get(),
6098 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006099 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006100 return false;
6101 }
6102
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006103 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006104 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006105 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006106 return false;
6107 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006108 // Verify
6109 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006110 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006111 super_class->PrettyDescriptor().c_str(),
6112 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006113 return false;
6114 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006115 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006116 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006117 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006118 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006119 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006120 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006121 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006122 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006123 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006124 DCHECK(Thread::Current()->IsExceptionPending());
6125 return false;
6126 }
6127 // Verify
6128 if (!klass->CanAccess(interface)) {
6129 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006130 ThrowIllegalAccessError(klass.Get(),
6131 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006132 interface->PrettyDescriptor().c_str(),
6133 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006134 return false;
6135 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006136 }
6137 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006138 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006139 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006140 return true;
6141}
6142
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006143bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006144 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006145 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006146 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6147 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006148 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006149 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006150 return false;
6151 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006152 return true;
6153 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006154 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006155 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006156 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006157 return false;
6158 }
6159 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006160 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006161 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6162 return false;
6163 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006164 if (super->IsFinal()) {
6165 ThrowVerifyError(klass.Get(),
6166 "Superclass %s of %s is declared final",
6167 super->PrettyDescriptor().c_str(),
6168 klass->PrettyDescriptor().c_str());
6169 return false;
6170 }
6171 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006172 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006173 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006174 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006175 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006176 return false;
6177 }
6178 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006179 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006180 super->PrettyDescriptor().c_str(),
6181 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006182 return false;
6183 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006184
Brian Carlstromf3632832014-05-20 15:36:53 -07006185 // Inherit kAccClassIsFinalizable from the superclass in case this
6186 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006187 if (super->IsFinalizable()) {
6188 klass->SetFinalizable();
6189 }
6190
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006191 // Inherit class loader flag form super class.
6192 if (super->IsClassLoaderClass()) {
6193 klass->SetClassLoaderClass();
6194 }
6195
Elliott Hughes2da50362011-10-10 16:57:08 -07006196 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006197 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006198 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006199 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006200 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006201 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006202 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006203 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006204 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006205 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006206 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006207 return false;
6208 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006209
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006210 if (kIsDebugBuild) {
6211 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006212 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006213 CHECK(super->IsResolved());
6214 super = super->GetSuperClass();
6215 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006216 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006217 return true;
6218}
6219
Vladimir Marko782fb712020-12-23 12:47:31 +00006220// A wrapper class representing the result of a method translation used for linking methods and
6221// updating superclass default methods. For each method in a classes vtable there are 4 states it
6222// could be in:
6223// 1) No translation is necessary. In this case there is no MethodTranslation object for it. This
6224// is the standard case and is true when the method is not overridable by a default method,
6225// the class defines a concrete implementation of the method, the default method implementation
6226// remains the same, or an abstract method stayed abstract.
6227// 2) The method must be translated to a different default method. We note this with
6228// CreateTranslatedMethod.
6229// 3) The method must be replaced with a conflict method. This happens when a superclass
6230// implements an interface with a default method and this class implements an unrelated
6231// interface that also defines that default method. We note this with CreateConflictingMethod.
6232// 4) The method must be replaced with an abstract miranda method. This happens when a superclass
6233// implements an interface with a default method and this class implements a subinterface of
6234// the superclass's interface which declares the default method abstract. We note this with
6235// CreateAbstractMethod.
6236//
6237// When a method translation is unnecessary (case #1), we don't put it into the
6238// default_translation maps. So an instance of MethodTranslation must be in one of #2-#4.
6239class ClassLinker::MethodTranslation {
6240 public:
6241 MethodTranslation() : translation_(nullptr), type_(Type::kInvalid) {}
6242
6243 // This slot must become a default conflict method.
6244 static MethodTranslation CreateConflictingMethod() {
6245 return MethodTranslation(Type::kConflict, /*translation=*/nullptr);
6246 }
6247
6248 // This slot must become an abstract method.
6249 static MethodTranslation CreateAbstractMethod() {
6250 return MethodTranslation(Type::kAbstract, /*translation=*/nullptr);
6251 }
6252
6253 // Use the given method as the current value for this vtable slot during translation.
6254 static MethodTranslation CreateTranslatedMethod(ArtMethod* new_method) {
6255 return MethodTranslation(Type::kTranslation, new_method);
6256 }
6257
6258 // Returns true if this is a method that must become a conflict method.
6259 bool IsInConflict() const {
6260 return type_ == Type::kConflict;
6261 }
6262
6263 // Returns true if this is a method that must become an abstract method.
6264 bool IsAbstract() const {
6265 return type_ == Type::kAbstract;
6266 }
6267
6268 // Returns true if this is a method that must become a different method.
6269 bool IsTranslation() const {
6270 return type_ == Type::kTranslation;
6271 }
6272
6273 // Get the translated version of this method.
6274 ArtMethod* GetTranslation() const {
6275 DCHECK(IsTranslation());
6276 DCHECK(translation_ != nullptr);
6277 return translation_;
6278 }
6279
6280 private:
6281 enum class Type {
6282 kInvalid,
6283 kTranslation,
6284 kConflict,
6285 kAbstract,
6286 };
6287
6288 MethodTranslation(Type type, ArtMethod* translation)
6289 : translation_(translation), type_(type) {}
6290
6291 ArtMethod* translation_;
6292 Type type_;
6293};
6294
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006295// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006296bool ClassLinker::LinkMethods(Thread* self,
6297 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006298 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006299 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006300 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006301 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006302 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6303 // need to have default methods be in the virtuals array of each class but we don't set that up
6304 // until LinkInterfaceMethods.
Vladimir Marko782fb712020-12-23 12:47:31 +00006305 constexpr size_t kBufferSize = 8; // Avoid malloc/free for a few translations.
6306 std::pair<size_t, ClassLinker::MethodTranslation> buffer[kBufferSize];
6307 HashMap<size_t, ClassLinker::MethodTranslation> default_translations(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07006308 // Link virtual methods then interface methods.
6309 // We set up the interface lookup table first because we need it to determine if we need to update
6310 // any vtable entries with new default method implementations.
6311 return SetupInterfaceLookupTable(self, klass, interfaces)
6312 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006313 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006314}
6315
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006316// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6317// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6318// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006319class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006320 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006321 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006322 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006323 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6324 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006325 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006326 }
6327
6328 const char* GetName() {
6329 if (name_ == nullptr) {
6330 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6331 }
6332 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006333 }
6334
Mathieu Chartiere401d142015-04-22 13:56:20 -07006335 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006336 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006337 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006338 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006339 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006340 if (dex_file_ == other_dex_file) {
6341 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6342 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006343 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006344 uint32_t other_name_len;
6345 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6346 &other_name_len);
6347 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6348 return false;
6349 }
6350 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6351 }
6352
6353 private:
6354 // Dex file for the method to compare against.
6355 const DexFile* const dex_file_;
6356 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006357 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006358 // Lazily computed name from the dex file's strings.
6359 const char* name_;
6360 // Lazily computed name length.
6361 uint32_t name_len_;
6362};
6363
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006364class LinkVirtualHashTable {
6365 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006366 LinkVirtualHashTable(Handle<mirror::Class> klass,
6367 size_t hash_size,
6368 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006369 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006370 : klass_(klass),
6371 hash_size_(hash_size),
6372 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006373 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006374 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6375 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006376
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006377 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006378 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6379 virtual_method_index, image_pointer_size_);
6380 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006381 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006382 uint32_t index = hash % hash_size_;
6383 // Linear probe until we have an empty slot.
6384 while (hash_table_[index] != invalid_index_) {
6385 if (++index == hash_size_) {
6386 index = 0;
6387 }
6388 }
6389 hash_table_[index] = virtual_method_index;
6390 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006391
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006392 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006393 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006394 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006395 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006396 size_t index = hash % hash_size_;
6397 while (true) {
6398 const uint32_t value = hash_table_[index];
6399 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6400 // the block and can safely assume not found.
6401 if (value == invalid_index_) {
6402 break;
6403 }
6404 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006405 ArtMethod* virtual_method =
6406 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6407 if (comparator->HasSameNameAndSignature(
6408 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006409 hash_table_[index] = removed_index_;
6410 return value;
6411 }
6412 }
6413 if (++index == hash_size_) {
6414 index = 0;
6415 }
6416 }
6417 return GetNotFoundIndex();
6418 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006419
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006420 static uint32_t GetNotFoundIndex() {
6421 return invalid_index_;
6422 }
6423
6424 private:
6425 static const uint32_t invalid_index_;
6426 static const uint32_t removed_index_;
6427
6428 Handle<mirror::Class> klass_;
6429 const size_t hash_size_;
6430 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006431 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006432};
6433
6434const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6435const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6436
Stephen Hines1ddd9132017-02-08 01:51:18 -08006437bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006438 Thread* self,
6439 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00006440 /*out*/HashMap<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006441 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006442 if (klass->IsInterface()) {
6443 // No vtable.
6444 if (!IsUint<16>(num_virtual_methods)) {
6445 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6446 return false;
6447 }
6448 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006449 // Assign each method an IMT index and set the default flag.
6450 for (size_t i = 0; i < num_virtual_methods; ++i) {
6451 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6452 m->SetMethodIndex(i);
6453 if (!m->IsAbstract()) {
Vladimir Marko1c993cd2020-05-28 09:30:06 +00006454 // If the dex file does not support default methods, throw ClassFormatError.
6455 // This check is necessary to protect from odd cases, such as native default
6456 // methods, that the dex file verifier permits for old dex file versions. b/157170505
6457 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
6458 // currently running CTS tests for default methods with dex file version 035 which
6459 // does not support default methods. So, we limit this to native methods. b/157718952
6460 if (m->IsNative()) {
6461 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
6462 ThrowClassFormatError(klass.Get(),
6463 "Dex file does not support default method '%s'",
6464 m->PrettyMethod().c_str());
6465 return false;
6466 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006467 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6468 has_defaults = true;
6469 }
6470 }
6471 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6472 // during initialization. This is a performance optimization. We could simply traverse the
6473 // virtual_methods_ array again during initialization.
6474 if (has_defaults) {
6475 klass->SetHasDefaultMethods();
6476 }
6477 return true;
6478 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006479 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6480 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006481 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006482 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006483 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006484 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006485 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006486 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006487 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006488 return false;
6489 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006490 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006491 vtable->SetElementPtrSize(
6492 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006493 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006494 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6495 // might give us new default methods). If no new interfaces then we can skip the rest since
6496 // the class cannot override any of the super-class's methods. This is required for
6497 // correctness since without it we might not update overridden default method vtable entries
6498 // correctly.
6499 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006500 klass->SetVTable(vtable.Get());
6501 return true;
6502 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006503 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006504 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006505 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006506 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006507 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6508 // might give us new default methods). See comment above.
6509 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006510 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006511 return true;
6512 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006513 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6514 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006515 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006516 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006517 return false;
6518 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006519 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006520 // How the algorithm works:
6521 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6522 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6523 // method which has not been matched to a vtable method, and j if the virtual method at the
6524 // index overrode the super virtual method at index j.
6525 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6526 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6527 // the need for the initial vtable which we later shrink back down).
6528 // 3. Add non overridden methods to the end of the vtable.
6529 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006530 // + 1 so that even if we only have new default methods we will still be able to use this hash
6531 // table (i.e. it will never have 0 size).
6532 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006533 uint32_t* hash_table_ptr;
6534 std::unique_ptr<uint32_t[]> hash_heap_storage;
6535 if (hash_table_size <= kMaxStackHash) {
6536 hash_table_ptr = reinterpret_cast<uint32_t*>(
6537 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6538 } else {
6539 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6540 hash_table_ptr = hash_heap_storage.get();
6541 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006542 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006543 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006544 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006545 DCHECK(klass->GetVirtualMethodDuringLinking(
6546 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006547 hash_table.Add(i);
6548 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006549 // 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 -07006550 // the hash table.
6551 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006552 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006553 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006554 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6555 super_method->GetAccessFlags())) {
6556 // Continue on to the next method since this one is package private and canot be overridden.
6557 // Before Android 4.1, the package-private method super_method might have been incorrectly
6558 // overridden.
6559 continue;
6560 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006561 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006562 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006563 // We remove the method so that subsequent lookups will be faster by making the hash-map
6564 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006565 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6566 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006567 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6568 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006569 if (super_method->IsFinal()) {
6570 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6571 virtual_method->PrettyMethod().c_str(),
6572 super_method->GetDeclaringClassDescriptor());
6573 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006574 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006575 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6576 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006577 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006578 // We didn't directly override this method but we might through default methods...
6579 // Check for default method update.
6580 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006581 switch (FindDefaultMethodImplementation(self,
6582 super_method,
6583 klass,
6584 /*out*/&default_method)) {
6585 case DefaultMethodSearchResult::kDefaultConflict: {
6586 // A conflict was found looking for default methods. Note this (assuming it wasn't
6587 // pre-existing) in the translations map.
6588 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6589 // Don't generate another conflict method to reduce memory use as an optimization.
6590 default_translations->insert(
6591 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6592 }
6593 break;
6594 }
6595 case DefaultMethodSearchResult::kAbstractFound: {
6596 // No conflict but method is abstract.
6597 // We note that this vtable entry must be made abstract.
6598 if (UNLIKELY(!super_method->IsAbstract())) {
6599 default_translations->insert(
6600 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6601 }
6602 break;
6603 }
6604 case DefaultMethodSearchResult::kDefaultFound: {
6605 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6606 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6607 // Found a default method implementation that is new.
6608 // TODO Refactor this add default methods to virtuals here and not in
6609 // LinkInterfaceMethods maybe.
6610 // The problem is default methods might override previously present
6611 // default-method or miranda-method vtable entries from the superclass.
6612 // Unfortunately we need these to be entries in this class's virtuals. We do not
6613 // give these entries there until LinkInterfaceMethods so we pass this map around
6614 // to let it know which vtable entries need to be updated.
6615 // Make a note that vtable entry j must be updated, store what it needs to be updated
6616 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6617 // then.
6618 default_translations->insert(
6619 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006620 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6621 << " overridden by default "
6622 << default_method->PrettyMethod()
6623 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006624 }
6625 break;
6626 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006627 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006628 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006629 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006630 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006631 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006632 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006633 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006634 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6635 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006636 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006637 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006638 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006639 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006640 local_method->SetMethodIndex(actual_count);
6641 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006642 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006643 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006644 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006645 return false;
6646 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006647 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006648 CHECK_LE(actual_count, max_count);
6649 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006650 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6651 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006652 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006653 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006654 return false;
6655 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006656 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006657 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006658 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006659 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006660 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006661 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6662 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006663 return false;
6664 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006665 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006666 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006667 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006668 return false;
6669 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006670 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006671 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6672 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006673 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006674 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006675 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006676 }
6677 return true;
6678}
6679
Alex Light9139e002015-10-09 15:59:48 -07006680// Determine if the given iface has any subinterface in the given list that declares the method
6681// specified by 'target'.
6682//
6683// Arguments
6684// - self: The thread we are running on
6685// - target: A comparator that will match any method that overrides the method we are checking for
6686// - iftable: The iftable we are searching for an overriding method on.
6687// - ifstart: The index of the interface we are checking to see if anything overrides
6688// - iface: The interface we are checking to see if anything overrides.
6689// - image_pointer_size:
6690// The image pointer size.
6691//
6692// Returns
6693// - True: There is some method that matches the target comparator defined in an interface that
6694// is a subtype of iface.
6695// - False: There is no method that matches the target comparator in any interface that is a subtype
6696// of iface.
6697static bool ContainsOverridingMethodOf(Thread* self,
6698 MethodNameAndSignatureComparator& target,
6699 Handle<mirror::IfTable> iftable,
6700 size_t ifstart,
6701 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006702 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006703 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006704 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006705 DCHECK(iface != nullptr);
6706 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006707 DCHECK_GE(ifstart, 0u);
6708 DCHECK_LT(ifstart, iftable->Count());
6709 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6710 DCHECK(iface->IsInterface());
6711
6712 size_t iftable_count = iftable->Count();
6713 StackHandleScope<1> hs(self);
6714 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6715 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6716 // Skip ifstart since our current interface obviously cannot override itself.
6717 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006718 // Iterate through every method on this interface. The order does not matter.
6719 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006720 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006721 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006722 // Check if the i'th interface is a subtype of this one.
6723 if (iface->IsAssignableFrom(current_iface.Get())) {
6724 return true;
6725 }
6726 break;
6727 }
6728 }
6729 }
6730 return false;
6731}
6732
Alex Lighteb7c1442015-08-31 13:17:42 -07006733// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006734// out_default_method and returns kDefaultFound on success. If no default method was found return
6735// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6736// default_method conflict) it will return kDefaultConflict.
6737ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6738 Thread* self,
6739 ArtMethod* target_method,
6740 Handle<mirror::Class> klass,
6741 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006742 DCHECK(self != nullptr);
6743 DCHECK(target_method != nullptr);
6744 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006745
6746 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006747
6748 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6749 // table. This lets us walk the table backwards when searching for default methods. The first one
6750 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6751 // track of it and then continue checking all other interfaces, since we need to throw an error if
6752 // we encounter conflicting default method implementations (one is not a subtype of the other).
6753 //
6754 // The order of unrelated interfaces does not matter and is not defined.
6755 size_t iftable_count = klass->GetIfTableCount();
6756 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006757 // No interfaces. We have already reset out to null so just return kAbstractFound.
6758 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006759 }
6760
Alex Light9139e002015-10-09 15:59:48 -07006761 StackHandleScope<3> hs(self);
6762 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006763 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006764 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006765 MethodNameAndSignatureComparator target_name_comparator(
6766 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6767 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006768 for (size_t k = iftable_count; k != 0; ) {
6769 --k;
6770
Alex Lighteb7c1442015-08-31 13:17:42 -07006771 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006772
6773 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006774 // Iterate through every declared method on this interface. The order does not matter.
6775 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6776 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006777 // Skip abstract methods and methods with different names.
6778 if (current_method->IsAbstract() ||
6779 !target_name_comparator.HasSameNameAndSignature(
6780 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6781 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006782 } else if (!current_method->IsPublic()) {
6783 // The verifier should have caught the non-public method for dex version 37. Just warn and
6784 // skip it since this is from before default-methods so we don't really need to care that it
6785 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006786 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6787 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006788 << "This will be a fatal error in subsequent versions of android. "
6789 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006790 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006791 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006792 // We have multiple default impls of the same method. This is a potential default conflict.
6793 // We need to check if this possibly conflicting method is either a superclass of the chosen
6794 // default implementation or is overridden by a non-default interface method. In either case
6795 // there is no conflict.
6796 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6797 !ContainsOverridingMethodOf(self,
6798 target_name_comparator,
6799 iftable,
6800 k,
6801 iface,
6802 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006803 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006804 << current_method->PrettyMethod() << " and "
6805 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6806 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006807 *out_default_method = nullptr;
6808 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006809 } else {
6810 break; // Continue checking at the next interface.
6811 }
6812 } else {
Alex Light9139e002015-10-09 15:59:48 -07006813 // chosen_iface == null
6814 if (!ContainsOverridingMethodOf(self,
6815 target_name_comparator,
6816 iftable,
6817 k,
6818 iface,
6819 image_pointer_size_)) {
6820 // Don't set this as the chosen interface if something else is overriding it (because that
6821 // other interface would be potentially chosen instead if it was default). If the other
6822 // interface was abstract then we wouldn't select this interface as chosen anyway since
6823 // the abstract method masks it.
6824 *out_default_method = current_method;
6825 chosen_iface.Assign(iface.Get());
6826 // We should now finish traversing the graph to find if we have default methods that
6827 // conflict.
6828 } else {
David Sehr709b0702016-10-13 09:12:37 -07006829 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6830 << "' was "
6831 << "skipped because it was overridden by an abstract method in a "
6832 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006833 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006834 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006835 break;
6836 }
6837 }
Alex Light9139e002015-10-09 15:59:48 -07006838 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006839 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6840 << "' selected "
6841 << "as the implementation for '" << target_method->PrettyMethod()
6842 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006843 return DefaultMethodSearchResult::kDefaultFound;
6844 } else {
6845 return DefaultMethodSearchResult::kAbstractFound;
6846 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006847}
6848
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006849ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006850 ArtMethod* conflict_method,
6851 ArtMethod* interface_method,
6852 ArtMethod* method,
6853 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006854 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006855 Runtime* const runtime = Runtime::Current();
6856 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6857 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6858
6859 // Create a new entry if the existing one is the shared conflict method.
6860 ArtMethod* new_conflict_method = new_entry
6861 ? runtime->CreateImtConflictMethod(linear_alloc)
6862 : conflict_method;
6863
6864 // Allocate a new table. Note that we will leak this table at the next conflict,
6865 // but that's a tradeoff compared to making the table fixed size.
6866 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006867 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6868 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006869 if (data == nullptr) {
6870 LOG(ERROR) << "Failed to allocate conflict table";
6871 return conflict_method;
6872 }
6873 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6874 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006875 method,
6876 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006877
6878 // Do a fence to ensure threads see the data in the table before it is assigned
6879 // to the conflict method.
6880 // Note that there is a race in the presence of multiple threads and we may leak
6881 // memory from the LinearAlloc, but that's a tradeoff compared to using
6882 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006883 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006884 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006885 return new_conflict_method;
6886}
6887
Vladimir Marko921094a2017-01-12 18:37:06 +00006888bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6889 Handle<mirror::Class> klass,
6890 Handle<mirror::IfTable> iftable) {
6891 DCHECK(!klass->IsInterface());
6892 const bool has_superclass = klass->HasSuperClass();
6893 const bool extend_super_iftable = has_superclass;
6894 const size_t ifcount = klass->GetIfTableCount();
6895 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6896 for (size_t i = 0; i < ifcount; ++i) {
6897 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6898 if (num_methods > 0) {
6899 const bool is_super = i < super_ifcount;
6900 // This is an interface implemented by a super-class. Therefore we can just copy the method
6901 // array from the superclass.
6902 const bool super_interface = is_super && extend_super_iftable;
6903 ObjPtr<mirror::PointerArray> method_array;
6904 if (super_interface) {
6905 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6906 DCHECK(if_table != nullptr);
6907 DCHECK(if_table->GetMethodArray(i) != nullptr);
6908 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006909 StackHandleScope<1u> hs(self);
6910 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6911 method_array =
6912 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006913 } else {
6914 method_array = AllocPointerArray(self, num_methods);
6915 }
6916 if (UNLIKELY(method_array == nullptr)) {
6917 self->AssertPendingOOMException();
6918 return false;
6919 }
6920 iftable->SetMethodArray(i, method_array);
6921 }
6922 }
6923 return true;
6924}
6925
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006926void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6927 ArtMethod* imt_conflict_method,
6928 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006929 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006930 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006931 // Place method in imt if entry is empty, place conflict otherwise.
6932 if (*imt_ref == unimplemented_method) {
6933 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006934 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006935 // If we are not a conflict and we have the same signature and name as the imt
6936 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006937 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6938 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006939 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006940 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006941 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006942 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006943 *imt_ref = current_method;
6944 } else {
Alex Light9139e002015-10-09 15:59:48 -07006945 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006946 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006947 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006948 } else {
6949 // Place the default conflict method. Note that there may be an existing conflict
6950 // method in the IMT, but it could be one tailored to the super class, with a
6951 // specific ImtConflictTable.
6952 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006953 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006954 }
6955}
6956
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006957void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006958 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6959 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006960 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006961 Runtime* const runtime = Runtime::Current();
6962 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6963 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006964 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006965 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006966 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006967 FillIMTFromIfTable(klass->GetIfTable(),
6968 unimplemented_method,
6969 conflict_method,
6970 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006971 /*create_conflict_tables=*/true,
6972 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006973 &new_conflict,
6974 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006975 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006976 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6977 // we can just use the same pointer.
6978 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006979 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006980 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6981 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6982 bool same = true;
6983 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6984 ArtMethod* method = imt_data[i];
6985 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6986 if (method != super_method) {
6987 bool is_conflict_table = method->IsRuntimeMethod() &&
6988 method != unimplemented_method &&
6989 method != conflict_method;
6990 // Verify conflict contents.
6991 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6992 super_method != unimplemented_method &&
6993 super_method != conflict_method;
6994 if (!is_conflict_table || !super_conflict_table) {
6995 same = false;
6996 } else {
6997 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6998 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6999 same = same && table1->Equals(table2, image_pointer_size_);
7000 }
7001 }
7002 }
7003 if (same) {
7004 imt = super_imt;
7005 }
7006 }
7007 if (imt == nullptr) {
7008 imt = klass->GetImt(image_pointer_size_);
7009 DCHECK(imt != nullptr);
7010 imt->Populate(imt_data, image_pointer_size_);
7011 } else {
7012 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007013 }
7014}
7015
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007016ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
7017 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07007018 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007019 void* data = linear_alloc->Alloc(Thread::Current(),
7020 ImtConflictTable::ComputeSize(count,
7021 image_pointer_size));
7022 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
7023}
7024
7025ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
7026 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
7027}
7028
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007029void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007030 ArtMethod* unimplemented_method,
7031 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007032 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007033 bool create_conflict_tables,
7034 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007035 /*out*/bool* new_conflict,
7036 /*out*/ArtMethod** imt) {
7037 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007038 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007039 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007040 const size_t num_virtuals = interface->NumVirtualMethods();
7041 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7042 // Virtual methods can be larger than the if table methods if there are default methods.
7043 DCHECK_GE(num_virtuals, method_array_count);
7044 if (kIsDebugBuild) {
7045 if (klass->IsInterface()) {
7046 DCHECK_EQ(method_array_count, 0u);
7047 } else {
7048 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
7049 }
7050 }
7051 if (method_array_count == 0) {
7052 continue;
7053 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007054 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007055 for (size_t j = 0; j < method_array_count; ++j) {
7056 ArtMethod* implementation_method =
7057 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7058 if (ignore_copied_methods && implementation_method->IsCopied()) {
7059 continue;
7060 }
7061 DCHECK(implementation_method != nullptr);
7062 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7063 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7064 // or interface methods in the IMT here they will not create extra conflicts since we compare
7065 // names and signatures in SetIMTRef.
7066 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007067 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007068
7069 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7070 // the same implementation method, keep track of this to avoid creating a conflict table in
7071 // this case.
7072
7073 // Conflict table size for each IMT slot.
7074 ++conflict_counts[imt_index];
7075
7076 SetIMTRef(unimplemented_method,
7077 imt_conflict_method,
7078 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007079 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007080 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007081 }
7082 }
7083
7084 if (create_conflict_tables) {
7085 // Create the conflict tables.
7086 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007087 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007088 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007089 if (imt[i] == imt_conflict_method) {
7090 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7091 if (new_table != nullptr) {
7092 ArtMethod* new_conflict_method =
7093 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7094 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7095 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007096 } else {
7097 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007098 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007099 }
7100 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007101 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007102 }
7103 }
7104
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007105 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007106 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007107 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7108 // Virtual methods can be larger than the if table methods if there are default methods.
7109 if (method_array_count == 0) {
7110 continue;
7111 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007112 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007113 for (size_t j = 0; j < method_array_count; ++j) {
7114 ArtMethod* implementation_method =
7115 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7116 if (ignore_copied_methods && implementation_method->IsCopied()) {
7117 continue;
7118 }
7119 DCHECK(implementation_method != nullptr);
7120 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007121 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007122 if (!imt[imt_index]->IsRuntimeMethod() ||
7123 imt[imt_index] == unimplemented_method ||
7124 imt[imt_index] == imt_conflict_method) {
7125 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007126 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007127 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7128 const size_t num_entries = table->NumEntries(image_pointer_size_);
7129 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7130 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007131 }
7132 }
7133 }
7134}
7135
Alex Lighteb7c1442015-08-31 13:17:42 -07007136// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7137// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007138static bool NotSubinterfaceOfAny(
Vladimir Marko782fb712020-12-23 12:47:31 +00007139 const HashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007140 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007141 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007142 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007143 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007144 for (ObjPtr<mirror::Class> c : classes) {
7145 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007146 return false;
7147 }
7148 }
7149 return true;
7150}
7151
7152// Fills in and flattens the interface inheritance hierarchy.
7153//
7154// By the end of this function all interfaces in the transitive closure of to_process are added to
7155// the iftable and every interface precedes all of its sub-interfaces in this list.
7156//
7157// all I, J: Interface | I <: J implies J precedes I
7158//
7159// (note A <: B means that A is a subtype of B)
7160//
7161// This returns the total number of items in the iftable. The iftable might be resized down after
7162// this call.
7163//
7164// We order this backwards so that we do not need to reorder superclass interfaces when new
7165// interfaces are added in subclass's interface tables.
7166//
7167// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7168// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7169// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7170// iftable must be large enough to hold all interfaces without changing its size.
Vladimir Marko782fb712020-12-23 12:47:31 +00007171static size_t FillIfTable(Thread* self,
7172 ObjPtr<mirror::Class> klass,
7173 ObjPtr<mirror::ObjectArray<mirror::Class>> interfaces,
7174 ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007175 size_t super_ifcount,
Vladimir Marko782fb712020-12-23 12:47:31 +00007176 size_t num_interfaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007177 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00007178 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
7179 // This is the set of all classes already in the iftable. Used to make checking
7180 // if a class has already been added quicker.
7181 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
7182 mirror::Class* buffer[kBufferSize];
7183 HashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07007184 // The first super_ifcount elements are from the superclass. We note that they are already added.
7185 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007186 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007187 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007188 classes_in_iftable.insert(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007189 }
7190 size_t filled_ifcount = super_ifcount;
Vladimir Marko782fb712020-12-23 12:47:31 +00007191 const bool have_interfaces = interfaces != nullptr;
7192 for (size_t i = 0; i != num_interfaces; ++i) {
7193 ObjPtr<mirror::Class> interface = have_interfaces
7194 ? interfaces->Get(i)
7195 : mirror::Class::GetDirectInterface(self, klass, i);
7196
Alex Lighteb7c1442015-08-31 13:17:42 -07007197 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7198 // At this point in the loop current-iface-list has the invariant that:
7199 // for every pair of interfaces I,J within it:
7200 // if index_of(I) < index_of(J) then I is not a subtype of J
7201
7202 // If we have already seen this element then all of its super-interfaces must already be in the
7203 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00007204 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007205 // We haven't seen this interface so add all of its super-interfaces onto the
7206 // current-iface-list, skipping those already on it.
7207 int32_t ifcount = interface->GetIfTableCount();
7208 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007209 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007210 if (!ContainsElement(classes_in_iftable, super_interface)) {
7211 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007212 classes_in_iftable.insert(super_interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007213 iftable->SetInterface(filled_ifcount, super_interface);
7214 filled_ifcount++;
7215 }
7216 }
7217 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7218 // Place this interface onto the current-iface-list after all of its super-interfaces.
Vladimir Marko782fb712020-12-23 12:47:31 +00007219 classes_in_iftable.insert(interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007220 iftable->SetInterface(filled_ifcount, interface);
7221 filled_ifcount++;
7222 } else if (kIsDebugBuild) {
7223 // Check all super-interfaces are already in the list.
7224 int32_t ifcount = interface->GetIfTableCount();
7225 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007226 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007227 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007228 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7229 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007230 }
7231 }
7232 }
7233 if (kIsDebugBuild) {
7234 // Check that the iftable is ordered correctly.
7235 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007236 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007237 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007238 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007239 // !(if_a <: if_b)
7240 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007241 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7242 << ") extends "
7243 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007244 << "interface list.";
7245 }
7246 }
7247 }
7248 return filled_ifcount;
7249}
7250
Vladimir Marko782fb712020-12-23 12:47:31 +00007251bool ClassLinker::SetupInterfaceLookupTable(Thread* self,
7252 Handle<mirror::Class> klass,
Alex Lighteb7c1442015-08-31 13:17:42 -07007253 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7254 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007255 const bool has_superclass = klass->HasSuperClass();
7256 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007257 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007258 const size_t num_interfaces =
7259 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007260 if (num_interfaces == 0) {
7261 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007262 if (LIKELY(has_superclass)) {
7263 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7264 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007265 // Class implements no interfaces.
7266 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007267 return true;
7268 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007269 // Class implements same interfaces as parent, are any of these not marker interfaces?
7270 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007271 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007272 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007273 if (super_iftable->GetMethodArrayCount(i) > 0) {
7274 has_non_marker_interface = true;
7275 break;
7276 }
7277 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007278 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007279 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007280 klass->SetIfTable(super_iftable);
7281 return true;
7282 }
7283 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007284 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007285 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007286 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007287 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007288 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007289 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007290 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007291 if (UNLIKELY(!interface->IsInterface())) {
7292 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007293 ThrowIncompatibleClassChangeError(klass.Get(),
7294 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007295 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007296 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7297 return false;
7298 }
7299 ifcount += interface->GetIfTableCount();
7300 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007301 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007302 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007303 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007304 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007305 return false;
7306 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007307 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007308 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007309 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007310 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007311 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007312 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007313 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007314 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007315
7316 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7317 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7318 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007319 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007320
Vladimir Marko782fb712020-12-23 12:47:31 +00007321 const size_t new_ifcount = FillIfTable(
7322 self, klass.Get(), interfaces.Get(), iftable.Get(), super_ifcount, num_interfaces);
Alex Lighteb7c1442015-08-31 13:17:42 -07007323
Ian Rogers7b078e82014-09-10 14:44:24 -07007324 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007325
Ian Rogersb52b01a2012-01-12 17:01:38 -08007326 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007327 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007328 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007329 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007330 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007331 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007332 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007333 return false;
7334 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007335 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007336 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007337 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007338 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007339 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007340 return true;
7341}
7342
Alex Light1f3925d2016-09-07 12:04:20 -07007343// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7344// of methods must be unique.
7345static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7346 return nullptr;
7347}
7348
7349template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007350static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007351 const ScopedArenaVector<ArtMethod*>& list,
7352 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007353 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007354 for (ArtMethod* method : list) {
7355 if (cmp.HasSameNameAndSignature(method)) {
7356 return method;
7357 }
7358 }
Alex Light1f3925d2016-09-07 12:04:20 -07007359 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007360}
7361
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007362namespace {
7363
Alex Light1f3925d2016-09-07 12:04:20 -07007364// Check that all vtable entries are present in this class's virtuals or are the same as a
7365// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007366void CheckClassOwnsVTableEntries(Thread* self,
7367 Handle<mirror::Class> klass,
7368 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007369 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007370 StackHandleScope<2> hs(self);
7371 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007372 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007373 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007374 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007375 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7376 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7377 CHECK(m != nullptr);
7378
Alex Lighta41a30782017-03-29 11:33:19 -07007379 if (m->GetMethodIndexDuringLinking() != i) {
7380 LOG(WARNING) << m->PrettyMethod()
7381 << " has an unexpected method index for its spot in the vtable for class"
7382 << klass->PrettyClass();
7383 }
Alex Lighte64300b2015-12-15 15:02:47 -08007384 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7385 auto is_same_method = [m] (const ArtMethod& meth) {
7386 return &meth == m;
7387 };
Alex Light3f980532017-03-17 15:10:32 -07007388 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7389 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7390 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7391 << klass->PrettyClass() << " or any of its superclasses!";
7392 }
Alex Lighte64300b2015-12-15 15:02:47 -08007393 }
7394}
7395
Alex Light1f3925d2016-09-07 12:04:20 -07007396// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7397// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007398template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007399void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007400 REQUIRES_SHARED(Locks::mutator_lock_) {
7401 StackHandleScope<1> hs(self);
7402 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7403 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007404
7405 // Observations:
7406 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7407 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7408 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7409 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7410 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7411 // * The single-pass algorithm will trade memory for speed, but that is OK.
7412
7413 CHECK_GT(num_entries, 0);
7414
7415 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7416 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7417 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7418 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7419 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7420 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7421 << m2->PrettyMethod() << " (0x" << std::hex
7422 << reinterpret_cast<uintptr_t>(m2) << ")";
7423 };
7424 struct BaseHashType {
7425 static size_t HashCombine(size_t seed, size_t val) {
7426 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7427 }
7428 };
7429
7430 // Check assuming all entries come from the same dex file.
7431 {
7432 // Find the first interesting method and its dex file.
7433 int32_t start = 0;
7434 for (; start < num_entries; ++start) {
7435 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7436 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7437 // maybe).
7438 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7439 vtable_entry->GetAccessFlags())) {
7440 continue;
7441 }
7442 break;
7443 }
7444 if (start == num_entries) {
7445 return;
7446 }
7447 const DexFile* dex_file =
7448 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7449 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7450
7451 // Helper function to avoid logging if we have to run the cross-file checks.
7452 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7453 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7454 using PairType = std::pair<uint32_t, uint16_t>;
7455 struct PairHash : BaseHashType {
7456 size_t operator()(const PairType& key) const {
7457 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7458 }
7459 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007460 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007461 seen.reserve(2 * num_entries);
7462 bool need_slow_path = false;
7463 bool found_dup = false;
7464 for (int i = start; i < num_entries; ++i) {
7465 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7466 // wrt/ kPointerSize.
7467 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7468 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7469 vtable_entry->GetAccessFlags())) {
7470 continue;
7471 }
7472 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7473 if (dex_file != m->GetDexFile()) {
7474 need_slow_path = true;
7475 break;
7476 }
7477 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7478 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7479 auto it = seen.find(pair);
7480 if (it != seen.end()) {
7481 found_dup = true;
7482 if (log_warn) {
7483 log_fn(it->second, i);
7484 }
7485 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007486 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007487 }
7488 }
7489 return std::make_pair(need_slow_path, found_dup);
7490 };
7491 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7492 if (!result.first) {
7493 if (result.second) {
7494 check_fn(/* log_warn= */ true);
7495 }
7496 return;
7497 }
7498 }
7499
7500 // Need to check across dex files.
7501 struct Entry {
7502 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00007503 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007504 const char* name = nullptr;
7505 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007506
Vladimir Marko782fb712020-12-23 12:47:31 +00007507 Entry() = default;
7508 Entry(const Entry& other) = default;
7509 Entry& operator=(const Entry& other) = default;
7510
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007511 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00007512 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
7513 // This call writes `name_len` and it is therefore necessary that the
7514 // initializer for `name_len` comes before it, otherwise the value
7515 // from the call would be overwritten by that initializer.
7516 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007517 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00007518 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
7519 if (name[name_len] != 0) {
7520 name_len += strlen(name + name_len);
7521 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007522 }
7523
7524 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00007525 return name_len == other.name_len &&
7526 memcmp(name, other.name, name_len) == 0 &&
7527 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007528 }
7529 };
7530 struct EntryHash {
7531 size_t operator()(const Entry& key) const {
7532 return key.cached_hash;
7533 }
7534 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007535 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007536 for (int32_t i = 0; i < num_entries; ++i) {
7537 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7538 // wrt/ kPointerSize.
7539 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7540 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7541 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007542 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7543 vtable_entry->GetAccessFlags())) {
7544 continue;
7545 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007546 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7547 const DexFile* dex_file = m->GetDexFile();
7548 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7549
7550 Entry e(dex_file, mid);
7551
7552 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7553 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7554 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7555 sig_hash);
7556
7557 auto it = map.find(e);
7558 if (it != map.end()) {
7559 log_fn(it->second, i);
7560 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007561 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07007562 }
7563 }
7564}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007565
7566void CheckVTableHasNoDuplicates(Thread* self,
7567 Handle<mirror::Class> klass,
7568 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007569 REQUIRES_SHARED(Locks::mutator_lock_) {
7570 switch (pointer_size) {
7571 case PointerSize::k64:
7572 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7573 break;
7574 case PointerSize::k32:
7575 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7576 break;
7577 }
7578}
Alex Light1f3925d2016-09-07 12:04:20 -07007579
Orion Hodson5880c772020-07-28 20:12:08 +01007580static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07007581 REQUIRES_SHARED(Locks::mutator_lock_) {
7582 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7583 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7584}
7585
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007586} // namespace
7587
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007588void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7589 ArtMethod* unimplemented_method,
7590 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007591 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007592 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007593 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007594 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007595 if (super_class->ShouldHaveImt()) {
7596 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7597 for (size_t i = 0; i < ImTable::kSize; ++i) {
7598 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007599 }
7600 } else {
7601 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007602 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007603 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007604 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007605 FillIMTFromIfTable(if_table,
7606 unimplemented_method,
7607 imt_conflict_method,
7608 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007609 /*create_conflict_tables=*/false,
7610 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007611 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007612 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007613 }
7614 }
7615}
7616
Vladimir Marko921094a2017-01-12 18:37:06 +00007617class ClassLinker::LinkInterfaceMethodsHelper {
7618 public:
7619 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7620 Handle<mirror::Class> klass,
7621 Thread* self,
7622 Runtime* runtime)
7623 : class_linker_(class_linker),
7624 klass_(klass),
7625 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7626 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7627 self_(self),
7628 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7629 allocator_(&stack_),
7630 default_conflict_methods_(allocator_.Adapter()),
7631 overriding_default_conflict_methods_(allocator_.Adapter()),
7632 miranda_methods_(allocator_.Adapter()),
7633 default_methods_(allocator_.Adapter()),
7634 overriding_default_methods_(allocator_.Adapter()),
7635 move_table_(allocator_.Adapter()) {
7636 }
7637
7638 ArtMethod* FindMethod(ArtMethod* interface_method,
7639 MethodNameAndSignatureComparator& interface_name_comparator,
7640 ArtMethod* vtable_impl)
7641 REQUIRES_SHARED(Locks::mutator_lock_);
7642
7643 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7644 MethodNameAndSignatureComparator& interface_name_comparator)
7645 REQUIRES_SHARED(Locks::mutator_lock_);
7646
7647 bool HasNewVirtuals() const {
7648 return !(miranda_methods_.empty() &&
7649 default_methods_.empty() &&
7650 overriding_default_methods_.empty() &&
7651 overriding_default_conflict_methods_.empty() &&
7652 default_conflict_methods_.empty());
7653 }
7654
7655 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7656
7657 ObjPtr<mirror::PointerArray> UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007658 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007659 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007660
7661 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7662
7663 void UpdateIMT(ArtMethod** out_imt);
7664
7665 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7666 if (kIsDebugBuild) {
7667 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7668 // Check that there are no stale methods are in the dex cache array.
7669 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7670 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007671 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7672 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007673 CHECK(move_table_.find(m) == move_table_.end() ||
7674 // The original versions of copied methods will still be present so allow those too.
7675 // Note that if the first check passes this might fail to GetDeclaringClass().
7676 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7677 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7678 [m] (ArtMethod& meth) {
7679 return &meth == m;
7680 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7681 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7682 }
7683 }
7684 }
7685
7686 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7687 LengthPrefixedArray<ArtMethod>* methods) {
7688 if (kIsDebugBuild) {
7689 CHECK(methods != nullptr);
7690 // Put some random garbage in old methods to help find stale pointers.
7691 if (methods != old_methods && old_methods != nullptr) {
7692 // Need to make sure the GC is not running since it could be scanning the methods we are
7693 // about to overwrite.
7694 ScopedThreadStateChange tsc(self_, kSuspended);
7695 gc::ScopedGCCriticalSection gcs(self_,
7696 gc::kGcCauseClassLinker,
7697 gc::kCollectorTypeClassLinker);
7698 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7699 method_size_,
7700 method_alignment_);
7701 memset(old_methods, 0xFEu, old_size);
7702 }
7703 }
7704 }
7705
7706 private:
7707 size_t NumberOfNewVirtuals() const {
7708 return miranda_methods_.size() +
7709 default_methods_.size() +
7710 overriding_default_conflict_methods_.size() +
7711 overriding_default_methods_.size() +
7712 default_conflict_methods_.size();
7713 }
7714
7715 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7716 return !klass_->IsInterface();
7717 }
7718
7719 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7720 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7721 << "Interfaces should only have default-conflict methods appended to them.";
7722 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7723 << miranda_methods_.size()
7724 << " default_methods=" << default_methods_.size()
7725 << " overriding_default_methods=" << overriding_default_methods_.size()
7726 << " default_conflict_methods=" << default_conflict_methods_.size()
7727 << " overriding_default_conflict_methods="
7728 << overriding_default_conflict_methods_.size();
7729 }
7730
7731 ClassLinker* class_linker_;
7732 Handle<mirror::Class> klass_;
7733 size_t method_alignment_;
7734 size_t method_size_;
7735 Thread* const self_;
7736
7737 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7738 // the virtual methods array.
7739 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7740 // during cross compilation.
7741 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7742 ArenaStack stack_;
7743 ScopedArenaAllocator allocator_;
7744
7745 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7746 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7747 ScopedArenaVector<ArtMethod*> miranda_methods_;
7748 ScopedArenaVector<ArtMethod*> default_methods_;
7749 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7750
7751 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7752};
7753
7754ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7755 ArtMethod* interface_method,
7756 MethodNameAndSignatureComparator& interface_name_comparator,
7757 ArtMethod* vtable_impl) {
7758 ArtMethod* current_method = nullptr;
7759 switch (class_linker_->FindDefaultMethodImplementation(self_,
7760 interface_method,
7761 klass_,
7762 /*out*/&current_method)) {
7763 case DefaultMethodSearchResult::kDefaultConflict: {
7764 // Default method conflict.
7765 DCHECK(current_method == nullptr);
7766 ArtMethod* default_conflict_method = nullptr;
7767 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7768 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7769 default_conflict_method = vtable_impl;
7770 } else {
7771 // See if we already have a conflict method for this method.
7772 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7773 interface_name_comparator,
7774 default_conflict_methods_,
7775 overriding_default_conflict_methods_);
7776 if (LIKELY(preexisting_conflict != nullptr)) {
7777 // We already have another conflict we can reuse.
7778 default_conflict_method = preexisting_conflict;
7779 } else {
7780 // Note that we do this even if we are an interface since we need to create this and
7781 // cannot reuse another classes.
7782 // Create a new conflict method for this to use.
7783 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7784 new(default_conflict_method) ArtMethod(interface_method,
7785 class_linker_->GetImagePointerSize());
7786 if (vtable_impl == nullptr) {
7787 // Save the conflict method. We need to add it to the vtable.
7788 default_conflict_methods_.push_back(default_conflict_method);
7789 } else {
7790 // Save the conflict method but it is already in the vtable.
7791 overriding_default_conflict_methods_.push_back(default_conflict_method);
7792 }
7793 }
7794 }
7795 current_method = default_conflict_method;
7796 break;
7797 } // case kDefaultConflict
7798 case DefaultMethodSearchResult::kDefaultFound: {
7799 DCHECK(current_method != nullptr);
7800 // Found a default method.
7801 if (vtable_impl != nullptr &&
7802 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7803 // We found a default method but it was the same one we already have from our
7804 // superclass. Don't bother adding it to our vtable again.
7805 current_method = vtable_impl;
7806 } else if (LIKELY(FillTables())) {
7807 // Interfaces don't need to copy default methods since they don't have vtables.
7808 // Only record this default method if it is new to save space.
7809 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7810 // would make lookup for interface super much faster. (We would only need to scan
7811 // the iftable to find if there is a NSME or AME.)
7812 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7813 default_methods_,
7814 overriding_default_methods_);
7815 if (old == nullptr) {
7816 // We found a default method implementation and there were no conflicts.
7817 if (vtable_impl == nullptr) {
7818 // Save the default method. We need to add it to the vtable.
7819 default_methods_.push_back(current_method);
7820 } else {
7821 // Save the default method but it is already in the vtable.
7822 overriding_default_methods_.push_back(current_method);
7823 }
7824 } else {
7825 CHECK(old == current_method) << "Multiple default implementations selected!";
7826 }
7827 }
7828 break;
7829 } // case kDefaultFound
7830 case DefaultMethodSearchResult::kAbstractFound: {
7831 DCHECK(current_method == nullptr);
7832 // Abstract method masks all defaults.
7833 if (vtable_impl != nullptr &&
7834 vtable_impl->IsAbstract() &&
7835 !vtable_impl->IsDefaultConflicting()) {
7836 // We need to make this an abstract method but the version in the vtable already is so
7837 // don't do anything.
7838 current_method = vtable_impl;
7839 }
7840 break;
7841 } // case kAbstractFound
7842 }
7843 return current_method;
7844}
7845
7846ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7847 ArtMethod* interface_method,
7848 MethodNameAndSignatureComparator& interface_name_comparator) {
7849 // Find out if there is already a miranda method we can use.
7850 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7851 miranda_methods_);
7852 if (miranda_method == nullptr) {
7853 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7854 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7855 CHECK(miranda_method != nullptr);
7856 // Point the interface table at a phantom slot.
7857 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7858 miranda_methods_.push_back(miranda_method);
7859 }
7860 return miranda_method;
7861}
7862
7863void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7864 LogNewVirtuals();
7865
7866 const size_t old_method_count = klass_->NumMethods();
7867 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7868 DCHECK_NE(old_method_count, new_method_count);
7869
7870 // Attempt to realloc to save RAM if possible.
7871 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7872 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7873 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7874 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7875 // CopyFrom has internal read barriers.
7876 //
7877 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7878 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7879 method_size_,
7880 method_alignment_);
7881 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7882 method_size_,
7883 method_alignment_);
7884 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7885 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007886 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007887 self_, old_methods, old_methods_ptr_size, new_size));
7888 CHECK(methods != nullptr); // Native allocation failure aborts.
7889
7890 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7891 if (methods != old_methods) {
7892 // Maps from heap allocated miranda method to linear alloc miranda method.
7893 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7894 // Copy over the old methods.
7895 for (auto& m : klass_->GetMethods(pointer_size)) {
7896 move_table_.emplace(&m, &*out);
7897 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7898 // barriers when it copies.
7899 out->CopyFrom(&m, pointer_size);
7900 ++out;
7901 }
7902 }
7903 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7904 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7905 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007906 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7907 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007908 ArtMethod& new_method = *out;
7909 new_method.CopyFrom(mir_method, pointer_size);
7910 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7911 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7912 << "Miranda method should be abstract!";
7913 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007914 // Update the entry in the method array, as the array will be used for future lookups,
7915 // where thread suspension is allowed.
7916 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7917 // would not see them.
7918 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007919 ++out;
7920 }
7921 // We need to copy the default methods into our own method table since the runtime requires that
7922 // every method on a class's vtable be in that respective class's virtual method table.
7923 // NOTE This means that two classes might have the same implementation of a method from the same
7924 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7925 // default method found on a class with one found on the declaring interface directly and must
7926 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007927 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7928 &overriding_default_methods_}) {
7929 for (size_t i = 0; i < methods_vec->size(); ++i) {
7930 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007931 ArtMethod& new_method = *out;
7932 new_method.CopyFrom(def_method, pointer_size);
7933 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7934 // verified yet it shouldn't have methods that are skipping access checks.
7935 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7936 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007937 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007938 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7939 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7940 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7941 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007942 // Update the entry in the method array, as the array will be used for future lookups,
7943 // where thread suspension is allowed.
7944 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7945 // would not see them.
7946 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007947 ++out;
7948 }
7949 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007950 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7951 &overriding_default_conflict_methods_}) {
7952 for (size_t i = 0; i < methods_vec->size(); ++i) {
7953 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007954 ArtMethod& new_method = *out;
7955 new_method.CopyFrom(conf_method, pointer_size);
7956 // This is a type of default method (there are default method impls, just a conflict) so
7957 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7958 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7959 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007960 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7961 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007962 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007963 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007964 constexpr uint32_t kMaskFlags =
7965 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007966 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7967 DCHECK(new_method.IsDefaultConflicting());
7968 // The actual method might or might not be marked abstract since we just copied it from a
7969 // (possibly default) interface method. We need to set it entry point to be the bridge so
7970 // that the compiler will not invoke the implementation of whatever method we copied from.
7971 EnsureThrowsInvocationError(class_linker_, &new_method);
7972 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007973 // Update the entry in the method array, as the array will be used for future lookups,
7974 // where thread suspension is allowed.
7975 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7976 // would not see them.
7977 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007978 ++out;
7979 }
7980 }
7981 methods->SetSize(new_method_count);
7982 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7983}
7984
7985ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007986 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007987 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007988 // Update the vtable to the new method structures. We can skip this for interfaces since they
7989 // do not have vtables.
7990 const size_t old_vtable_count = old_vtable->GetLength();
7991 const size_t new_vtable_count = old_vtable_count +
7992 miranda_methods_.size() +
7993 default_methods_.size() +
7994 default_conflict_methods_.size();
7995
Vladimir Marko3068d582019-05-28 16:39:29 +01007996 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
7997 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007998 if (UNLIKELY(vtable == nullptr)) {
7999 self_->AssertPendingOOMException();
8000 return nullptr;
8001 }
8002
8003 size_t vtable_pos = old_vtable_count;
8004 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8005 // Update all the newly copied method's indexes so they denote their placement in the vtable.
8006 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
8007 default_conflict_methods_,
8008 miranda_methods_}) {
8009 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008010 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008011 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
8012 // fields are references into the dex file the method was defined in. Since the ArtMethod
8013 // does not store that information it uses declaring_class_->dex_cache_.
8014 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
8015 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
8016 ++vtable_pos;
8017 }
8018 }
8019 DCHECK_EQ(vtable_pos, new_vtable_count);
8020
8021 // Update old vtable methods. We use the default_translations map to figure out what each
8022 // vtable entry should be updated to, if they need to be at all.
8023 for (size_t i = 0; i < old_vtable_count; ++i) {
8024 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
8025 // Try and find what we need to change this method to.
8026 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008027 if (translation_it != default_translations.end()) {
8028 if (translation_it->second.IsInConflict()) {
8029 // Find which conflict method we are to use for this method.
8030 MethodNameAndSignatureComparator old_method_comparator(
8031 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8032 // We only need to look through overriding_default_conflict_methods since this is an
8033 // overridden method we are fixing up here.
8034 ArtMethod* new_conflict_method = FindSameNameAndSignature(
8035 old_method_comparator, overriding_default_conflict_methods_);
8036 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
8037 translated_method = new_conflict_method;
8038 } else if (translation_it->second.IsAbstract()) {
8039 // Find which miranda method we are to use for this method.
8040 MethodNameAndSignatureComparator old_method_comparator(
8041 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8042 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
8043 miranda_methods_);
8044 DCHECK(miranda_method != nullptr);
8045 translated_method = miranda_method;
8046 } else {
8047 // Normal default method (changed from an older default or abstract interface method).
8048 DCHECK(translation_it->second.IsTranslation());
8049 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008050 auto it = move_table_.find(translated_method);
8051 DCHECK(it != move_table_.end());
8052 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00008053 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008054 } else {
8055 auto it = move_table_.find(translated_method);
8056 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008057 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008058
8059 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008060 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008061 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008062 if (kIsDebugBuild) {
8063 auto* methods = klass_->GetMethodsPtr();
8064 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008065 reinterpret_cast<uintptr_t>(translated_method));
8066 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008067 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8068 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008069 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008070 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008071 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008072 }
8073 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008074 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008075 return vtable;
8076}
8077
8078void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8079 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8080 const size_t ifcount = klass_->GetIfTableCount();
8081 // Go fix up all the stale iftable pointers.
8082 for (size_t i = 0; i < ifcount; ++i) {
8083 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008084 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8085 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008086 DCHECK(m != nullptr) << klass_->PrettyClass();
8087 auto it = move_table_.find(m);
8088 if (it != move_table_.end()) {
8089 auto* new_m = it->second;
8090 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8091 method_array->SetElementPtrSize(j, new_m, pointer_size);
8092 }
8093 }
8094 }
8095}
8096
8097void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8098 // Fix up IMT next.
8099 for (size_t i = 0; i < ImTable::kSize; ++i) {
8100 auto it = move_table_.find(out_imt[i]);
8101 if (it != move_table_.end()) {
8102 out_imt[i] = it->second;
8103 }
8104 }
8105}
8106
Alex Light705ad492015-09-21 11:36:30 -07008107// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008108bool ClassLinker::LinkInterfaceMethods(
8109 Thread* self,
8110 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00008111 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008112 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008113 ArtMethod** out_imt) {
8114 StackHandleScope<3> hs(self);
8115 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008116
8117 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008118 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008119 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008120 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008121 const size_t ifcount = klass->GetIfTableCount();
8122
Vladimir Marko921094a2017-01-12 18:37:06 +00008123 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008124
8125 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8126 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008127 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008128 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008129 const bool extend_super_iftable = has_superclass;
8130 if (has_superclass && fill_tables) {
8131 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008132 unimplemented_method,
8133 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008134 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008135 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008136 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008137 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8138 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008139 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008140 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8141 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008142 }
8143 }
8144
Vladimir Marko921094a2017-01-12 18:37:06 +00008145 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8146
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008147 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008148 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008149 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8150 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8151 // they will already be null. This has the additional benefit that the declarer of a miranda
8152 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008153 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008154 --i;
Alex Light9139e002015-10-09 15:59:48 -07008155 DCHECK_LT(i, ifcount);
8156
Alex Light705ad492015-09-21 11:36:30 -07008157 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008158 if (num_methods > 0) {
8159 StackHandleScope<2> hs2(self);
8160 const bool is_super = i < super_ifcount;
8161 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008162 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8163 // conflict methods. Just set this as nullptr in those cases.
8164 Handle<mirror::PointerArray> method_array(fill_tables
8165 ? hs2.NewHandle(iftable->GetMethodArray(i))
8166 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008167
Alex Lighte64300b2015-12-15 15:02:47 -08008168 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008169 ScopedNullHandle<mirror::PointerArray> null_handle;
8170 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008171 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008172
Alex Light9139e002015-10-09 15:59:48 -07008173 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8174 // and confusing. Default methods should always look through all the superclasses
8175 // because they are the last choice of an implementation. We get around this by looking
8176 // at the super-classes iftable methods (copied into method_array previously) when we are
8177 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008178 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008179 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008180 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008181 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008182 using_virtuals = true;
Alex Lighta467a6e2020-03-23 16:07:29 -07008183 input_virtual_methods = klass->GetDeclaredVirtualMethodsSlice(image_pointer_size_);
Alex Lighte64300b2015-12-15 15:02:47 -08008184 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008185 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008186 // For a new interface, however, we need the whole vtable in case a new
8187 // interface method is implemented in the whole superclass.
8188 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008189 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008190 input_vtable_array = vtable;
8191 input_array_length = input_vtable_array->GetLength();
8192 }
Alex Lighte64300b2015-12-15 15:02:47 -08008193
Alex Lighteb7c1442015-08-31 13:17:42 -07008194 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008195 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008196 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008197 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008198 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008199 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008200 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008201 // For each method listed in the interface's method list, find the
8202 // matching method in our class's method list. We want to favor the
8203 // subclass over the superclass, which just requires walking
8204 // back from the end of the vtable. (This only matters if the
8205 // superclass defines a private method and this class redefines
8206 // it -- otherwise it would use the same vtable slot. In .dex files
8207 // those don't end up in the virtual method table, so it shouldn't
8208 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008209 //
8210 // To find defaults we need to do the same but also go over interfaces.
8211 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008212 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008213 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008214 ArtMethod* vtable_method = using_virtuals ?
8215 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008216 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8217 ArtMethod* vtable_method_for_name_comparison =
8218 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Alex Lighta467a6e2020-03-23 16:07:29 -07008219 DCHECK(!vtable_method->IsStatic()) << vtable_method->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008220 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008221 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008222 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008223 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8224 // allocations.
8225 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008226 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008227 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008228 vtable_method->PrettyMethod().c_str(),
8229 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008230 return false;
Alex Light9139e002015-10-09 15:59:48 -07008231 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008232 // We might have a newer, better, default method for this, so we just skip it. If we
8233 // are still using this we will select it again when scanning for default methods. To
8234 // obviate the need to copy the method again we will make a note that we already found
8235 // a default here.
8236 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008237 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008238 break;
8239 } else {
8240 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008241 if (LIKELY(fill_tables)) {
8242 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8243 // Place method in imt if entry is empty, place conflict otherwise.
8244 SetIMTRef(unimplemented_method,
8245 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008246 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008247 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008248 /*out*/imt_ptr);
8249 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008250 break;
8251 }
8252 }
Alex Light9139e002015-10-09 15:59:48 -07008253 }
8254 // Continue on to the next method if we are done.
8255 if (LIKELY(found_impl)) {
8256 continue;
8257 } else if (LIKELY(super_interface)) {
8258 // Don't look for a default implementation when the super-method is implemented directly
8259 // by the class.
8260 //
8261 // See if we can use the superclasses method and skip searching everything else.
8262 // Note: !found_impl && super_interface
8263 CHECK(extend_super_iftable);
8264 // If this is a super_interface method it is possible we shouldn't override it because a
8265 // superclass could have implemented it directly. We get the method the superclass used
8266 // to implement this to know if we can override it with a default method. Doing this is
8267 // safe since we know that the super_iftable is filled in so we can simply pull it from
8268 // there. We don't bother if this is not a super-classes interface since in that case we
8269 // have scanned the entire vtable anyway and would have found it.
8270 // TODO This is rather dirty but it is faster than searching through the entire vtable
8271 // every time.
8272 ArtMethod* supers_method =
8273 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8274 DCHECK(supers_method != nullptr);
8275 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008276 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008277 // The method is not overridable by a default method (i.e. it is directly implemented
8278 // in some class). Therefore move onto the next interface method.
8279 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008280 } else {
8281 // If the super-classes method is override-able by a default method we need to keep
8282 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8283 // 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 -07008284 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8285 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8286 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008287 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008288 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8289 << " and not 'nullptr' or "
8290 << supers_method->PrettyMethod()
8291 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008292 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008293 }
8294 }
8295 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008296 ArtMethod* current_method = helper.FindMethod(interface_method,
8297 interface_name_comparator,
8298 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008299 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008300 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008301 // We could not find an implementation for this method and since it is a brand new
8302 // interface we searched the entire vtable (and all default methods) for an
8303 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008304 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8305 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008306 }
8307
8308 if (current_method != nullptr) {
8309 // We found a default method implementation. Record it in the iftable and IMT.
8310 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8311 SetIMTRef(unimplemented_method,
8312 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008313 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008314 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008315 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008316 }
8317 }
Alex Light705ad492015-09-21 11:36:30 -07008318 } // For each method in interface end.
8319 } // if (num_methods > 0)
8320 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008321 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008322 if (helper.HasNewVirtuals()) {
8323 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8324 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8325 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8326
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008327 // 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 -07008328 // suspension assert.
8329 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008330
Alex Light705ad492015-09-21 11:36:30 -07008331 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008332 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008333 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008334 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008335 return false;
8336 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008337 helper.UpdateIfTable(iftable);
8338 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008339 }
Alex Light705ad492015-09-21 11:36:30 -07008340
Vladimir Marko921094a2017-01-12 18:37:06 +00008341 helper.CheckNoStaleMethodsInDexCache();
8342 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008343 } else {
8344 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008345 }
Alex Light705ad492015-09-21 11:36:30 -07008346 if (kIsDebugBuild && !is_interface) {
Orion Hodson5880c772020-07-28 20:12:08 +01008347 CheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008348 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008349 return true;
8350}
8351
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008352bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008353 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008354 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008355}
8356
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008357bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008358 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008359 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008360}
8361
Brian Carlstromdbc05252011-09-09 01:59:59 -07008362struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008363 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008364 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008365 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008366 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008367 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008368 // 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 -07008369 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8370 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008371 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008372 if (type1 == Primitive::kPrimNot) {
8373 // Reference always goes first.
8374 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008375 }
Vladimir Markod5777482014-11-12 17:02:02 +00008376 if (type2 == Primitive::kPrimNot) {
8377 // Reference always goes first.
8378 return false;
8379 }
8380 size_t size1 = Primitive::ComponentSize(type1);
8381 size_t size2 = Primitive::ComponentSize(type2);
8382 if (size1 != size2) {
8383 // Larger primitive types go first.
8384 return size1 > size2;
8385 }
8386 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8387 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008388 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008389 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8390 // by name and for equal names by type id index.
8391 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8392 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008393 }
8394};
8395
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008396bool ClassLinker::LinkFields(Thread* self,
8397 Handle<mirror::Class> klass,
8398 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008399 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008400 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008401 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008402 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8403 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008404
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008405 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008406 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008407 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008408 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008409 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008410 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008411 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008412 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008413 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008414 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008415 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008416 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008417
David Sehr709b0702016-10-13 09:12:37 -07008418 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008419
Brian Carlstromdbc05252011-09-09 01:59:59 -07008420 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008421 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008422 //
8423 // The overall sort order order is:
8424 // 1) All object reference fields, sorted alphabetically.
8425 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8426 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8427 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8428 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8429 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8430 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8431 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8432 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8433 //
8434 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8435 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008436 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008437 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008438 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008439 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008440 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008441 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008442 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8443 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008444
Fred Shih381e4ca2014-08-25 17:24:27 -07008445 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008446 size_t current_field = 0;
8447 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008448 FieldGaps gaps;
8449
Brian Carlstromdbc05252011-09-09 01:59:59 -07008450 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008451 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008452 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008453 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008454 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008455 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008456 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008457 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8458 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008459 MemberOffset old_offset = field_offset;
8460 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8461 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8462 }
Roland Levillain14d90572015-07-16 10:52:26 +01008463 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008464 grouped_and_sorted_fields.pop_front();
8465 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008466 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008467 field_offset = MemberOffset(field_offset.Uint32Value() +
8468 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008469 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008470 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8471 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008472 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8473 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8474 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8475 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Mathieu Chartier55650292020-09-14 12:21:04 -07008476 if (!grouped_and_sorted_fields.empty()) {
8477 std::ostringstream oss;
8478 oss << "Missed " << grouped_and_sorted_fields.size() << " fields ";
8479 for (ArtField* field : grouped_and_sorted_fields) {
8480 oss << field->PrettyField() << " ";
8481 }
8482 LOG(FATAL) << oss.str();
8483 }
Ian Rogers7b078e82014-09-10 14:44:24 -07008484 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008485
Elliott Hughesadb460d2011-10-05 17:02:34 -07008486 // 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 -07008487 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008488 // We know there are no non-reference fields in the Reference classes, and we know
8489 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008490 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008491 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008492 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008493 --num_reference_fields;
8494 }
8495
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008496 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008497 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008498 if (is_static) {
8499 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008500 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008501 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008502 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008503 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008504 if (num_reference_fields == 0 || super_class == nullptr) {
8505 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008506 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008507 if (super_class == nullptr ||
8508 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8509 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008510 }
8511 }
8512 if (kIsDebugBuild) {
8513 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8514 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008515 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008516 while (cur_super != nullptr) {
8517 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8518 cur_super = cur_super->GetSuperClass();
8519 }
8520 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008521 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008522 } else {
8523 // Check that there is at least num_reference_fields other than Object.class.
8524 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008525 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008526 }
8527 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008528 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008529 std::string temp;
8530 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8531 size_t previous_size = klass->GetObjectSize();
8532 if (previous_size != 0) {
8533 // Make sure that we didn't originally have an incorrect size.
8534 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008535 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008536 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008537 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008538 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008539
8540 if (kIsDebugBuild) {
8541 // Make sure that the fields array is ordered by name but all reference
8542 // offsets are at the beginning as far as alignment allows.
8543 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008544 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008545 : klass->GetFirstReferenceInstanceFieldOffset();
8546 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8547 num_reference_fields *
8548 sizeof(mirror::HeapReference<mirror::Object>));
8549 MemberOffset current_ref_offset = start_ref_offset;
8550 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008551 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008552 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008553 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8554 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008555 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008556 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008557 // NOTE: The field names can be the same. This is not possible in the Java language
8558 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008559 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008560 }
8561 Primitive::Type type = field->GetTypeAsPrimitiveType();
8562 bool is_primitive = type != Primitive::kPrimNot;
8563 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8564 strcmp("referent", field->GetName()) == 0) {
8565 is_primitive = true; // We lied above, so we have to expect a lie here.
8566 }
8567 MemberOffset offset = field->GetOffsetDuringLinking();
8568 if (is_primitive) {
8569 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8570 // Shuffled before references.
8571 size_t type_size = Primitive::ComponentSize(type);
8572 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8573 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8574 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8575 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8576 }
8577 } else {
8578 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8579 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8580 sizeof(mirror::HeapReference<mirror::Object>));
8581 }
8582 }
8583 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8584 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008585 return true;
8586}
8587
Vladimir Marko76649e82014-11-10 18:32:59 +00008588// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008589void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008590 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008591 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008592 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008593 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008594 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008595 // Compute reference offsets unless our superclass overflowed.
8596 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8597 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008598 if (num_reference_fields != 0u) {
8599 // All of the fields that contain object references are guaranteed be grouped in memory
8600 // starting at an appropriately aligned address after super class object data.
8601 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8602 sizeof(mirror::HeapReference<mirror::Object>));
8603 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008604 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008605 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008606 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008607 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008608 reference_offsets |= (0xffffffffu << start_bit) &
8609 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008610 }
8611 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008612 }
8613 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008614 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008615}
8616
Vladimir Marko18090d12018-06-01 16:53:12 +01008617ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8618 ObjPtr<mirror::DexCache> dex_cache) {
8619 StackHandleScope<1> hs(Thread::Current());
8620 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8621 return DoResolveString(string_idx, h_dex_cache);
8622}
8623
8624ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8625 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008626 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008627 uint32_t utf16_length;
8628 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008629 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008630 if (string != nullptr) {
8631 dex_cache->SetResolvedString(string_idx, string);
8632 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008633 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008634}
8635
Vladimir Marko18090d12018-06-01 16:53:12 +01008636ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8637 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008638 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008639 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008640 uint32_t utf16_length;
8641 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008642 ObjPtr<mirror::String> string =
8643 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008644 if (string != nullptr) {
8645 dex_cache->SetResolvedString(string_idx, string);
8646 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008647 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008648}
8649
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008650ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008651 ObjPtr<mirror::Class> referrer) {
8652 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8653}
8654
8655ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008656 ObjPtr<mirror::DexCache> dex_cache,
8657 ObjPtr<mirror::ClassLoader> class_loader) {
8658 const DexFile& dex_file = *dex_cache->GetDexFile();
8659 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8660 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8661 ObjPtr<mirror::Class> type = nullptr;
8662 if (descriptor[1] == '\0') {
8663 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8664 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008665 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008666 } else {
8667 Thread* const self = Thread::Current();
8668 DCHECK(self != nullptr);
8669 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8670 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008671 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008672 }
8673 if (type != nullptr) {
8674 if (type->IsResolved()) {
8675 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008676 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008677 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008678 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008679 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008680 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008681}
8682
Andreas Gampeb0625e02019-05-01 12:43:31 -07008683template <typename RefType>
8684ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008685 StackHandleScope<2> hs(Thread::Current());
8686 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8687 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8688 return DoResolveType(type_idx, dex_cache, class_loader);
8689}
8690
Andreas Gampe4835d212018-11-21 14:55:10 -08008691// Instantiate the above.
8692template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8693 ArtField* referrer);
8694template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8695 ArtMethod* referrer);
8696template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8697 ObjPtr<mirror::Class> referrer);
8698
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008699ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008700 Handle<mirror::DexCache> dex_cache,
8701 Handle<mirror::ClassLoader> class_loader) {
8702 Thread* self = Thread::Current();
8703 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8704 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8705 if (resolved != nullptr) {
8706 // TODO: we used to throw here if resolved's class loader was not the
8707 // boot class loader. This was to permit different classes with the
8708 // same name to be loaded simultaneously by different loaders
8709 dex_cache->SetResolvedType(type_idx, resolved);
8710 } else {
8711 CHECK(self->IsExceptionPending())
8712 << "Expected pending exception for failed resolution of: " << descriptor;
8713 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8714 StackHandleScope<1> hs(self);
8715 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008716 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008717 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8718 self->ClearException();
8719 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8720 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008721 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008722 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008723 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008724 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008725 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008726}
8727
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008728ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8729 ObjPtr<mirror::DexCache> dex_cache,
8730 ObjPtr<mirror::ClassLoader> class_loader,
8731 uint32_t method_idx) {
8732 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8733 // functions can optimize the search if the dex_cache is the same as the DexCache
8734 // of the class, with fall-back to name and signature search otherwise.
8735 ArtMethod* resolved = nullptr;
8736 if (klass->IsInterface()) {
8737 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8738 } else {
8739 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8740 }
8741 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008742 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008743 hiddenapi::ShouldDenyAccessToMember(resolved,
8744 hiddenapi::AccessContext(class_loader, dex_cache),
8745 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008746 resolved = nullptr;
8747 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008748 if (resolved != nullptr) {
8749 // In case of jmvti, the dex file gets verified before being registered, so first
8750 // check if it's registered before checking class tables.
8751 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008752 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8753 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008754 << "DexFile referrer: " << dex_file.GetLocation()
8755 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8756 // Be a good citizen and update the dex cache to speed subsequent calls.
8757 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008758 // Disable the following invariant check as the verifier breaks it. b/73760543
8759 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8760 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8761 // << "Method: " << resolved->PrettyMethod() << ", "
8762 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8763 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008764 }
8765 return resolved;
8766}
8767
David Brazdil4525e0b2018-04-05 16:57:32 +01008768// Returns true if `method` is either null or hidden.
8769// Does not print any warnings if it is hidden.
8770static bool CheckNoSuchMethod(ArtMethod* method,
8771 ObjPtr<mirror::DexCache> dex_cache,
8772 ObjPtr<mirror::ClassLoader> class_loader)
8773 REQUIRES_SHARED(Locks::mutator_lock_) {
8774 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008775 hiddenapi::ShouldDenyAccessToMember(method,
8776 hiddenapi::AccessContext(class_loader, dex_cache),
8777 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008778}
8779
8780ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8781 ObjPtr<mirror::DexCache> dex_cache,
8782 ObjPtr<mirror::ClassLoader> class_loader,
8783 uint32_t method_idx) {
8784 if (klass->IsInterface()) {
8785 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8786 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8787 } else {
8788 // If there was an interface method with the same signature, we would have
8789 // found it in the "copied" methods. Only DCHECK that the interface method
8790 // really does not exist.
8791 if (kIsDebugBuild) {
8792 ArtMethod* method =
8793 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8794 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8795 }
8796 return nullptr;
8797 }
8798}
8799
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008800template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008801ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008802 Handle<mirror::DexCache> dex_cache,
8803 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008804 ArtMethod* referrer,
8805 InvokeType type) {
Nicolas Geoffray605c5912020-04-08 15:12:39 +01008806 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Andreas Gampefa4333d2017-02-14 11:10:34 -08008807 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008808 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008809 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008810 PointerSize pointer_size = image_pointer_size_;
8811 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008812 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008813 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8814 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008815 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8816 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008817 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008818 return resolved;
8819 }
Vladimir Marko89011192017-12-11 13:45:05 +00008820 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008821 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008822 ObjPtr<mirror::Class> klass = nullptr;
8823 if (valid_dex_cache_method) {
8824 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8825 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008826 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008827 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008828 // We normaly should not end up here. However the verifier currently doesn't guarantee
8829 // the invariant of having the klass in the class table. b/73760543
8830 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Nicolas Geoffray07614192020-04-28 17:31:31 +01008831 if (klass == nullptr) {
8832 // This can only happen if the current thread is not allowed to load
8833 // classes.
8834 DCHECK(!Thread::Current()->CanLoadClasses());
8835 DCHECK(Thread::Current()->IsExceptionPending());
8836 return nullptr;
8837 }
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008838 }
Vladimir Markoba118822017-06-12 15:41:56 +01008839 } else {
8840 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008841 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008842 if (klass == nullptr) {
8843 DCHECK(Thread::Current()->IsExceptionPending());
8844 return nullptr;
8845 }
8846 }
8847
8848 // Check if the invoke type matches the class type.
8849 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008850 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008851 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008852 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008853 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008854 }
Vladimir Markoba118822017-06-12 15:41:56 +01008855
8856 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008857 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008858 }
Vladimir Markoba118822017-06-12 15:41:56 +01008859
8860 // Note: We can check for IllegalAccessError only if we have a referrer.
8861 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8862 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8863 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8864 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8865 resolved,
8866 dex_cache.Get(),
8867 method_idx,
8868 type)) {
8869 DCHECK(Thread::Current()->IsExceptionPending());
8870 return nullptr;
8871 }
8872 }
8873
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008874 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008875 if (LIKELY(resolved != nullptr) &&
8876 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8877 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008878 return resolved;
8879 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008880 // If we had a method, or if we can find one with another lookup type,
8881 // it's an incompatible-class-change error.
8882 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008883 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008884 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008885 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008886 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008887 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008888 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008889 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8890 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008891 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008892 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008893 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008894 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008895 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008896}
8897
Vladimir Marko89011192017-12-11 13:45:05 +00008898ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008899 Handle<mirror::DexCache> dex_cache,
8900 Handle<mirror::ClassLoader> class_loader) {
8901 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008902 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008903 if (resolved != nullptr) {
8904 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008905 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8906 return resolved;
8907 }
8908 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008909 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008910 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008911 if (klass == nullptr) {
8912 Thread::Current()->AssertPendingException();
8913 return nullptr;
8914 }
8915 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008916 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8917 } else {
8918 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008919 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008920 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008921 hiddenapi::ShouldDenyAccessToMember(
8922 resolved,
8923 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8924 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008925 resolved = nullptr;
8926 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008927 return resolved;
8928}
8929
Vladimir Markof44d36c2017-03-14 14:18:46 +00008930ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8931 ObjPtr<mirror::DexCache> dex_cache,
8932 ObjPtr<mirror::ClassLoader> class_loader,
8933 bool is_static) {
8934 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008935 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008936 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8937 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008938 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008939 }
8940 if (klass == nullptr) {
8941 // The class has not been resolved yet, so the field is also unresolved.
8942 return nullptr;
8943 }
8944 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008945
David Brazdil1ab0fa82018-05-04 11:28:03 +01008946 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008947}
8948
Vladimir Markoe11dd502017-12-08 14:09:45 +00008949ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008950 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008951 Handle<mirror::ClassLoader> class_loader,
8952 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008953 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayf3688822020-03-25 15:04:03 +00008954 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008955 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008956 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008957 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008958 return resolved;
8959 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008960 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008961 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008962 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008963 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008964 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008965 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008966 }
8967
David Brazdil1ab0fa82018-05-04 11:28:03 +01008968 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008969 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008970 const char* name = dex_file.GetFieldName(field_id);
8971 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008972 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008973 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008974 return resolved;
8975}
8976
Vladimir Markoe11dd502017-12-08 14:09:45 +00008977ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008978 Handle<mirror::DexCache> dex_cache,
8979 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008980 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008981 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008982 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008983 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008984 return resolved;
8985 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008986 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008987 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008988 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008989 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008990 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008991 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008992 }
8993
David Brazdil1ab0fa82018-05-04 11:28:03 +01008994 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8995 if (resolved == nullptr) {
8996 const char* name = dex_file.GetFieldName(field_id);
8997 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008998 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008999 }
9000 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009001}
9002
David Brazdil1ab0fa82018-05-04 11:28:03 +01009003ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9004 ObjPtr<mirror::DexCache> dex_cache,
9005 ObjPtr<mirror::ClassLoader> class_loader,
9006 uint32_t field_idx,
9007 bool is_static) {
9008 ArtField* resolved = nullptr;
9009 Thread* self = is_static ? Thread::Current() : nullptr;
9010 const DexFile& dex_file = *dex_cache->GetDexFile();
9011
9012 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
9013 : klass->FindInstanceField(dex_cache, field_idx);
9014
9015 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009016 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009017 const char* name = dex_file.GetFieldName(field_id);
9018 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9019 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
9020 : klass->FindInstanceField(name, type);
9021 }
9022
9023 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009024 hiddenapi::ShouldDenyAccessToMember(resolved,
9025 hiddenapi::AccessContext(class_loader, dex_cache),
9026 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009027 resolved = nullptr;
9028 }
9029
9030 if (resolved != nullptr) {
9031 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9032 }
9033
9034 return resolved;
9035}
9036
9037ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9038 ObjPtr<mirror::DexCache> dex_cache,
9039 ObjPtr<mirror::ClassLoader> class_loader,
9040 uint32_t field_idx) {
9041 ArtField* resolved = nullptr;
9042 Thread* self = Thread::Current();
9043 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009044 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009045
9046 const char* name = dex_file.GetFieldName(field_id);
9047 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9048 resolved = mirror::Class::FindField(self, klass, name, type);
9049
9050 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009051 hiddenapi::ShouldDenyAccessToMember(resolved,
9052 hiddenapi::AccessContext(class_loader, dex_cache),
9053 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009054 resolved = nullptr;
9055 }
9056
9057 if (resolved != nullptr) {
9058 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9059 }
9060
9061 return resolved;
9062}
9063
Vladimir Markoaf940202017-12-08 15:01:18 +00009064ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9065 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009066 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009067 Handle<mirror::DexCache> dex_cache,
9068 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009069 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009070 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009071
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009072 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009073 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009074 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009075 }
9076
Narayan Kamath25352fc2016-08-03 12:46:58 +01009077 StackHandleScope<4> hs(self);
9078
9079 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009080 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009081 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009082 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009083 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009084 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009085 DCHECK(self->IsExceptionPending());
9086 return nullptr;
9087 }
9088
9089 // Then resolve the argument types.
9090 //
9091 // TODO: Is there a better way to figure out the number of method arguments
9092 // other than by looking at the shorty ?
9093 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9094
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009095 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009096 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9097 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009098 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009099 DCHECK(self->IsExceptionPending());
9100 return nullptr;
9101 }
9102
9103 DexFileParameterIterator it(dex_file, proto_id);
9104 int32_t i = 0;
9105 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9106 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009107 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009108 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009109 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009110 DCHECK(self->IsExceptionPending());
9111 return nullptr;
9112 }
9113
9114 method_params->Set(i++, param_class.Get());
9115 }
9116
9117 DCHECK(!it.HasNext());
9118
9119 Handle<mirror::MethodType> type = hs.NewHandle(
9120 mirror::MethodType::Create(self, return_type, method_params));
9121 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9122
9123 return type.Get();
9124}
9125
Vladimir Markoaf940202017-12-08 15:01:18 +00009126ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009127 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009128 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009129 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009130 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9131 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009132 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009133}
9134
Vladimir Marko5aead702019-03-27 11:00:36 +00009135ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009136 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009137 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009138 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009139 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009140 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9141 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009142 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009143 bool is_static;
9144 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009145 switch (handle_type) {
9146 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009147 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009148 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009149 is_static = true;
9150 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009151 break;
9152 }
9153 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009154 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009155 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009156 is_static = true;
9157 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009158 break;
9159 }
9160 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009161 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009162 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009163 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009164 num_params = 2;
9165 break;
9166 }
9167 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009168 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009169 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009170 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009171 num_params = 1;
9172 break;
9173 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009174 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009175 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009176 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009177 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009178 case DexFile::MethodHandleType::kInvokeInterface:
9179 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009180 }
9181
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009182 ArtField* target_field =
9183 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9184 if (LIKELY(target_field != nullptr)) {
9185 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9186 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9187 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9188 ThrowIllegalAccessErrorField(referring_class, target_field);
9189 return nullptr;
9190 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009191 if (UNLIKELY(is_put && target_field->IsFinal())) {
9192 ThrowIllegalAccessErrorField(referring_class, target_field);
9193 return nullptr;
9194 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009195 } else {
9196 DCHECK(Thread::Current()->IsExceptionPending());
9197 return nullptr;
9198 }
9199
9200 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009201 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009202 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9203 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009204 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009205 DCHECK(self->IsExceptionPending());
9206 return nullptr;
9207 }
9208
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009209 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009210 Handle<mirror::Class> return_type;
9211 switch (handle_type) {
9212 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009213 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009214 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009215 break;
9216 }
9217 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009218 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009219 break;
9220 }
9221 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009222 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009223 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009224 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009225 break;
9226 }
9227 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009228 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009229 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009230 break;
9231 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009232 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009233 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009234 case DexFile::MethodHandleType::kInvokeConstructor:
9235 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009236 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009237 UNREACHABLE();
9238 }
9239
9240 for (int32_t i = 0; i < num_params; ++i) {
9241 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9242 DCHECK(self->IsExceptionPending());
9243 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009244 }
9245 }
9246
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009247 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009248 DCHECK(self->IsExceptionPending());
9249 return nullptr;
9250 }
9251
9252 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009253 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9254 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009255 DCHECK(self->IsExceptionPending());
9256 return nullptr;
9257 }
Orion Hodson631827d2017-04-10 14:53:47 +01009258
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009259 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9260 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9261}
9262
Vladimir Marko5aead702019-03-27 11:00:36 +00009263ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009264 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009265 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009266 ArtMethod* referrer) {
9267 DexFile::MethodHandleType handle_type =
9268 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9269 mirror::MethodHandle::Kind kind;
9270 uint32_t receiver_count = 0;
9271 ArtMethod* target_method = nullptr;
9272 switch (handle_type) {
9273 case DexFile::MethodHandleType::kStaticPut:
9274 case DexFile::MethodHandleType::kStaticGet:
9275 case DexFile::MethodHandleType::kInstancePut:
9276 case DexFile::MethodHandleType::kInstanceGet:
9277 UNREACHABLE();
9278 case DexFile::MethodHandleType::kInvokeStatic: {
9279 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9280 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009281 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9282 method_handle.field_or_method_idx_,
9283 referrer,
9284 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009285 break;
9286 }
9287 case DexFile::MethodHandleType::kInvokeInstance: {
9288 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9289 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009290 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9291 method_handle.field_or_method_idx_,
9292 referrer,
9293 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009294 break;
9295 }
9296 case DexFile::MethodHandleType::kInvokeConstructor: {
9297 // Constructors are currently implemented as a transform. They
9298 // are special cased later in this method.
9299 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9300 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009301 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9302 method_handle.field_or_method_idx_,
9303 referrer,
9304 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009305 break;
9306 }
9307 case DexFile::MethodHandleType::kInvokeDirect: {
9308 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9309 receiver_count = 1;
9310 StackHandleScope<2> hs(self);
9311 // A constant method handle with type kInvokeDirect can refer to
9312 // a method that is private or to a method in a super class. To
9313 // disambiguate the two options, we resolve the method ignoring
9314 // the invocation type to determine if the method is private. We
9315 // then resolve again specifying the intended invocation type to
9316 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009317 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009318 hs.NewHandle(referrer->GetDexCache()),
9319 hs.NewHandle(referrer->GetClassLoader()));
9320 if (UNLIKELY(target_method == nullptr)) {
9321 break;
9322 }
9323
9324 if (target_method->IsPrivate()) {
9325 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009326 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9327 method_handle.field_or_method_idx_,
9328 referrer,
9329 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009330 } else {
9331 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009332 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9333 method_handle.field_or_method_idx_,
9334 referrer,
9335 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009336 if (UNLIKELY(target_method == nullptr)) {
9337 break;
9338 }
9339 // Find the method specified in the parent in referring class
9340 // so invoke-super invokes the method in the parent of the
9341 // referrer.
9342 target_method =
9343 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9344 kRuntimePointerSize);
9345 }
9346 break;
9347 }
9348 case DexFile::MethodHandleType::kInvokeInterface: {
9349 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9350 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009351 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9352 method_handle.field_or_method_idx_,
9353 referrer,
9354 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009355 break;
9356 }
Orion Hodson631827d2017-04-10 14:53:47 +01009357 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009358
9359 if (UNLIKELY(target_method == nullptr)) {
9360 DCHECK(Thread::Current()->IsExceptionPending());
9361 return nullptr;
9362 }
9363
9364 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9365 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9366 uint32_t access_flags = target_method->GetAccessFlags();
9367 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9368 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9369 return nullptr;
9370 }
9371
9372 // Calculate the number of parameters from the method shorty. We add the
9373 // receiver count (0 or 1) and deduct one for the return value.
9374 uint32_t shorty_length;
9375 target_method->GetShorty(&shorty_length);
9376 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9377
Orion Hodsonecd58562018-09-24 11:27:33 +01009378 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009379 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009380 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9381 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9382 if (method_params.Get() == nullptr) {
9383 DCHECK(self->IsExceptionPending());
9384 return nullptr;
9385 }
9386
Orion Hodsonecd58562018-09-24 11:27:33 +01009387 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009388 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009389 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009390 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009391 // Insert receiver. Use the class identified in the method handle rather than the declaring
9392 // class of the resolved method which may be super class or default interface method
9393 // (b/115964401).
9394 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9395 // receiver_class should have been resolved when resolving the target method.
9396 DCHECK(receiver_class != nullptr);
9397 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009398 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009399
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009400 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009401 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009402 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009403 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009404 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009405 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009406 if (nullptr == klass) {
9407 DCHECK(self->IsExceptionPending());
9408 return nullptr;
9409 }
9410 method_params->Set(index++, klass);
9411 it.Next();
9412 }
9413
Orion Hodsonecd58562018-09-24 11:27:33 +01009414 Handle<mirror::Class> return_type =
9415 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009416 if (UNLIKELY(return_type.IsNull())) {
9417 DCHECK(self->IsExceptionPending());
9418 return nullptr;
9419 }
9420
9421 Handle<mirror::MethodType>
9422 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9423 if (UNLIKELY(method_type.IsNull())) {
9424 DCHECK(self->IsExceptionPending());
9425 return nullptr;
9426 }
9427
9428 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9429 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9430 Handle<mirror::MethodHandlesLookup> lookup =
9431 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9432 return lookup->FindConstructor(self, constructor_class, method_type);
9433 }
9434
9435 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9436 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9437}
9438
Vladimir Markoaf940202017-12-08 15:01:18 +00009439ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9440 uint32_t method_handle_idx,
9441 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009442 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009443 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009444 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009445 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9446 case DexFile::MethodHandleType::kStaticPut:
9447 case DexFile::MethodHandleType::kStaticGet:
9448 case DexFile::MethodHandleType::kInstancePut:
9449 case DexFile::MethodHandleType::kInstanceGet:
9450 return ResolveMethodHandleForField(self, method_handle, referrer);
9451 case DexFile::MethodHandleType::kInvokeStatic:
9452 case DexFile::MethodHandleType::kInvokeInstance:
9453 case DexFile::MethodHandleType::kInvokeConstructor:
9454 case DexFile::MethodHandleType::kInvokeDirect:
9455 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009456 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009457 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009458}
9459
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009460bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9461 return (entry_point == GetQuickResolutionStub()) ||
9462 (quick_resolution_trampoline_ == entry_point);
9463}
9464
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009465bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9466 return (entry_point == GetQuickToInterpreterBridge()) ||
9467 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9468}
9469
9470bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9471 return (entry_point == GetQuickGenericJniStub()) ||
9472 (quick_generic_jni_trampoline_ == entry_point);
9473}
9474
David Sehra49e0532017-08-25 08:05:29 -07009475bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009476 return entry_point == GetJniDlsymLookupStub() ||
9477 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009478}
9479
Vladimir Markofa458ac2020-02-12 14:08:07 +00009480bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9481 return entry_point == GetJniDlsymLookupCriticalStub() ||
9482 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9483}
9484
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009485const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9486 return GetQuickGenericJniStub();
9487}
9488
Mathieu Chartiere401d142015-04-22 13:56:20 -07009489void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009490 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009491 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9492 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009493 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009494 }
9495}
9496
Alex Lightdb01a092017-04-03 15:39:55 -07009497void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9498 DCHECK(method->IsObsolete());
9499 // We cannot mess with the entrypoints of native methods because they are used to determine how
9500 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9501 if (!method->IsNative()) {
9502 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9503 }
9504}
9505
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009506void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009507 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009508 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009509 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9510 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009511 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9512 os << "Dumping registered class loaders\n";
9513 size_t class_loader_index = 0;
9514 for (const ClassLoaderData& class_loader : class_loaders_) {
9515 ObjPtr<mirror::ClassLoader> loader =
9516 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9517 if (loader != nullptr) {
9518 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9519 bool saw_one_dex_file = false;
9520 for (const DexCacheData& dex_cache : dex_caches_) {
9521 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9522 if (saw_one_dex_file) {
9523 os << ":";
9524 }
9525 saw_one_dex_file = true;
9526 os << dex_cache.dex_file->GetLocation();
9527 }
9528 }
9529 os << "]";
9530 bool found_parent = false;
9531 if (loader->GetParent() != nullptr) {
9532 size_t parent_index = 0;
9533 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9534 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9535 soa.Self()->DecodeJObject(class_loader2.weak_root));
9536 if (loader2 == loader->GetParent()) {
9537 os << ", parent #" << parent_index;
9538 found_parent = true;
9539 break;
9540 }
9541 parent_index++;
9542 }
9543 if (!found_parent) {
9544 os << ", unregistered parent of type "
9545 << loader->GetParent()->GetClass()->PrettyDescriptor();
9546 }
9547 } else {
9548 os << ", no parent";
9549 }
9550 os << "\n";
9551 }
9552 }
9553 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009554 Runtime* runtime = Runtime::Current();
9555 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9556 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009557}
9558
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009559class CountClassesVisitor : public ClassLoaderVisitor {
9560 public:
9561 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9562
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009563 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009564 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009565 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009566 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009567 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9568 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009569 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009570 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009571
9572 size_t num_zygote_classes;
9573 size_t num_non_zygote_classes;
9574};
9575
9576size_t ClassLinker::NumZygoteClasses() const {
9577 CountClassesVisitor visitor;
9578 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009579 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009580}
9581
9582size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009583 CountClassesVisitor visitor;
9584 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009585 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009586}
9587
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009588size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009589 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009590 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009591 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009592}
9593
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009594pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009595 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009596}
9597
9598pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009599 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009600}
9601
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009602void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009603 DCHECK(!init_done_);
9604
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009605 DCHECK(klass != nullptr);
9606 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009607
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009608 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009609 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009610 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9611 int32_t index = static_cast<int32_t>(class_root);
9612 DCHECK(class_roots->Get(index) == nullptr);
9613 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009614}
9615
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009616ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9617 Thread* self,
9618 const std::vector<const DexFile*>& dex_files,
9619 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009620 Handle<mirror::ClassLoader> parent_loader,
9621 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009622
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009623 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009624
Mathieu Chartierc7853442015-03-27 14:35:38 -07009625 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009626 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009627
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009628 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009629 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009630 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009631 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009632 mirror::ObjectArray<mirror::Object>::Alloc(self,
9633 dex_elements_class.Get(),
9634 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009635 Handle<mirror::Class> h_dex_element_class =
9636 hs.NewHandle(dex_elements_class->GetComponentType());
9637
Mathieu Chartierc7853442015-03-27 14:35:38 -07009638 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009639 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009640 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009641
Andreas Gampe08883de2016-11-08 13:20:52 -08009642 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009643 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009644
Andreas Gampe08883de2016-11-08 13:20:52 -08009645 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009646 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009647
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009648 // Fill the elements array.
9649 int32_t index = 0;
9650 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009651 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009652
Calin Juravle7865ac72017-06-28 11:03:12 -07009653 // CreateWellKnownClassLoader is only used by gtests and compiler.
9654 // 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 -07009655 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9656 self,
9657 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009658 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009659 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009660
Mathieu Chartier3738e982017-05-12 16:07:28 -07009661 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9662 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009663 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009664 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009665 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009666 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009667
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009668 Handle<mirror::String> h_file_name = hs2.NewHandle(
9669 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009670 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009671 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9672
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009673 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009674 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009675 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009676
9677 h_dex_elements->Set(index, h_element.Get());
9678 index++;
9679 }
9680 DCHECK_EQ(index, h_dex_elements->GetLength());
9681
9682 // Create DexPathList.
9683 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009684 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009685 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009686 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009687 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009688 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9689 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9690 // elements.
9691 {
9692 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9693 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9694 DCHECK(native_lib_dirs != nullptr);
9695 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9696 DCHECK(list_class != nullptr);
9697 {
9698 StackHandleScope<1> h_list_scope(self);
9699 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9700 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9701 DCHECK(list_init);
9702 list_class = h_list_class.Get();
9703 }
9704 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9705 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9706 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9707 // normally never null), as long as one does not try to add elements, this will still
9708 // work.
9709 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9710 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009711
Calin Juravle7865ac72017-06-28 11:03:12 -07009712 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009713 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9714 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009715 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009716 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009717 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009718 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009719 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009720 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009721
9722 // Make a pretend boot-classpath.
9723 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009724 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009725 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009726 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009727 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009728 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009729 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009730 if (parent_loader.Get() == nullptr) {
9731 ScopedObjectAccessUnchecked soa(self);
9732 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9733 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9734 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9735 } else {
9736 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9737 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009738
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009739 ArtField* shared_libraries_field =
9740 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9741 DCHECK(shared_libraries_field != nullptr);
9742 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9743
9744 return h_class_loader.Get();
9745}
9746
9747jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9748 const std::vector<const DexFile*>& dex_files,
9749 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009750 jobject parent_loader,
9751 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009752 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9753 WellKnownClasses::dalvik_system_PathClassLoader) ||
9754 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009755 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9756 self->GetJniEnv()->IsSameObject(loader_class,
9757 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009758
9759 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9760 // We could move the jobject to the callers, but all call-sites do this...
9761 ScopedObjectAccessUnchecked soa(self);
9762
9763 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009764 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009765
9766 Handle<mirror::Class> h_loader_class =
9767 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009768 Handle<mirror::ClassLoader> h_parent =
9769 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9770 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9771 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009772
9773 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9774 self,
9775 dex_files,
9776 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009777 h_parent,
9778 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009779
9780 // Make it a global ref and return.
9781 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009782 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009783 return soa.Env()->NewGlobalRef(local_ref.get());
9784}
9785
Calin Juravle7865ac72017-06-28 11:03:12 -07009786jobject ClassLinker::CreatePathClassLoader(Thread* self,
9787 const std::vector<const DexFile*>& dex_files) {
9788 return CreateWellKnownClassLoader(self,
9789 dex_files,
9790 WellKnownClasses::dalvik_system_PathClassLoader,
9791 nullptr);
9792}
9793
Andreas Gampe8ac75952015-06-02 21:01:45 -07009794void ClassLinker::DropFindArrayClassCache() {
9795 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9796 find_array_class_cache_next_victim_ = 0;
9797}
9798
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009799void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009800 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009801 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009802 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009803 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9804 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009805 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009806 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009807 }
9808 }
9809}
9810
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009811void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9812 for (const ClassLoaderData& data : class_loaders_) {
9813 LinearAlloc* alloc = data.allocator;
9814 if (alloc != nullptr && !visitor->Visit(alloc)) {
9815 break;
9816 }
9817 }
9818}
9819
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009820void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9821 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009822 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009823 Thread* const self = Thread::Current();
9824 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009825 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009826 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009827 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009828 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9829 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009830 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009831 }
9832}
9833
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009834void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009835 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009836 std::vector<ClassLoaderData> to_delete;
9837 // Do the delete outside the lock to avoid lock violation in jit code cache.
9838 {
9839 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9840 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9841 const ClassLoaderData& data = *it;
9842 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009843 ObjPtr<mirror::ClassLoader> class_loader =
9844 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009845 if (class_loader != nullptr) {
9846 ++it;
9847 } else {
9848 VLOG(class_linker) << "Freeing class loader";
9849 to_delete.push_back(data);
9850 it = class_loaders_.erase(it);
9851 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009852 }
9853 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009854 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009855 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009856 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009857 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009858}
9859
Mathieu Chartier65975772016-08-05 10:46:36 -07009860class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9861 public:
9862 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9863 : method_(method),
9864 pointer_size_(pointer_size) {}
9865
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009866 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009867 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9868 holder_ = klass;
9869 }
9870 // Return false to stop searching if holder_ is not null.
9871 return holder_ == nullptr;
9872 }
9873
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009874 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009875 const ArtMethod* const method_;
9876 const PointerSize pointer_size_;
9877};
9878
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009879ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009880 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9881 CHECK(method->IsCopied());
9882 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9883 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009884 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009885}
9886
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009887ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9888 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009889 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009890 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009891 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009892}
9893
Vladimir Markod1f73512020-04-02 10:50:35 +01009894bool ClassLinker::IsUpdatableBootClassPathDescriptor(const char* descriptor ATTRIBUTE_UNUSED) {
9895 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
9896 LOG(FATAL) << "UNREACHABLE";
9897 UNREACHABLE();
9898}
9899
Calin Juravle33787682019-07-26 14:27:18 -07009900bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
9901 REQUIRES_SHARED(Locks::mutator_lock_) {
9902 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
9903 LOG(FATAL) << "UNREACHABLE";
9904 UNREACHABLE();
9905}
9906
9907bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
9908 REQUIRES_SHARED(Locks::mutator_lock_) {
9909 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
9910 LOG(FATAL) << "UNREACHABLE";
9911 UNREACHABLE();
9912}
9913
9914bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
9915 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
9916 LOG(FATAL) << "UNREACHABLE";
9917 UNREACHABLE();
9918}
9919
Roland Levillain0e840272018-08-23 19:55:30 +01009920// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009921template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009922 uint32_t method_idx,
9923 Handle<mirror::DexCache> dex_cache,
9924 Handle<mirror::ClassLoader> class_loader,
9925 ArtMethod* referrer,
9926 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009927template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009928 uint32_t method_idx,
9929 Handle<mirror::DexCache> dex_cache,
9930 Handle<mirror::ClassLoader> class_loader,
9931 ArtMethod* referrer,
9932 InvokeType type);
9933
Roland Levillain0e840272018-08-23 19:55:30 +01009934// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009935template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009936 Thread* self,
9937 ObjPtr<mirror::Class> java_lang_Class,
9938 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009939template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009940 Thread* self,
9941 ObjPtr<mirror::Class> java_lang_Class,
9942 uint32_t class_size);
9943
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009944} // namespace art