blob: 8080eca0bf99297898cfca8530a7f3970f345b0e [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"
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000132#include "nterp_helpers.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700133#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700134#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700135#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700136#include "oat_file_assistant.h"
137#include "oat_file_manager.h"
138#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700139#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700140#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800141#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700142#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700143#include "thread-inl.h"
Alex Light133987d2020-03-26 19:22:12 +0000144#include "thread.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700145#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700146#include "trace.h"
Vladimir Markob68bb7a2020-03-17 10:55:25 +0000147#include "transaction.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700148#include "verifier/class_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700149#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700150
Nicolas Geoffray00391822019-12-10 10:17:23 +0000151#include "interpreter/interpreter_mterp_impl.h"
152
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700153namespace art {
154
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800155using android::base::StringPrintf;
156
Orion Hodson5880c772020-07-28 20:12:08 +0100157static constexpr bool kCheckImageObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700158static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700159
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700160static void ThrowNoClassDefFoundError(const char* fmt, ...)
161 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700162 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700163static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700164 va_list args;
165 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800166 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000167 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800168 va_end(args);
169}
170
Andreas Gampe99babb62015-11-02 16:20:00 -0800171static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700172 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700173 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700174 StackHandleScope<1> hs(self);
175 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700176 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700177 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700178
179 if (exception_class == nullptr) {
180 // No exc class ~ no <init>-with-string.
181 CHECK(self->IsExceptionPending());
182 self->ClearException();
183 return false;
184 }
185
Vladimir Markoba118822017-06-12 15:41:56 +0100186 ArtMethod* exception_init_method = exception_class->FindConstructor(
187 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700188 return exception_init_method != nullptr;
189}
190
Vladimir Markobb206de2019-03-28 10:30:32 +0000191static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700192 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700193 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
194 if (ext == nullptr) {
195 return nullptr;
196 } else {
197 return ext->GetVerifyError();
198 }
199}
200
201// Helper for ThrowEarlierClassFailure. Throws the stored error.
202static void HandleEarlierVerifyError(Thread* self,
203 ClassLinker* class_linker,
204 ObjPtr<mirror::Class> c)
205 REQUIRES_SHARED(Locks::mutator_lock_) {
206 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800207 DCHECK(obj != nullptr);
208 self->AssertNoPendingException();
209 if (obj->IsClass()) {
210 // Previous error has been stored as class. Create a new exception of that type.
211
212 // It's possible the exception doesn't have a <init>(String).
213 std::string temp;
214 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
215
216 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700217 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800218 } else {
219 self->ThrowNewException(descriptor, nullptr);
220 }
221 } else {
222 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100223 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700224 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800225 CHECK(throwable_class->IsAssignableFrom(error_class));
226 self->SetException(obj->AsThrowable());
227 }
228 self->AssertPendingException();
229}
230
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000231static void ChangeInterpreterBridgeToNterp(ArtMethod* method, ClassLinker* class_linker)
232 REQUIRES_SHARED(Locks::mutator_lock_) {
233 Runtime* runtime = Runtime::Current();
234 if (class_linker->IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode()) &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000235 CanMethodUseNterp(method)) {
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000236 if (method->GetDeclaringClass()->IsVisiblyInitialized() ||
237 !NeedsClinitCheckBeforeCall(method)) {
238 runtime->GetInstrumentation()->UpdateMethodsCode(method, interpreter::GetNterpEntryPoint());
239 } else {
240 // Put the resolution stub, which will initialize the class and then
241 // call the method with nterp.
242 runtime->GetInstrumentation()->UpdateMethodsCode(method, GetQuickResolutionStub());
243 }
244 }
245}
246
Andreas Gampe5b20b352018-10-11 19:03:20 -0700247// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
248// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
249// before.
Andreas Gampe5b20b352018-10-11 19:03:20 -0700250static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
251 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray00391822019-12-10 10:17:23 +0000252 Runtime* runtime = Runtime::Current();
253 ClassLinker* class_linker = runtime->GetClassLinker();
Andreas Gampe5b20b352018-10-11 19:03:20 -0700254 if (!klass->WasVerificationAttempted()) {
255 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
256 klass->SetVerificationAttempted();
Nicolas Geoffray00391822019-12-10 10:17:23 +0000257 // Now that the class has passed verification, try to set nterp entrypoints
258 // to methods that currently use the switch interpreter.
259 if (interpreter::CanRuntimeUseNterp()) {
260 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Nicolas Geoffray60d4abc2020-07-27 13:58:51 +0000261 ChangeInterpreterBridgeToNterp(&m, class_linker);
Nicolas Geoffray00391822019-12-10 10:17:23 +0000262 }
263 }
Andreas Gampe5b20b352018-10-11 19:03:20 -0700264 }
265}
266
Vladimir Markobf121912019-06-04 13:49:05 +0100267// Callback responsible for making a batch of classes visibly initialized
268// after all threads have called it from a checkpoint, ensuring visibility.
269class ClassLinker::VisiblyInitializedCallback final
270 : public Closure, public IntrusiveForwardListNode<VisiblyInitializedCallback> {
271 public:
272 explicit VisiblyInitializedCallback(ClassLinker* class_linker)
273 : class_linker_(class_linker),
274 num_classes_(0u),
275 thread_visibility_counter_(0),
276 barriers_() {
277 std::fill_n(classes_, kMaxClasses, nullptr);
278 }
279
280 bool IsEmpty() const {
281 DCHECK_LE(num_classes_, kMaxClasses);
282 return num_classes_ == 0u;
283 }
284
285 bool IsFull() const {
286 DCHECK_LE(num_classes_, kMaxClasses);
287 return num_classes_ == kMaxClasses;
288 }
289
290 void AddClass(Thread* self, ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
291 DCHECK_EQ(klass->GetStatus(), ClassStatus::kInitialized);
292 DCHECK(!IsFull());
293 classes_[num_classes_] = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, klass);
294 ++num_classes_;
295 }
296
297 void AddBarrier(Barrier* barrier) {
298 barriers_.push_front(barrier);
299 }
300
301 std::forward_list<Barrier*> GetAndClearBarriers() {
302 std::forward_list<Barrier*> result;
303 result.swap(barriers_);
304 result.reverse(); // Return barriers in insertion order.
305 return result;
306 }
307
308 void MakeVisible(Thread* self) {
309 DCHECK_EQ(thread_visibility_counter_.load(std::memory_order_relaxed), 0);
310 size_t count = Runtime::Current()->GetThreadList()->RunCheckpoint(this);
311 AdjustThreadVisibilityCounter(self, count);
312 }
313
314 void Run(Thread* self) override {
315 self->ClearMakeVisiblyInitializedCounter();
316 AdjustThreadVisibilityCounter(self, -1);
317 }
318
319 private:
320 void AdjustThreadVisibilityCounter(Thread* self, ssize_t adjustment) {
321 ssize_t old = thread_visibility_counter_.fetch_add(adjustment, std::memory_order_relaxed);
322 if (old + adjustment == 0) {
323 // All threads passed the checkpoint. Mark classes as visibly initialized.
324 {
325 ScopedObjectAccess soa(self);
326 StackHandleScope<1u> hs(self);
327 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
328 JavaVMExt* vm = self->GetJniEnv()->GetVm();
329 for (size_t i = 0, num = num_classes_; i != num; ++i) {
330 klass.Assign(ObjPtr<mirror::Class>::DownCast(self->DecodeJObject(classes_[i])));
331 vm->DeleteWeakGlobalRef(self, classes_[i]);
332 if (klass != nullptr) {
Vladimir Markobf121912019-06-04 13:49:05 +0100333 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100334 class_linker_->FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100335 }
336 }
337 num_classes_ = 0u;
338 }
339 class_linker_->VisiblyInitializedCallbackDone(self, this);
340 }
341 }
342
Vladimir Marko9f18fbc2019-07-31 15:06:12 +0100343 static constexpr size_t kMaxClasses = 16;
Vladimir Markobf121912019-06-04 13:49:05 +0100344
345 ClassLinker* const class_linker_;
346 size_t num_classes_;
347 jweak classes_[kMaxClasses];
348
349 // The thread visibility counter starts at 0 and it is incremented by the number of
350 // threads that need to run this callback (by the thread that request the callback
351 // to be run) and decremented once for each `Run()` execution. When it reaches 0,
352 // whether after the increment or after a decrement, we know that `Run()` was executed
353 // for all threads and therefore we can mark the classes as visibly initialized.
354 std::atomic<ssize_t> thread_visibility_counter_;
355
356 // List of barries to `Pass()` for threads that wait for the callback to complete.
357 std::forward_list<Barrier*> barriers_;
358};
359
360void ClassLinker::MakeInitializedClassesVisiblyInitialized(Thread* self, bool wait) {
361 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
362 return; // Nothing to do. Thanks to the x86 memory model classes skip the initialized status.
363 }
364 std::optional<Barrier> maybe_barrier; // Avoid constructing the Barrier for `wait == false`.
365 if (wait) {
366 maybe_barrier.emplace(0);
367 }
368 int wait_count = 0;
369 VisiblyInitializedCallback* callback = nullptr;
370 {
371 MutexLock lock(self, visibly_initialized_callback_lock_);
372 if (visibly_initialized_callback_ != nullptr && !visibly_initialized_callback_->IsEmpty()) {
373 callback = visibly_initialized_callback_.release();
374 running_visibly_initialized_callbacks_.push_front(*callback);
375 }
376 if (wait) {
377 DCHECK(maybe_barrier.has_value());
378 Barrier* barrier = std::addressof(*maybe_barrier);
379 for (VisiblyInitializedCallback& cb : running_visibly_initialized_callbacks_) {
380 cb.AddBarrier(barrier);
381 ++wait_count;
382 }
383 }
384 }
385 if (callback != nullptr) {
386 callback->MakeVisible(self);
387 }
388 if (wait_count != 0) {
389 DCHECK(maybe_barrier.has_value());
390 maybe_barrier->Increment(self, wait_count);
391 }
392}
393
394void ClassLinker::VisiblyInitializedCallbackDone(Thread* self,
395 VisiblyInitializedCallback* callback) {
396 MutexLock lock(self, visibly_initialized_callback_lock_);
397 // Pass the barriers if requested.
398 for (Barrier* barrier : callback->GetAndClearBarriers()) {
399 barrier->Pass(self);
400 }
401 // Remove the callback from the list of running callbacks.
402 auto before = running_visibly_initialized_callbacks_.before_begin();
403 auto it = running_visibly_initialized_callbacks_.begin();
404 DCHECK(it != running_visibly_initialized_callbacks_.end());
405 while (std::addressof(*it) != callback) {
406 before = it;
407 ++it;
408 DCHECK(it != running_visibly_initialized_callbacks_.end());
409 }
410 running_visibly_initialized_callbacks_.erase_after(before);
411 // Reuse or destroy the callback object.
412 if (visibly_initialized_callback_ == nullptr) {
413 visibly_initialized_callback_.reset(callback);
414 } else {
415 delete callback;
416 }
417}
418
Alex Lightfb119572019-09-18 15:04:53 -0700419void ClassLinker::ForceClassInitialized(Thread* self, Handle<mirror::Class> klass) {
420 ClassLinker::VisiblyInitializedCallback* cb = MarkClassInitialized(self, klass);
421 if (cb != nullptr) {
422 cb->MakeVisible(self);
423 }
424 ScopedThreadSuspension sts(self, ThreadState::kSuspended);
425 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/true);
426}
427
Vladimir Markobf121912019-06-04 13:49:05 +0100428ClassLinker::VisiblyInitializedCallback* ClassLinker::MarkClassInitialized(
429 Thread* self, Handle<mirror::Class> klass) {
430 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
431 // Thanks to the x86 memory model, we do not need any memory fences and
432 // we can immediately mark the class as visibly initialized.
433 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100434 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100435 return nullptr;
436 }
437 if (Runtime::Current()->IsActiveTransaction()) {
438 // Transactions are single-threaded, so we can mark the class as visibly intialized.
439 // (Otherwise we'd need to track the callback's entry in the transaction for rollback.)
440 mirror::Class::SetStatus(klass, ClassStatus::kVisiblyInitialized, self);
Vladimir Marko86c87522020-05-11 16:55:55 +0100441 FixupStaticTrampolines(self, klass.Get());
Vladimir Markobf121912019-06-04 13:49:05 +0100442 return nullptr;
443 }
444 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
445 MutexLock lock(self, visibly_initialized_callback_lock_);
446 if (visibly_initialized_callback_ == nullptr) {
447 visibly_initialized_callback_.reset(new VisiblyInitializedCallback(this));
448 }
449 DCHECK(!visibly_initialized_callback_->IsFull());
450 visibly_initialized_callback_->AddClass(self, klass.Get());
451
452 if (visibly_initialized_callback_->IsFull()) {
453 VisiblyInitializedCallback* callback = visibly_initialized_callback_.release();
454 running_visibly_initialized_callbacks_.push_front(*callback);
455 return callback;
456 } else {
457 return nullptr;
458 }
459}
460
Vladimir Marko86c87522020-05-11 16:55:55 +0100461const void* ClassLinker::RegisterNative(
462 Thread* self, ArtMethod* method, const void* native_method) {
463 CHECK(method->IsNative()) << method->PrettyMethod();
464 CHECK(native_method != nullptr) << method->PrettyMethod();
465 void* new_native_method = nullptr;
466 Runtime* runtime = Runtime::Current();
467 runtime->GetRuntimeCallbacks()->RegisterNativeMethod(method,
468 native_method,
469 /*out*/&new_native_method);
470 if (method->IsCriticalNative()) {
471 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
472 // Remove old registered method if any.
473 auto it = critical_native_code_with_clinit_check_.find(method);
474 if (it != critical_native_code_with_clinit_check_.end()) {
475 critical_native_code_with_clinit_check_.erase(it);
476 }
477 // To ensure correct memory visibility, we need the class to be visibly
478 // initialized before we can set the JNI entrypoint.
479 if (method->GetDeclaringClass()->IsVisiblyInitialized()) {
480 method->SetEntryPointFromJni(new_native_method);
481 } else {
482 critical_native_code_with_clinit_check_.emplace(method, new_native_method);
483 }
484 } else {
485 method->SetEntryPointFromJni(new_native_method);
486 }
487 return new_native_method;
488}
489
490void ClassLinker::UnregisterNative(Thread* self, ArtMethod* method) {
491 CHECK(method->IsNative()) << method->PrettyMethod();
492 // Restore stub to lookup native pointer via dlsym.
493 if (method->IsCriticalNative()) {
494 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
495 auto it = critical_native_code_with_clinit_check_.find(method);
496 if (it != critical_native_code_with_clinit_check_.end()) {
497 critical_native_code_with_clinit_check_.erase(it);
498 }
499 method->SetEntryPointFromJni(GetJniDlsymLookupCriticalStub());
500 } else {
501 method->SetEntryPointFromJni(GetJniDlsymLookupStub());
502 }
503}
504
505const void* ClassLinker::GetRegisteredNative(Thread* self, ArtMethod* method) {
506 if (method->IsCriticalNative()) {
507 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
508 auto it = critical_native_code_with_clinit_check_.find(method);
509 if (it != critical_native_code_with_clinit_check_.end()) {
510 return it->second;
511 }
512 const void* native_code = method->GetEntryPointFromJni();
513 return IsJniDlsymLookupCriticalStub(native_code) ? nullptr : native_code;
514 } else {
515 const void* native_code = method->GetEntryPointFromJni();
516 return IsJniDlsymLookupStub(native_code) ? nullptr : native_code;
517 }
518}
519
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800520void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
521 bool wrap_in_no_class_def,
522 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700523 // The class failed to initialize on a previous attempt, so we want to throw
524 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
525 // failed in verification, in which case v2 5.4.1 says we need to re-throw
526 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800527 Runtime* const runtime = Runtime::Current();
528 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700529 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000530 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
531 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800532 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700533 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800534 } else {
535 extra = verify_error->AsThrowable()->Dump();
536 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700537 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800538 if (log) {
539 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
540 << ": " << extra;
541 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700542 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700543
David Sehr709b0702016-10-13 09:12:37 -0700544 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800545 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800546 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700547 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700548 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000549 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700550 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000551 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
552 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800553 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800554 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800555 }
Alex Lightd6251582016-10-31 11:12:30 -0700556 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
557 // might have meant to go down the earlier if statement with the original error but it got
558 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000559 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800560 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
561 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
562 // exception will be a cause.
563 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700564 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700565 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700566 }
567}
568
Brian Carlstromb23eab12014-10-08 17:55:21 -0700569static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700570 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700571 if (VLOG_IS_ON(class_linker)) {
572 std::string temp;
573 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000574 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700575 }
576}
577
578static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700579 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700580 Thread* self = Thread::Current();
581 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700582
583 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700584 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700585
David Srbecky346fd962020-07-27 16:51:00 +0100586 // Boot classpath classes should not fail initialization. This is a consistency debug check.
587 // This cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800588 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800589 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800590 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
591 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
592 // could have caused the error.
593 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
594 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
595 << " failed initialization: "
596 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800597 }
598
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700599 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700600 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
601 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700602
Elliott Hughesa4f94742012-05-29 16:28:38 -0700603 // We only wrap non-Error exceptions; an Error can just be used as-is.
604 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000605 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700606 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700607 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700608}
609
Andreas Gampe87658f32019-04-18 18:39:02 +0000610ClassLinker::ClassLinker(InternTable* intern_table, bool fast_class_not_found_exceptions)
Andreas Gampe2af99022017-04-25 08:32:59 -0700611 : boot_class_table_(new ClassTable()),
612 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800613 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800614 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700615 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000616 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700617 intern_table_(intern_table),
Andreas Gampe87658f32019-04-18 18:39:02 +0000618 fast_class_not_found_exceptions_(fast_class_not_found_exceptions),
Vladimir Marko7dac8642019-11-06 17:09:30 +0000619 jni_dlsym_lookup_trampoline_(nullptr),
Vladimir Markofa458ac2020-02-12 14:08:07 +0000620 jni_dlsym_lookup_critical_trampoline_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800621 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800622 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100623 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800624 quick_to_interpreter_bridge_trampoline_(nullptr),
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000625 nterp_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700626 image_pointer_size_(kRuntimePointerSize),
Vladimir Markobf121912019-06-04 13:49:05 +0100627 visibly_initialized_callback_lock_("visibly initialized callback lock"),
628 visibly_initialized_callback_(nullptr),
Vladimir Marko86c87522020-05-11 16:55:55 +0100629 critical_native_code_with_clinit_check_lock_("critical native code with clinit check lock"),
630 critical_native_code_with_clinit_check_(),
Andreas Gampe7dface32017-07-25 21:32:59 -0700631 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
632 // For CHA disabled during Aot, see b/34193647.
633
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700634 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700635 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
636 "Array cache size wrong.");
637 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700638}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700639
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800640void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700641 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800642 if (c2 == nullptr) {
643 LOG(FATAL) << "Could not find class " << descriptor;
644 UNREACHABLE();
645 }
646 if (c1.Get() != c2) {
647 std::ostringstream os1, os2;
648 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
649 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
650 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
651 << ". This is most likely the result of a broken build. Make sure that "
652 << "libcore and art projects match.\n\n"
653 << os1.str() << "\n\n" << os2.str();
654 UNREACHABLE();
655 }
656}
657
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800658bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
659 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800660 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700661
Mathieu Chartiere401d142015-04-22 13:56:20 -0700662 Thread* const self = Thread::Current();
663 Runtime* const runtime = Runtime::Current();
664 gc::Heap* const heap = runtime->GetHeap();
665
Jeff Haodcdc85b2015-12-04 14:06:18 -0800666 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700667 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700668
Mathieu Chartiere401d142015-04-22 13:56:20 -0700669 // Use the pointer size from the runtime since we are probably creating the image.
670 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
671
Elliott Hughes30646832011-10-13 16:59:46 -0700672 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700673 // 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 -0800674 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700675 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700676 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700677 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
678 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000679 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100680 heap->AllocNonMovableObject(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800681 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100682 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700683 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700684 if (kUseBakerReadBarrier) {
685 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800686 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700687 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700688 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800689 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700690 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700691
Elliott Hughes418d20f2011-09-22 14:00:39 -0700692 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700693 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700694 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700695 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700696 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700697
Ian Rogers23435d02012-09-24 11:23:12 -0700698 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700699 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700700 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800701 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700702 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700703 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000704 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700705
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700706 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800707 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
708 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Vladimir Marko991cd5c2019-05-30 14:23:39 +0100709 runtime->SetSentinel(heap->AllocNonMovableObject(self,
710 java_lang_Object.Get(),
711 java_lang_Object->GetObjectSize(),
712 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700713
Igor Murashkin86083f72017-10-27 10:59:04 -0700714 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000715 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700716 // It might seem the lock here is unnecessary, however all the SubtypeCheck
717 // functions are annotated to require locks all the way down.
718 //
719 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
720 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000721 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
722 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700723 }
724
Ian Rogers23435d02012-09-24 11:23:12 -0700725 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700726 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700727 AllocClass(self, java_lang_Class.Get(),
728 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700729 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700730
Roland Levillain0e840272018-08-23 19:55:30 +0100731 // Setup java.lang.String.
732 //
733 // We make this class non-movable for the unlikely case where it were to be
734 // moved by a sticky-bit (minor) collection when using the Generational
735 // Concurrent Copying (CC) collector, potentially creating a stale reference
736 // in the `klass_` field of one of its instances allocated in the Large-Object
737 // Space (LOS) -- see the comment about the dirty card scanning logic in
738 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700739 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700740 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100741 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700742 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000743 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400744
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700745 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700746 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700747 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700748 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000749 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700750
Ian Rogers23435d02012-09-24 11:23:12 -0700751 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700752 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100753 mirror::ObjectArray<mirror::Class>::Alloc(self,
754 object_array_class.Get(),
755 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700756 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100757 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
758 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
759 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
760 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100761 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
762 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700763
Mathieu Chartier6beced42016-11-15 15:51:31 -0800764 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
765 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
766
Vladimir Marko02610552018-06-04 14:38:00 +0100767 // Create array interface entries to populate once we can load system classes.
768 object_array_class->SetIfTable(AllocIfTable(self, 2));
769 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
770
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700771 // Setup the primitive type classes.
Vladimir Marko70e2a762019-07-12 16:49:00 +0100772 CreatePrimitiveClass(self, Primitive::kPrimBoolean, ClassRoot::kPrimitiveBoolean);
773 CreatePrimitiveClass(self, Primitive::kPrimByte, ClassRoot::kPrimitiveByte);
774 CreatePrimitiveClass(self, Primitive::kPrimChar, ClassRoot::kPrimitiveChar);
775 CreatePrimitiveClass(self, Primitive::kPrimShort, ClassRoot::kPrimitiveShort);
776 CreatePrimitiveClass(self, Primitive::kPrimInt, ClassRoot::kPrimitiveInt);
777 CreatePrimitiveClass(self, Primitive::kPrimLong, ClassRoot::kPrimitiveLong);
778 CreatePrimitiveClass(self, Primitive::kPrimFloat, ClassRoot::kPrimitiveFloat);
779 CreatePrimitiveClass(self, Primitive::kPrimDouble, ClassRoot::kPrimitiveDouble);
780 CreatePrimitiveClass(self, Primitive::kPrimVoid, ClassRoot::kPrimitiveVoid);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700781
Vladimir Marko70e2a762019-07-12 16:49:00 +0100782 // Allocate the primitive array classes. We need only the native pointer
783 // array at this point (int[] or long[], depending on architecture) but
784 // we shall perform the same setup steps for all primitive array classes.
785 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveBoolean, ClassRoot::kBooleanArrayClass);
786 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveByte, ClassRoot::kByteArrayClass);
787 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveChar, ClassRoot::kCharArrayClass);
788 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveShort, ClassRoot::kShortArrayClass);
789 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveInt, ClassRoot::kIntArrayClass);
790 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveLong, ClassRoot::kLongArrayClass);
791 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveFloat, ClassRoot::kFloatArrayClass);
792 AllocPrimitiveArrayClass(self, ClassRoot::kPrimitiveDouble, ClassRoot::kDoubleArrayClass);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700793
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700794 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700795
Ian Rogers52813c92012-10-11 11:50:38 -0700796 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700797 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700798 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100799 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100800 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700801 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000802 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700803
Alex Lightd6251582016-10-31 11:12:30 -0700804
805 // Setup dalvik.system.ClassExt
806 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
807 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100808 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000809 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700810
Mathieu Chartier66f19252012-09-18 08:57:04 -0700811 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700812 Handle<mirror::Class> object_array_string(hs.NewHandle(
813 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700814 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700815 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100816 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700817
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000818 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700819 // Create runtime resolution and imt conflict methods.
820 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000821 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
822 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700823
Ian Rogers23435d02012-09-24 11:23:12 -0700824 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
825 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
826 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800827 if (boot_class_path.empty()) {
828 *error_msg = "Boot classpath is empty.";
829 return false;
830 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800831 for (auto& dex_file : boot_class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800832 if (dex_file == nullptr) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800833 *error_msg = "Null dex file.";
834 return false;
835 }
Mathieu Chartier0a19e212019-11-27 14:35:24 -0800836 AppendToBootClassPath(self, dex_file.get());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800837 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700838 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700839
840 // now we can use FindSystemClass
841
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700842 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
843 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700844 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800845 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700846 // We need to set up the generic trampolines since we don't have an image.
Vladimir Marko7dac8642019-11-06 17:09:30 +0000847 jni_dlsym_lookup_trampoline_ = GetJniDlsymLookupStub();
Vladimir Markofa458ac2020-02-12 14:08:07 +0000848 jni_dlsym_lookup_critical_trampoline_ = GetJniDlsymLookupCriticalStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700849 quick_resolution_trampoline_ = GetQuickResolutionStub();
850 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
Vladimir Marko7dac8642019-11-06 17:09:30 +0000851 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700852 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +0000853 nterp_trampoline_ = interpreter::GetNterpEntryPoint();
Alex Light64ad14d2014-08-19 14:23:13 -0700854 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700855
Alex Lightd6251582016-10-31 11:12:30 -0700856 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000857 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800858 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700859 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000860 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800861 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000862 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800863 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700864 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000865 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700866 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
867 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700868
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800869 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
870 // in class_table_.
871 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700872
Vladimir Marko70e2a762019-07-12 16:49:00 +0100873 // Setup core array classes, i.e. Object[], String[] and Class[] and primitive
874 // arrays - can't be done until Object has a vtable and component classes are loaded.
875 FinishCoreArrayClassSetup(ClassRoot::kObjectArrayClass);
876 FinishCoreArrayClassSetup(ClassRoot::kClassArrayClass);
877 FinishCoreArrayClassSetup(ClassRoot::kJavaLangStringArrayClass);
878 FinishCoreArrayClassSetup(ClassRoot::kBooleanArrayClass);
879 FinishCoreArrayClassSetup(ClassRoot::kByteArrayClass);
880 FinishCoreArrayClassSetup(ClassRoot::kCharArrayClass);
881 FinishCoreArrayClassSetup(ClassRoot::kShortArrayClass);
882 FinishCoreArrayClassSetup(ClassRoot::kIntArrayClass);
883 FinishCoreArrayClassSetup(ClassRoot::kLongArrayClass);
884 FinishCoreArrayClassSetup(ClassRoot::kFloatArrayClass);
885 FinishCoreArrayClassSetup(ClassRoot::kDoubleArrayClass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700886
Ian Rogers23435d02012-09-24 11:23:12 -0700887 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700888 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800889 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700890 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800891 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700892 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
893 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100894 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
895 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700896
David Srbecky346fd962020-07-27 16:51:00 +0100897 // Check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread suspension.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700898 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000899 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700900 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000901 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700902 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000903 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700904 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000905 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700906
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700907 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100908 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700909
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800910 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700911
Ian Rogers23435d02012-09-24 11:23:12 -0700912 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100913 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
914 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700915
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700916 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100917 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700918 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100919 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700920
921 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700922 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
923 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100924 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700925
926 // Create java.lang.reflect.Constructor.class root and array root.
927 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
928 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100929 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700930 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
931 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100932 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700933
934 // Create java.lang.reflect.Method.class root and array root.
935 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
936 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100937 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700938 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
939 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100940 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700941
Orion Hodson005ac512017-10-24 15:43:43 +0100942 // Create java.lang.invoke.CallSite.class root
943 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
944 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100945 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100946
Narayan Kamathafa48272016-08-03 12:46:58 +0100947 // Create java.lang.invoke.MethodType.class root
948 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
949 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100950 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100951
952 // Create java.lang.invoke.MethodHandleImpl.class root
953 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
954 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100955 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100956 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100957
Orion Hodsonc069a302017-01-18 09:23:12 +0000958 // Create java.lang.invoke.MethodHandles.Lookup.class root
959 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
960 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100961 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000962
Orion Hodson005ac512017-10-24 15:43:43 +0100963 // Create java.lang.invoke.VarHandle.class root
964 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000965 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100966 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100967
968 // Create java.lang.invoke.FieldVarHandle.class root
969 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
970 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100971 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100972
973 // Create java.lang.invoke.ArrayElementVarHandle.class root
974 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
975 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100976 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100977
978 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
979 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
980 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100981 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100982
983 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
984 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
985 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100986 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000987
Narayan Kamath000e1882016-10-24 17:14:25 +0100988 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
989 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100990 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100991
Brian Carlstrom1f870082011-08-23 16:02:11 -0700992 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700993 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000994 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800995 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700996 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700997 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
998 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700999 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001000 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001001 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001002 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001003 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001004 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001005 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001006 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001007 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001008 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07001009 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001010 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001011
Ian Rogers23435d02012-09-24 11:23:12 -07001012 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001013 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001014 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001015 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001016 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001017
jeffhao8cd6dda2012-02-22 10:15:34 -08001018 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -07001019 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001020 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001021 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -07001022 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001023 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
1024 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
1025 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -07001026 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00001027 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
1028 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -07001029
Mathieu Chartiercdca4762016-04-28 09:44:54 -07001030 // Create conflict tables that depend on the class linker.
1031 runtime->FixupConflictTables();
1032
Ian Rogers98379392014-02-24 16:53:16 -08001033 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001034
Brian Carlstroma004aa92012-02-08 18:05:09 -08001035 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001036
1037 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001038}
1039
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001040static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
1041 REQUIRES_SHARED(Locks::mutator_lock_) {
1042 // Find String.<init> -> StringFactory bindings.
1043 ObjPtr<mirror::Class> string_factory_class =
1044 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
1045 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001046 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001047 WellKnownClasses::InitStringInit(string_class, string_factory_class);
1048 // Update the primordial thread.
1049 self->InitStringEntryPoints();
1050}
1051
Ian Rogers98379392014-02-24 16:53:16 -08001052void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001053 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -07001054
Andreas Gampe9abc31e2018-05-17 11:47:09 -07001055 CreateStringInitBindings(self, this);
1056
Brian Carlstrom16192862011-09-12 17:50:06 -07001057 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -07001058 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -07001059 // as the types of the field can't be resolved prior to the runtime being
1060 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001061 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001062 Handle<mirror::Class> java_lang_ref_Reference =
1063 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001064 Handle<mirror::Class> java_lang_ref_FinalizerReference =
1065 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001066
Mathieu Chartierc7853442015-03-27 14:35:38 -07001067 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001068 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
1069 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001070
Mathieu Chartierc7853442015-03-27 14:35:38 -07001071 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001072 CHECK_STREQ(queue->GetName(), "queue");
1073 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001074
Mathieu Chartierc7853442015-03-27 14:35:38 -07001075 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001076 CHECK_STREQ(queueNext->GetName(), "queueNext");
1077 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001078
Mathieu Chartierc7853442015-03-27 14:35:38 -07001079 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001080 CHECK_STREQ(referent->GetName(), "referent");
1081 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001082
Mathieu Chartierc7853442015-03-27 14:35:38 -07001083 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07001084 CHECK_STREQ(zombie->GetName(), "zombie");
1085 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -07001086
Brian Carlstroma663ea52011-08-19 23:33:41 -07001087 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001088 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001089 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001090 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001091 CHECK(klass != nullptr);
1092 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001093 // note SetClassRoot does additional validation.
1094 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001095 }
1096
Vladimir Marko02610552018-06-04 14:38:00 +01001097 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -07001098
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001099 // disable the slow paths in FindClass and CreatePrimitiveClass now
1100 // that Object, Class, and Object[] are setup
1101 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001102
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001103 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
1104 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
1105 // ensure that the class will be initialized.
1106 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampee0bbab92019-07-25 12:28:22 -07001107 verifier::ClassVerifier::Init(this); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -07001108
1109 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
1110 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
1111 // Strange, but don't crash.
1112 LOG(WARNING) << "Could not prepare StackOverflowError.";
1113 self->ClearException();
1114 }
1115 }
1116
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001117 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001118}
1119
Vladimir Markodcfcce42018-06-27 10:00:28 +00001120void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001121 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
1122 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001123 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001124 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001125 Handle<mirror::Class> h_class(hs.NewHandle(c));
David Srbecky08110ef2020-05-20 19:33:43 +01001126 if (!EnsureInitialized(self, h_class, true, true)) {
1127 LOG(FATAL) << "Exception when initializing " << h_class->PrettyClass()
1128 << ": " << self->GetException()->Dump();
1129 }
Vladimir Markodcfcce42018-06-27 10:00:28 +00001130 } else {
1131 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -07001132 }
1133 }
1134}
1135
Jeff Haodcdc85b2015-12-04 14:06:18 -08001136struct TrampolineCheckData {
1137 const void* quick_resolution_trampoline;
1138 const void* quick_imt_conflict_trampoline;
1139 const void* quick_generic_jni_trampoline;
1140 const void* quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001141 const void* nterp_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001142 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001143 ArtMethod* m;
1144 bool error;
1145};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001146
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001147bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1148 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001149 CHECK(!init_done_);
1150
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001151 Runtime* const runtime = Runtime::Current();
1152 Thread* const self = Thread::Current();
1153 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001154 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1155 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001156 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1157 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001158 if (!ValidPointerSize(pointer_size_unchecked)) {
1159 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001160 return false;
1161 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001162 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001163 if (!runtime->IsAotCompiler()) {
1164 // Only the Aot compiler supports having an image with a different pointer size than the
1165 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1166 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001167 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001168 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001169 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001170 sizeof(void*));
1171 return false;
1172 }
1173 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001174 DCHECK(!runtime->HasResolutionMethod());
1175 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1176 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1177 runtime->SetImtUnimplementedMethod(
1178 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1179 runtime->SetCalleeSaveMethod(
1180 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1181 CalleeSaveType::kSaveAllCalleeSaves);
1182 runtime->SetCalleeSaveMethod(
1183 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1184 CalleeSaveType::kSaveRefsOnly);
1185 runtime->SetCalleeSaveMethod(
1186 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1187 CalleeSaveType::kSaveRefsAndArgs);
1188 runtime->SetCalleeSaveMethod(
1189 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1190 CalleeSaveType::kSaveEverything);
1191 runtime->SetCalleeSaveMethod(
1192 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1193 CalleeSaveType::kSaveEverythingForClinit);
1194 runtime->SetCalleeSaveMethod(
1195 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1196 CalleeSaveType::kSaveEverythingForSuspendCheck);
1197
Jeff Haodcdc85b2015-12-04 14:06:18 -08001198 std::vector<const OatFile*> oat_files =
1199 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1200 DCHECK(!oat_files.empty());
1201 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001202 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001203 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001204 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1205 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1206 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1207 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001208 nterp_trampoline_ = default_oat_header.GetNterpTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001209 if (kIsDebugBuild) {
1210 // Check that the other images use the same trampoline.
1211 for (size_t i = 1; i < oat_files.size(); ++i) {
1212 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001213 const void* ith_jni_dlsym_lookup_trampoline_ =
1214 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001215 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1216 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001217 const void* ith_quick_resolution_trampoline =
1218 ith_oat_header.GetQuickResolutionTrampoline();
1219 const void* ith_quick_imt_conflict_trampoline =
1220 ith_oat_header.GetQuickImtConflictTrampoline();
1221 const void* ith_quick_generic_jni_trampoline =
1222 ith_oat_header.GetQuickGenericJniTrampoline();
1223 const void* ith_quick_to_interpreter_bridge_trampoline =
1224 ith_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001225 const void* ith_nterp_trampoline =
1226 ith_oat_header.GetNterpTrampoline();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001227 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001228 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001229 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001230 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1231 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001232 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_ ||
1233 ith_nterp_trampoline != nterp_trampoline_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001234 // Make sure that all methods in this image do not contain those trampolines as
1235 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1236 TrampolineCheckData data;
1237 data.error = false;
1238 data.pointer_size = GetImagePointerSize();
1239 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1240 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1241 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1242 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001243 data.nterp_trampoline = ith_nterp_trampoline;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001244 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001245 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1246 if (obj->IsClass()) {
1247 ObjPtr<mirror::Class> klass = obj->AsClass();
1248 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1249 const void* entrypoint =
1250 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1251 if (entrypoint == data.quick_resolution_trampoline ||
1252 entrypoint == data.quick_imt_conflict_trampoline ||
1253 entrypoint == data.quick_generic_jni_trampoline ||
1254 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1255 data.m = &m;
1256 data.error = true;
1257 return;
1258 }
1259 }
1260 }
1261 };
1262 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001263 if (data.error) {
1264 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001265 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001266 *error_msg = "Found an ArtMethod with a bad entrypoint";
1267 return false;
1268 }
1269 }
1270 }
1271 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001272
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001273 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001274 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001275 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001276 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001277
Vladimir Marko024d69f2019-06-13 10:52:32 +01001278 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1279 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1280 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1281 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1282 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1283 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001284
Vladimir Markod1908512018-11-22 14:57:28 +00001285 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001286 // Boot class loader, use a null handle.
1287 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001288 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001289 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001290 /*out*/&dex_files,
1291 error_msg)) {
1292 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001293 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001294 // Append opened dex files at the end.
1295 boot_dex_files_.insert(boot_dex_files_.end(),
1296 std::make_move_iterator(dex_files.begin()),
1297 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001298 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001299 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1300 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1301 }
Ian Rogers98379392014-02-24 16:53:16 -08001302 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001303
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001304 VLOG(startup) << __FUNCTION__ << " exiting";
1305 return true;
1306}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001307
Vladimir Marko4433c432018-12-04 14:57:47 +00001308void ClassLinker::AddExtraBootDexFiles(
1309 Thread* self,
1310 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1311 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001312 AppendToBootClassPath(self, dex_file.get());
Orion Hodson771708f2021-01-06 15:45:16 +00001313 if (kIsDebugBuild) {
1314 for (const auto& boot_dex_file : boot_dex_files_) {
1315 DCHECK_NE(boot_dex_file->GetLocation(), dex_file->GetLocation());
1316 }
1317 }
Vladimir Marko4433c432018-12-04 14:57:47 +00001318 boot_dex_files_.push_back(std::move(dex_file));
1319 }
1320}
1321
Jeff Hao5872d7c2016-04-27 11:07:41 -07001322bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001323 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001324 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001325 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1326 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001327}
1328
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001329class CHAOnDeleteUpdateClassVisitor {
1330 public:
1331 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1332 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1333 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1334 self_(Thread::Current()) {}
1335
1336 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1337 // This class is going to be unloaded. Tell CHA about it.
1338 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1339 return true;
1340 }
1341 private:
1342 const LinearAlloc* allocator_;
1343 const ClassHierarchyAnalysis* cha_;
1344 const PointerSize pointer_size_;
1345 const Thread* self_;
1346};
1347
Chris Wailes0c61be42018-09-26 17:27:34 -07001348/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001349 * A class used to ensure that all references to strings interned in an AppImage have been
1350 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001351 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001352class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001353 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001354 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1355 const InternTable::UnorderedSet& image_interns)
1356 : space_(space),
1357 image_interns_(image_interns),
1358 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001359
Chris Wailes0c61be42018-09-26 17:27:34 -07001360 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001361 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001362 if (referred_obj != nullptr &&
1363 space_.HasAddress(referred_obj.Ptr()) &&
1364 referred_obj->IsString()) {
1365 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001366 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1367 if (it != image_interns_.end() && it->Read() == referred_str) {
1368 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001369 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001370 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001371 }
1372
Chris Wailes0c61be42018-09-26 17:27:34 -07001373 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001374 mirror::CompressedReference<mirror::Object>* root) const
1375 REQUIRES_SHARED(Locks::mutator_lock_) {
1376 if (!root->IsNull()) {
1377 VisitRoot(root);
1378 }
1379 }
1380
Chris Wailes0c61be42018-09-26 17:27:34 -07001381 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001382 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001383 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001384 }
1385
1386 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001387 void operator()(ObjPtr<mirror::Object> obj,
1388 MemberOffset offset,
1389 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001390 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001391 // References within image or across images don't need a read barrier.
1392 ObjPtr<mirror::Object> referred_obj =
1393 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1394 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001395 }
1396
1397 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1398 ObjPtr<mirror::Reference> ref) const
1399 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001400 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001401 }
1402
Vladimir Marko8e05f092019-06-10 11:10:38 +01001403 size_t GetCount() const {
1404 return count_;
1405 }
1406
1407 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001408 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001409 const InternTable::UnorderedSet& image_interns_;
1410 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001411};
1412
Chris Wailes0c61be42018-09-26 17:27:34 -07001413/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001414 * This function counts references to strings interned in the AppImage.
1415 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001416 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001417size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1418 const InternTable::UnorderedSet& image_interns)
1419 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001420 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1421 const ImageHeader& image_header = space.GetImageHeader();
1422 const uint8_t* target_base = space.GetMemMap()->Begin();
1423 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001424
1425 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1426 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001427
Vladimir Marko8e05f092019-06-10 11:10:38 +01001428 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001429 bitmap->VisitMarkedRange(objects_begin,
1430 objects_end,
1431 [&space, &visitor](mirror::Object* obj)
1432 REQUIRES_SHARED(Locks::mutator_lock_) {
1433 if (space.HasAddress(obj)) {
1434 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001435 obj->VisitReferences</* kVisitNativeRoots= */ true,
1436 kVerifyNone,
1437 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001438 } else {
1439 // Don't visit native roots for non-dex-cache as they can't contain
1440 // native references to strings. This is verified during compilation
1441 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001442 obj->VisitReferences</* kVisitNativeRoots= */ false,
1443 kVerifyNone,
1444 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001445 }
1446 }
1447 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001448 return visitor.GetCount();
1449}
1450
1451template <typename Visitor>
1452static void VisitInternedStringReferences(
1453 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001454 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1455 const uint8_t* target_base = space->Begin();
1456 const ImageSection& sro_section =
1457 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1458 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1459
1460 VLOG(image)
1461 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1462 << num_string_offsets;
1463
1464 const auto* sro_base =
1465 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1466
1467 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1468 uint32_t base_offset = sro_base[offset_index].first;
1469
David Srbecky86d6cd52020-12-02 18:13:10 +00001470 uint32_t raw_member_offset = sro_base[offset_index].second;
1471 DCHECK_ALIGNED(base_offset, 2);
1472 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001473
David Srbecky86d6cd52020-12-02 18:13:10 +00001474 ObjPtr<mirror::Object> obj_ptr =
1475 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1476 MemberOffset member_offset(raw_member_offset);
1477 ObjPtr<mirror::String> referred_string =
1478 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001479 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001480 kWithoutReadBarrier,
1481 /* kIsVolatile= */ false>(member_offset);
1482 DCHECK(referred_string != nullptr);
1483
1484 ObjPtr<mirror::String> visited = visitor(referred_string);
1485 if (visited != referred_string) {
1486 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1487 /* kCheckTransaction= */ false,
1488 kVerifyNone,
1489 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001490 }
1491 }
1492}
1493
1494static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1495 REQUIRES_SHARED(Locks::mutator_lock_) {
1496 InternTable::UnorderedSet image_interns;
1497 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1498 if (section.Size() > 0) {
1499 size_t read_count;
1500 const uint8_t* data = space->Begin() + section.Offset();
1501 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1502 image_set.swap(image_interns);
1503 }
1504 size_t num_recorded_refs = 0u;
1505 VisitInternedStringReferences(
1506 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001507 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1508 REQUIRES_SHARED(Locks::mutator_lock_) {
1509 auto it = image_interns.find(GcRoot<mirror::String>(str));
1510 CHECK(it != image_interns.end());
1511 CHECK(it->Read() == str);
1512 ++num_recorded_refs;
1513 return str;
1514 });
1515 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1516 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001517}
1518
Andreas Gampe2af99022017-04-25 08:32:59 -07001519// new_class_set is the set of classes that were read from the class table section in the image.
1520// If there was no class table section, it is null.
1521// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001522class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001523 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001524 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001525 ClassLinker* class_linker,
1526 gc::space::ImageSpace* space,
1527 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001528 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001529 REQUIRES(!Locks::dex_lock_)
1530 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001531
Chris Wailesfbeef462018-10-19 14:16:35 -07001532 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001533 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001534};
1535
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001536void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001537 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001538 gc::space::ImageSpace* space,
1539 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001540 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001541 REQUIRES(!Locks::dex_lock_)
1542 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001543 ScopedTrace app_image_timing("AppImage:Updating");
1544
Vladimir Marko8e05f092019-06-10 11:10:38 +01001545 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1546 // In debug build, verify the string references before applying
1547 // the Runtime::LoadAppImageStartupCache() option.
1548 VerifyInternedStringReferences(space);
1549 }
1550
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001551 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001552 Runtime* const runtime = Runtime::Current();
1553 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001554 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001555 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001556 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001557 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001558 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001559 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001560 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001561 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001562 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001563 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001564 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001565 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001566 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001567
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001568 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001569 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001570 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001571
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001572 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001573 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001574 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001575 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1576 header.VisitPackedArtMethods([&](ArtMethod& method)
1577 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1578 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1579 if (klass != nullptr) {
1580 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1581 }
1582 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001583 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001584}
1585
Chris Wailesfbeef462018-10-19 14:16:35 -07001586void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001587 // Iterate over the string reference offsets stored in the image and intern
1588 // the strings they point to.
1589 ScopedTrace timing("AppImage:InternString");
1590
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001591 Runtime* const runtime = Runtime::Current();
1592 InternTable* const intern_table = runtime->GetInternTable();
1593
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001594 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1595 // for faster lookup.
1596 // TODO: Optimize with a bitmap or bloom filter
1597 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001598 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001599 REQUIRES_SHARED(Locks::mutator_lock_)
1600 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001601 const size_t non_boot_image_strings = intern_table->CountInterns(
1602 /*visit_boot_images=*/false,
1603 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001604 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001605 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1606 // Visit the smaller of the two sets to compute the intersection.
1607 if (interns.size() < non_boot_image_strings) {
1608 for (auto it = interns.begin(); it != interns.end(); ) {
1609 ObjPtr<mirror::String> string = it->Read();
1610 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1611 if (existing == nullptr) {
1612 existing = intern_table->LookupStrongLocked(string);
1613 }
1614 if (existing != nullptr) {
1615 intern_remap.Put(string.Ptr(), existing.Ptr());
1616 it = interns.erase(it);
1617 } else {
1618 ++it;
1619 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001620 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001621 } else {
1622 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1623 REQUIRES_SHARED(Locks::mutator_lock_)
1624 REQUIRES(Locks::intern_table_lock_) {
1625 auto it = interns.find(root);
1626 if (it != interns.end()) {
1627 ObjPtr<mirror::String> existing = root.Read();
1628 intern_remap.Put(it->Read(), existing.Ptr());
1629 it = interns.erase(it);
1630 }
1631 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1632 }
David Srbecky346fd962020-07-27 16:51:00 +01001633 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001634 if (kIsDebugBuild) {
1635 for (GcRoot<mirror::String>& root : interns) {
1636 ObjPtr<mirror::String> string = root.Read();
1637 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1638 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001639 }
1640 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001641 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001642 intern_table->AddImageStringsToTable(space, func);
1643 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001644 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001645 VisitInternedStringReferences(
1646 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001647 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1648 auto it = intern_remap.find(str.Ptr());
1649 if (it != intern_remap.end()) {
1650 return ObjPtr<mirror::String>(it->second);
1651 }
1652 return str;
1653 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001654 }
1655}
1656
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001657static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1658 const char* location,
1659 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001660 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001661 DCHECK(error_msg != nullptr);
1662 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001663 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001664 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001665 return std::unique_ptr<const DexFile>();
1666 }
1667 std::string inner_error_msg;
1668 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1669 if (dex_file == nullptr) {
1670 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1671 location,
1672 oat_file->GetLocation().c_str(),
1673 inner_error_msg.c_str());
1674 return std::unique_ptr<const DexFile>();
1675 }
1676
1677 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1678 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1679 location,
1680 dex_file->GetLocationChecksum(),
1681 oat_dex_file->GetDexFileLocationChecksum());
1682 return std::unique_ptr<const DexFile>();
1683 }
1684 return dex_file;
1685}
1686
1687bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1688 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1689 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001690 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001691 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001692 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001693 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001694 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001695 dex_caches_object->AsObjectArray<mirror::DexCache>();
1696 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001697 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001698 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1699 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1700 dex_file_location.c_str(),
1701 error_msg);
1702 if (dex_file == nullptr) {
1703 return false;
1704 }
1705 dex_cache->SetDexFile(dex_file.get());
1706 out_dex_files->push_back(std::move(dex_file));
1707 }
1708 return true;
1709}
1710
Andreas Gampe0793bec2016-12-01 11:37:33 -08001711// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1712// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001713class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001714 public:
1715 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1716 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001717 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001718 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1719 DCHECK(obj != nullptr);
1720 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1721 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1722 if (obj->IsClass()) {
1723 auto klass = obj->AsClass();
1724 for (ArtField& field : klass->GetIFields()) {
1725 CHECK_EQ(field.GetDeclaringClass(), klass);
1726 }
1727 for (ArtField& field : klass->GetSFields()) {
1728 CHECK_EQ(field.GetDeclaringClass(), klass);
1729 }
Orion Hodson5880c772020-07-28 20:12:08 +01001730 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001731 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001732 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001733 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001734 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001735 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001736 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001737 }
1738 if (klass->ShouldHaveImt()) {
1739 ImTable* imt = klass->GetImt(pointer_size);
1740 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001741 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001742 }
1743 }
1744 if (klass->ShouldHaveEmbeddedVTable()) {
1745 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001746 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001747 }
1748 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001749 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001750 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1751 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001752 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001753 }
1754 }
1755 }
1756 };
1757 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001758 }
1759
Andreas Gampe0793bec2016-12-01 11:37:33 -08001760 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001761 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001762 : spaces_(heap->GetBootImageSpaces()),
1763 pointer_size_(class_linker->GetImagePointerSize()) {
1764 space_begin_.reserve(spaces_.size());
1765 method_sections_.reserve(spaces_.size());
1766 runtime_method_sections_.reserve(spaces_.size());
1767 for (gc::space::ImageSpace* space : spaces_) {
1768 space_begin_.push_back(space->Begin());
1769 auto& header = space->GetImageHeader();
1770 method_sections_.push_back(&header.GetMethodsSection());
1771 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1772 }
1773 }
1774
Orion Hodson5880c772020-07-28 20:12:08 +01001775 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001776 REQUIRES_SHARED(Locks::mutator_lock_) {
1777 if (m->IsRuntimeMethod()) {
1778 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1779 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1780 } else if (m->IsCopied()) {
1781 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1782 } else if (expected_class != nullptr) {
1783 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1784 }
1785 if (!spaces_.empty()) {
1786 bool contains = false;
1787 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1788 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1789 contains = method_sections_[i]->Contains(offset) ||
1790 runtime_method_sections_[i]->Contains(offset);
1791 }
1792 CHECK(contains) << m << " not found";
1793 }
1794 }
1795
Orion Hodson5880c772020-07-28 20:12:08 +01001796 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1797 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001798 REQUIRES_SHARED(Locks::mutator_lock_) {
1799 CHECK(arr != nullptr);
1800 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1801 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1802 // expected_class == null means we are a dex cache.
1803 if (expected_class != nullptr) {
1804 CHECK(method != nullptr);
1805 }
1806 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001807 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001808 }
1809 }
1810 }
1811
Andreas Gampe0793bec2016-12-01 11:37:33 -08001812 const std::vector<gc::space::ImageSpace*>& spaces_;
1813 const PointerSize pointer_size_;
1814
1815 // Cached sections from the spaces.
1816 std::vector<const uint8_t*> space_begin_;
1817 std::vector<const ImageSection*> method_sections_;
1818 std::vector<const ImageSection*> runtime_method_sections_;
1819};
1820
Andreas Gampebe7af222017-07-25 09:57:28 -07001821static void VerifyAppImage(const ImageHeader& header,
1822 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001823 ClassTable* class_table,
1824 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001825 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001826 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1827 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1828 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1829 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1830 << mirror::Class::PrettyClass(klass);
1831 }
1832 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001833 {
1834 // Verify that all direct interfaces of classes in the class table are also resolved.
1835 std::vector<ObjPtr<mirror::Class>> classes;
1836 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1837 REQUIRES_SHARED(Locks::mutator_lock_) {
1838 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1839 classes.push_back(klass);
1840 }
1841 return true;
1842 };
1843 class_table->Visit(verify_direct_interfaces_in_table);
1844 Thread* self = Thread::Current();
1845 for (ObjPtr<mirror::Class> klass : classes) {
1846 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1847 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1848 << klass->PrettyDescriptor() << " iface #" << i;
1849 }
1850 }
1851 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001852}
1853
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001854bool ClassLinker::AddImageSpace(
1855 gc::space::ImageSpace* space,
1856 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001857 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1858 std::string* error_msg) {
1859 DCHECK(out_dex_files != nullptr);
1860 DCHECK(error_msg != nullptr);
1861 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001862 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001863 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001864 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001865 DCHECK(dex_caches_object != nullptr);
1866 Runtime* const runtime = Runtime::Current();
1867 gc::Heap* const heap = runtime->GetHeap();
1868 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001869 // Check that the image is what we are expecting.
1870 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1871 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1872 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1873 image_pointer_size_);
1874 return false;
1875 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001876 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1877 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1878 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1879 expected_image_roots,
1880 header.GetImageRoots()->GetLength());
1881 return false;
1882 }
1883 StackHandleScope<3> hs(self);
1884 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1885 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1886 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1887 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001888 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001889 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1890 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001891 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001892 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001893 *error_msg = StringPrintf("Expected %d class roots but got %d",
1894 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001895 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001896 return false;
1897 }
1898 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001899 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1900 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1901 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001902 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1903 return false;
1904 }
1905 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001906 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001907 if (oat_file->GetOatHeader().GetDexFileCount() !=
1908 static_cast<uint32_t>(dex_caches->GetLength())) {
1909 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1910 "image";
1911 return false;
1912 }
1913
Alex Lighta9bbc082019-11-14 14:51:41 -08001914 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001915 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001916 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1917 dex_file_location.c_str(),
1918 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001919 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001920 return false;
1921 }
1922
David Srbecky86d6cd52020-12-02 18:13:10 +00001923 LinearAlloc* linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader.Get());
1924 DCHECK(linear_alloc != nullptr);
1925 DCHECK_EQ(linear_alloc == Runtime::Current()->GetLinearAlloc(), !app_image);
1926 {
1927 // Native fields are all null. Initialize them and allocate native memory.
1928 WriterMutexLock mu(self, *Locks::dex_lock_);
1929 dex_cache->InitializeNativeFields(dex_file.get(), linear_alloc);
1930 }
1931 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001932 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001933 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001934 }
1935 out_dex_files->push_back(std::move(dex_file));
1936 }
1937
1938 if (app_image) {
1939 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001940 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001941 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1942 *error_msg = "Unexpected BootClassLoader in app image";
1943 return false;
1944 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001945 }
1946
Orion Hodson5880c772020-07-28 20:12:08 +01001947 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001948 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001949 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001950 }
1951 }
1952
1953 // Set entry point to interpreter if in InterpretOnly mode.
1954 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001955 // Set image methods' entry point to interpreter.
1956 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1957 if (!method.IsRuntimeMethod()) {
1958 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001959 if (!method.IsNative() && !method.IsResolutionMethod()) {
1960 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1961 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001962 }
1963 }
1964 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001965 }
1966
Nicolas Geoffray47171752020-08-31 15:03:20 +01001967 if (!runtime->IsAotCompiler()) {
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001968 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001969 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001970 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01001971 // In the image, the `data` pointer field of the ArtMethod contains the code
1972 // item offset. Change this to the actual pointer to the code item.
1973 if (method.HasCodeItem()) {
1974 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
1975 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01001976 method.SetCodeItem(code_item);
Nicolas Geoffray47171752020-08-31 15:03:20 +01001977 }
1978 // Set image methods' entry point that point to the interpreter bridge to the
1979 // nterp entry point.
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001980 if (method.GetEntryPointFromQuickCompiledCode() == nterp_trampoline_) {
1981 if (can_use_nterp) {
Nicolas Geoffrayb1cf8372021-02-02 13:32:20 +00001982 DCHECK(!NeedsClinitCheckBeforeCall(&method) ||
1983 method.GetDeclaringClass()->IsVisiblyInitialized());
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001984 method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
1985 } else {
1986 method.SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1987 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01001988 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001989 }, space->Begin(), image_pointer_size_);
1990 }
1991
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00001992 if (runtime->IsVerificationSoftFail()) {
1993 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1994 if (!method.IsNative() && method.IsInvokable()) {
1995 method.ClearSkipAccessChecks();
1996 }
1997 }, space->Begin(), image_pointer_size_);
1998 }
1999
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002000 ClassTable* class_table = nullptr;
2001 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002002 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002003 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002004 }
2005 // If we have a class table section, read it and use it for verification in
2006 // UpdateAppImageClassLoadersAndDexCaches.
2007 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002008 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002009 const bool added_class_table = class_table_section.Size() > 0u;
2010 if (added_class_table) {
2011 const uint64_t start_time2 = NanoTime();
2012 size_t read_count = 0;
2013 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2014 /*make copy*/false,
2015 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002016 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002017 }
2018 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002019 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002020
2021 {
2022 ScopedTrace trace("AppImage:UpdateClassLoaders");
2023 // Update class loader and resolved strings. If added_class_table is false, the resolved
2024 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002025 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002026 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002027 // Note: We probably don't need the read barrier unless we copy the app image objects into
2028 // the region space.
2029 ObjPtr<mirror::Class> klass(root.Read());
2030 // Do not update class loader for boot image classes where the app image
2031 // class loader is only the initiating loader but not the defining loader.
2032 // Avoid read barrier since we are comparing against null.
2033 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002034 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002035 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002036 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002037 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002038
Vladimir Marko305c38b2018-02-14 11:50:07 +00002039 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002040 // Every class in the app image has initially SubtypeCheckInfo in the
2041 // Uninitialized state.
2042 //
2043 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2044 // after class initialization is complete. The app image ClassStatus as-is
2045 // are almost all ClassStatus::Initialized, and being in the
2046 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2047 //
2048 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2049 //
2050 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002051 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002052 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2053 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002054 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002055 }
2056 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002057 }
2058 if (!oat_file->GetBssGcRoots().empty()) {
2059 // Insert oat file to class table for visiting .bss GC roots.
2060 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002061 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002062
Mathieu Chartier69731002016-03-02 16:08:31 -08002063 if (added_class_table) {
2064 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2065 class_table->AddClassSet(std::move(temp_set));
2066 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002067
Mathieu Chartier69731002016-03-02 16:08:31 -08002068 if (kIsDebugBuild && app_image) {
2069 // This verification needs to happen after the classes have been added to the class loader.
2070 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002071 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002072 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002073 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002074
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002075 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002076 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002077}
2078
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002079bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002080 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2081 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002082}
2083
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002084void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002085 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2086 // enabling tracing requires the mutator lock, there are no race conditions here.
2087 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002088 Thread* const self = Thread::Current();
2089 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002090 if (kUseReadBarrier) {
2091 // We do not track new roots for CC.
2092 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2093 kVisitRootFlagClearRootLog |
2094 kVisitRootFlagStartLoggingNewRoots |
2095 kVisitRootFlagStopLoggingNewRoots));
2096 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002097 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002098 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2099 // There is 3 GC cases to handle:
2100 // Non moving concurrent:
2101 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002102 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002103 //
2104 // Moving non-concurrent:
2105 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2106 // To prevent missing roots, this case needs to ensure that there is no
2107 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2108 // class which is in the class table.
2109 //
2110 // Moving concurrent:
2111 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2112 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002113 //
2114 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2115 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2116 // these objects.
2117 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002118 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002119 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002120 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002121 for (const ClassLoaderData& data : class_loaders_) {
2122 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2123 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2124 }
2125 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002126 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002127 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002128 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002129 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002130 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002131 // Concurrent moving GC marked new roots through the to-space invariant.
2132 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002133 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002134 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2135 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2136 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2137 if (old_ref != nullptr) {
2138 DCHECK(old_ref->IsClass());
2139 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2140 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2141 // Concurrent moving GC marked new roots through the to-space invariant.
2142 CHECK_EQ(new_ref, old_ref);
2143 }
2144 }
2145 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002146 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002147 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002148 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002149 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002150 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002151 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002152 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002153 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002154 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002155 }
2156 // We deliberately ignore the class roots in the image since we
2157 // handle image roots by using the MS/CMS rescanning of dirty cards.
2158}
2159
Brian Carlstroma663ea52011-08-19 23:33:41 -07002160// Keep in sync with InitCallback. Anything we visit, we need to
2161// reinit references to when reinitializing a ClassLinker from a
2162// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002163void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002164 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002165 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002166 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2167 // unloading if we are marking roots.
2168 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002169}
2170
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002171class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2172 public:
2173 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2174 : visitor_(visitor),
2175 done_(false) {}
2176
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002177 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002178 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002179 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002180 if (!done_ && class_table != nullptr) {
2181 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2182 if (!class_table->Visit(visitor)) {
2183 // If the visitor ClassTable returns false it means that we don't need to continue.
2184 done_ = true;
2185 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002186 }
2187 }
2188
2189 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002190 // Class visitor that limits the class visits from a ClassTable to the classes with
2191 // the provided defining class loader. This filter is used to avoid multiple visits
2192 // of the same class which can be recorded for multiple initiating class loaders.
2193 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2194 public:
2195 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2196 ClassVisitor* visitor)
2197 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2198
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002199 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002200 if (klass->GetClassLoader() != defining_class_loader_) {
2201 return true;
2202 }
2203 return (*visitor_)(klass);
2204 }
2205
Vladimir Marko0984e482019-03-27 16:41:41 +00002206 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002207 ClassVisitor* const visitor_;
2208 };
2209
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002210 ClassVisitor* const visitor_;
2211 // If done is true then we don't need to do any more visiting.
2212 bool done_;
2213};
2214
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002215void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002216 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002217 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2218 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002219 }
2220}
2221
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002222void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002223 Thread* const self = Thread::Current();
2224 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2225 // Not safe to have thread suspension when we are holding a lock.
2226 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002227 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002228 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002229 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002230 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002231 }
2232}
2233
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002234class GetClassesInToVector : public ClassVisitor {
2235 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002236 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002237 classes_.push_back(klass);
2238 return true;
2239 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002240 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002241};
2242
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002243class GetClassInToObjectArray : public ClassVisitor {
2244 public:
2245 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2246 : arr_(arr), index_(0) {}
2247
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002248 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002249 ++index_;
2250 if (index_ <= arr_->GetLength()) {
2251 arr_->Set(index_ - 1, klass);
2252 return true;
2253 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002254 return false;
2255 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002256
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002257 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002258 return index_ <= arr_->GetLength();
2259 }
2260
2261 private:
2262 mirror::ObjectArray<mirror::Class>* const arr_;
2263 int32_t index_;
2264};
2265
2266void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002267 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2268 // is avoiding duplicates.
2269 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002270 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002271 GetClassesInToVector accumulator;
2272 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002273 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002274 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002275 return;
2276 }
2277 }
2278 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002279 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002280 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002281 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002282 // We size the array assuming classes won't be added to the class table during the visit.
2283 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002284 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002285 size_t class_table_size;
2286 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002287 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002288 // Add 100 in case new classes get loaded when we are filling in the object array.
2289 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002290 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002291 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002292 classes.Assign(
2293 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002294 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002295 GetClassInToObjectArray accumulator(classes.Get());
2296 VisitClasses(&accumulator);
2297 if (accumulator.Succeeded()) {
2298 break;
2299 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002300 }
2301 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2302 // If the class table shrank during creation of the clases array we expect null elements. If
2303 // the class table grew then the loop repeats. If classes are created after the loop has
2304 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002305 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002306 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002307 return;
2308 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002309 }
2310 }
2311}
2312
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002313ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002314 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002315 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002316 // CHA unloading analysis is not needed. No negative consequences are expected because
2317 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002318 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002319 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002320 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002321 while (!running_visibly_initialized_callbacks_.empty()) {
2322 std::unique_ptr<VisiblyInitializedCallback> callback(
2323 std::addressof(running_visibly_initialized_callbacks_.front()));
2324 running_visibly_initialized_callbacks_.pop_front();
2325 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002326}
2327
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002328void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002329 Runtime* const runtime = Runtime::Current();
2330 JavaVMExt* const vm = runtime->GetJavaVM();
2331 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002332 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002333 if (runtime->GetJit() != nullptr) {
2334 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2335 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002336 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002337 code_cache->RemoveMethodsIn(self, *data.allocator);
2338 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002339 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002340 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002341 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002342 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002343 // Cleanup references to single implementation ArtMethods that will be deleted.
2344 if (cleanup_cha) {
2345 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2346 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2347 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002348 {
2349 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2350 auto end = critical_native_code_with_clinit_check_.end();
2351 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2352 if (data.allocator->ContainsUnsafe(it->first)) {
2353 it = critical_native_code_with_clinit_check_.erase(it);
2354 } else {
2355 ++it;
2356 }
2357 }
2358 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002359
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002360 delete data.allocator;
2361 delete data.class_table;
2362}
2363
Vladimir Markobcf17522018-06-01 13:14:32 +01002364ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2365 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002366 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002367 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2368 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002369}
2370
David Srbecky86d6cd52020-12-02 18:13:10 +00002371ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002372 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002373 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002374 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002375 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002376 self->AssertPendingOOMException();
2377 return nullptr;
2378 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002379 // Use InternWeak() so that the location String can be collected when the ClassLoader
2380 // with this DexCache is collected.
2381 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002382 if (location == nullptr) {
2383 self->AssertPendingOOMException();
2384 return nullptr;
2385 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002386 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002387 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002388}
2389
Vladimir Markobcf17522018-06-01 13:14:32 +01002390ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2391 const DexFile& dex_file,
2392 LinearAlloc* linear_alloc) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002393 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002394 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002395 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky86d6cd52020-12-02 18:13:10 +00002396 dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002397 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002398 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002399}
2400
Vladimir Marko70e2a762019-07-12 16:49:00 +01002401template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002402ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2403 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002404 uint32_t class_size,
2405 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002406 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002407 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002408 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002409 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2410 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002411 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002412 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002413 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002414 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002415 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002416}
2417
Vladimir Marko70e2a762019-07-12 16:49:00 +01002418template <bool kMovable>
2419ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2420 ObjPtr<mirror::Class> java_lang_Class,
2421 uint32_t class_size) {
2422 mirror::Class::InitializeClassVisitor visitor(class_size);
2423 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2424}
2425
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002426ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002427 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002428}
2429
Vladimir Marko70e2a762019-07-12 16:49:00 +01002430void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2431 ClassRoot primitive_root,
2432 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002433 // We make this class non-movable for the unlikely case where it were to be
2434 // moved by a sticky-bit (minor) collection when using the Generational
2435 // Concurrent Copying (CC) collector, potentially creating a stale reference
2436 // in the `klass_` field of one of its instances allocated in the Large-Object
2437 // Space (LOS) -- see the comment about the dirty card scanning logic in
2438 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002439 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2440 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2441 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2442 DCHECK(component_type->IsPrimitive());
2443 array_class->SetComponentType(component_type);
2444 SetClassRoot(array_root, array_class);
2445}
2446
2447void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2448 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2449 array_class->SetSuperClass(java_lang_Object);
2450 array_class->SetVTable(java_lang_Object->GetVTable());
2451 array_class->SetPrimitiveType(Primitive::kPrimNot);
2452 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2453 array_class->SetClassFlags(component_type->IsPrimitive()
2454 ? mirror::kClassFlagNoReferenceFields
2455 : mirror::kClassFlagObjectArray);
2456 array_class->SetClassLoader(component_type->GetClassLoader());
2457 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2458 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2459 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2460 array_class->SetImt(object_imt, image_pointer_size_);
2461 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2462 // the kAccVerificationAttempted flag is added below, and there are no
2463 // methods that need the kAccSkipAccessChecks flag.
2464 DCHECK_EQ(array_class->NumMethods(), 0u);
2465
2466 // don't need to set new_class->SetObjectSize(..)
2467 // because Object::SizeOf delegates to Array::SizeOf
2468
2469 // All arrays have java/lang/Cloneable and java/io/Serializable as
2470 // interfaces. We need to set that up here, so that stuff like
2471 // "instanceof" works right.
2472
2473 // Use the single, global copies of "interfaces" and "iftable"
2474 // (remember not to free them for arrays).
2475 {
2476 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2477 CHECK(array_iftable != nullptr);
2478 array_class->SetIfTable(array_iftable);
2479 }
2480
2481 // Inherit access flags from the component type.
2482 int access_flags = component_type->GetAccessFlags();
2483 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2484 access_flags &= kAccJavaFlagsMask;
2485 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2486 // and remove "interface".
2487 access_flags |= kAccAbstract | kAccFinal;
2488 access_flags &= ~kAccInterface;
2489 // Arrays are access-checks-clean and preverified.
2490 access_flags |= kAccVerificationAttempted;
2491
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002492 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002493
Vladimir Markobf121912019-06-04 13:49:05 +01002494 // Array classes are fully initialized either during single threaded startup,
2495 // or from a pre-fence visitor, so visibly initialized.
2496 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002497}
2498
2499void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2500 // Do not hold lock on the array class object, the initialization of
2501 // core array classes is done while the process is still single threaded.
2502 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2503 FinishArrayClassSetup(array_class);
2504
2505 std::string temp;
2506 const char* descriptor = array_class->GetDescriptor(&temp);
2507 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2508 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2509 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002510}
2511
Vladimir Markobcf17522018-06-01 13:14:32 +01002512ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002513 Thread* self,
2514 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002515 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002516 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002517}
2518
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002519ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2520 const char* descriptor,
2521 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002522 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002523 if (kIsDebugBuild) {
2524 StackHandleScope<1> hs(self);
2525 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2526 Thread::PoisonObjectPointersIfDebug();
2527 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002528
2529 // For temporary classes we must wait for them to be retired.
2530 if (init_done_ && klass->IsTemp()) {
2531 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002532 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002533 ThrowEarlierClassFailure(klass);
2534 return nullptr;
2535 }
2536 StackHandleScope<1> hs(self);
2537 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2538 ObjectLock<mirror::Class> lock(self, h_class);
2539 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002540 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002541 lock.WaitIgnoringInterrupts();
2542 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002543 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002544 ThrowEarlierClassFailure(h_class.Get());
2545 return nullptr;
2546 }
2547 CHECK(h_class->IsRetired());
2548 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002549 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002550 }
2551
Brian Carlstromaded5f72011-10-07 17:15:04 -07002552 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002553 size_t index = 0;
2554 // Maximum number of yield iterations until we start sleeping.
2555 static const size_t kNumYieldIterations = 1000;
2556 // How long each sleep is in us.
2557 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002558 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002559 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002560 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002561 {
2562 ObjectTryLock<mirror::Class> lock(self, h_class);
2563 // Can not use a monitor wait here since it may block when returning and deadlock if another
2564 // thread has locked klass.
2565 if (lock.Acquired()) {
2566 // Check for circular dependencies between classes, the lock is required for SetStatus.
2567 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2568 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002569 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002570 return nullptr;
2571 }
2572 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002573 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002574 {
2575 // Handle wrapper deals with klass moving.
2576 ScopedThreadSuspension sts(self, kSuspended);
2577 if (index < kNumYieldIterations) {
2578 sched_yield();
2579 } else {
2580 usleep(kSleepDurationUS);
2581 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002582 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002583 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002585
Vladimir Marko72ab6842017-01-20 19:32:50 +00002586 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002587 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002588 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002589 }
2590 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002591 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002592 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002593 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002594}
2595
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002596using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002597
2598// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002599ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002600 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002601 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002602 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002603 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002604 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002605 return ClassPathEntry(dex_file, dex_class_def);
2606 }
2607 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002608 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002609}
2610
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002611bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2612 Thread* self,
2613 const char* descriptor,
2614 size_t hash,
2615 Handle<mirror::ClassLoader> class_loader,
2616 /*out*/ ObjPtr<mirror::Class>* result) {
2617 ArtField* field =
2618 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2619 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2620 if (raw_shared_libraries == nullptr) {
2621 return true;
2622 }
2623
2624 StackHandleScope<2> hs(self);
2625 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2626 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2627 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002628 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2629 temp_loader.Assign(loader);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002630 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2631 return false; // One of the shared libraries is not supported.
2632 }
2633 if (*result != nullptr) {
2634 return true; // Found the class up the chain.
2635 }
2636 }
2637 return true;
2638}
2639
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002640bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2641 Thread* self,
2642 const char* descriptor,
2643 size_t hash,
2644 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002645 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002646 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002647 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002648 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002649 return true;
2650 }
2651
David Brazdil05909d82018-12-06 16:25:16 +00002652 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002653 // For regular path or dex class loader the search order is:
2654 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002655 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002656 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002657
Calin Juravlecdd49122017-07-05 20:09:53 -07002658 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2659 StackHandleScope<1> hs(self);
2660 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2661 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2662 return false; // One of the parents is not supported.
2663 }
2664 if (*result != nullptr) {
2665 return true; // Found the class up the chain.
2666 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002667
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002668 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2669 return false; // One of the shared library loader is not supported.
2670 }
2671 if (*result != nullptr) {
2672 return true; // Found the class in a shared library.
2673 }
2674
Calin Juravlecdd49122017-07-05 20:09:53 -07002675 // Search the current class loader classpath.
2676 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002677 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002678 }
2679
Calin Juravlecdd49122017-07-05 20:09:53 -07002680 if (IsDelegateLastClassLoader(soa, class_loader)) {
2681 // For delegate last, the search order is:
2682 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002683 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002684 // - class loader dex files
2685 // - parent
2686 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2687 if (*result != nullptr) {
2688 return true; // The class is part of the boot class path.
2689 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002690 if (self->IsExceptionPending()) {
2691 // Pending exception means there was an error other than ClassNotFound that must be returned
2692 // to the caller.
2693 return false;
2694 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002695
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002696 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2697 return false; // One of the shared library loader is not supported.
2698 }
2699 if (*result != nullptr) {
2700 return true; // Found the class in a shared library.
2701 }
2702
Calin Juravlecdd49122017-07-05 20:09:53 -07002703 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2704 if (*result != nullptr) {
2705 return true; // Found the class in the current class loader
2706 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002707 if (self->IsExceptionPending()) {
2708 // Pending exception means there was an error other than ClassNotFound that must be returned
2709 // to the caller.
2710 return false;
2711 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002712
2713 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2714 StackHandleScope<1> hs(self);
2715 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2716 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2717 }
2718
2719 // Unsupported class loader.
2720 *result = nullptr;
2721 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002722}
2723
Andreas Gampe501c3b02019-04-17 21:54:27 +00002724namespace {
2725
2726// Matches exceptions caught in DexFile.defineClass.
2727ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2728 ClassLinker* class_linker)
2729 REQUIRES_SHARED(Locks::mutator_lock_) {
2730 return
2731 // ClassNotFoundException.
2732 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2733 class_linker))
2734 ||
2735 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2736 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2737}
2738
2739// Clear exceptions caught in DexFile.defineClass.
2740ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2741 REQUIRES_SHARED(Locks::mutator_lock_) {
2742 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2743 self->ClearException();
2744 }
2745}
2746
2747} // namespace
2748
Calin Juravle415dc3d2017-06-28 11:03:12 -07002749// Finds the class in the boot class loader.
2750// If the class is found the method returns the resolved class. Otherwise it returns null.
2751ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2752 const char* descriptor,
2753 size_t hash) {
2754 ObjPtr<mirror::Class> result = nullptr;
2755 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2756 if (pair.second != nullptr) {
2757 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2758 if (klass != nullptr) {
2759 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002760 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002761 result = DefineClass(self,
2762 descriptor,
2763 hash,
2764 ScopedNullHandle<mirror::ClassLoader>(),
2765 *pair.first,
2766 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002767 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002768 if (result == nullptr) {
2769 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002770 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002771 }
2772 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002773 return result;
2774}
Andreas Gampef865ea92015-04-13 22:14:19 -07002775
Calin Juravle415dc3d2017-06-28 11:03:12 -07002776ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2777 ScopedObjectAccessAlreadyRunnable& soa,
2778 const char* descriptor,
2779 size_t hash,
2780 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002781 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2782 IsInMemoryDexClassLoader(soa, class_loader) ||
2783 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002784 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002785
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002786 ObjPtr<mirror::Class> ret;
2787 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002788 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002789 if (dex_class_def != nullptr) {
2790 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2791 descriptor,
2792 hash,
2793 class_loader,
2794 *cp_dex_file,
2795 *dex_class_def);
2796 if (klass == nullptr) {
2797 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002798 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002799 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00002800 } else {
2801 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002802 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002803 ret = klass;
2804 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002805 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002806 return true; // Continue with the next DexFile.
2807 };
2808
2809 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2810 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002811}
2812
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002813ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2814 const char* descriptor,
2815 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002816 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002817 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002818 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002819 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002820 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002821 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2822 // for primitive classes that aren't backed by dex files.
2823 return FindPrimitiveClass(descriptor[0]);
2824 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002825 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002826 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002827 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002828 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002829 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002830 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002831 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002832 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002833 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002834 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002835 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002836 return DefineClass(self,
2837 descriptor,
2838 hash,
2839 ScopedNullHandle<mirror::ClassLoader>(),
2840 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002841 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002842 } else {
2843 // The boot class loader is searched ahead of the application class loader, failures are
2844 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2845 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002846 ObjPtr<mirror::Throwable> pre_allocated =
2847 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002848 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002849 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002850 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002851 }
2852 ObjPtr<mirror::Class> result_ptr;
2853 bool descriptor_equals;
2854 if (descriptor[0] == '[') {
2855 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2856 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2857 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2858 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002859 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002860 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002861 bool known_hierarchy =
2862 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2863 if (result_ptr != nullptr) {
2864 // The chain was understood and we found the class. We still need to add the class to
2865 // the class table to protect from racy programs that can try and redefine the path list
2866 // which would change the Class<?> returned for subsequent evaluation of const-class.
2867 DCHECK(known_hierarchy);
2868 DCHECK(result_ptr->DescriptorEquals(descriptor));
2869 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002870 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002871 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002872 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2873 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002874 //
2875 // If the chain was understood but we did not find the class, let the Java-side
2876 // rediscover all this and throw the exception with the right stack trace. Note that
2877 // the Java-side could still succeed for racy programs if another thread is actively
2878 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002879
Alex Light185a4612018-10-04 15:54:25 -07002880 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002881 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002882 // Oops, we can't call into java so we can't run actual class-loader code.
2883 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002884 ObjPtr<mirror::Throwable> pre_allocated =
2885 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2886 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002887 return nullptr;
2888 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002889
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002890 // Inlined DescriptorToDot(descriptor) with extra validation.
2891 //
2892 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2893 // the DescriptorEquals() check below and give a confusing error message. For example,
2894 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2895 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2896 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2897 size_t descriptor_length = strlen(descriptor);
2898 if (UNLIKELY(descriptor[0] != 'L') ||
2899 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2900 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2901 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2902 return nullptr;
2903 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002904
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002905 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2906 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002907 if (known_hierarchy &&
2908 fast_class_not_found_exceptions_ &&
2909 !Runtime::Current()->IsJavaDebuggable()) {
2910 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2911 // debuggable, optimize this path by throwing directly here without going back to Java
2912 // language. This reduces how many ClassNotFoundExceptions happen.
2913 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2914 "%s",
2915 class_name_string.c_str());
2916 } else {
2917 ScopedLocalRef<jobject> class_loader_object(
2918 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2919 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2920 {
2921 ScopedThreadStateChange tsc(self, kNative);
2922 ScopedLocalRef<jobject> class_name_object(
2923 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2924 if (class_name_object.get() == nullptr) {
2925 DCHECK(self->IsExceptionPending()); // OOME.
2926 return nullptr;
2927 }
2928 CHECK(class_loader_object.get() != nullptr);
2929 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2930 WellKnownClasses::java_lang_ClassLoader_loadClass,
2931 class_name_object.get()));
2932 }
2933 if (result.get() == nullptr && !self->IsExceptionPending()) {
2934 // broken loader - throw NPE to be compatible with Dalvik
2935 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2936 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002937 return nullptr;
2938 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002939 result_ptr = soa.Decode<mirror::Class>(result.get());
2940 // Check the name of the returned class.
2941 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002942 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002943 } else {
2944 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002945 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002946 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002947
2948 if (self->IsExceptionPending()) {
2949 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2950 // However, to comply with the RI behavior, first check if another thread succeeded.
2951 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2952 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2953 self->ClearException();
2954 return EnsureResolved(self, descriptor, result_ptr);
2955 }
2956 return nullptr;
2957 }
2958
2959 // Try to insert the class to the class table, checking for mismatch.
2960 ObjPtr<mirror::Class> old;
2961 {
2962 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2963 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2964 old = class_table->Lookup(descriptor, hash);
2965 if (old == nullptr) {
2966 old = result_ptr; // For the comparison below, after releasing the lock.
2967 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002968 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002969 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002970 } // else throw below, after releasing the lock.
2971 }
2972 }
2973 if (UNLIKELY(old != result_ptr)) {
2974 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2975 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01002976 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002977 const char* loader_class_name =
2978 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2979 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2980 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2981 << DescriptorToDot(descriptor) << "\").";
2982 return EnsureResolved(self, descriptor, old);
2983 }
2984 if (UNLIKELY(!descriptor_equals)) {
2985 std::string result_storage;
2986 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2987 std::string loader_storage;
2988 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2989 ThrowNoClassDefFoundError(
2990 "Initiating class loader of type %s returned class %s instead of %s.",
2991 DescriptorToDot(loader_class_name).c_str(),
2992 DescriptorToDot(result_name).c_str(),
2993 DescriptorToDot(descriptor).c_str());
2994 return nullptr;
2995 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002996 // Success.
2997 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002998}
2999
Alex Light270db1c2019-12-03 12:20:01 +00003000// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3001// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3002// like pausing class definition.
3003struct ScopedDefiningClass {
3004 public:
3005 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3006 : self_(self), returned_(false) {
3007 Locks::mutator_lock_->AssertSharedHeld(self_);
3008 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3009 self_->IncrDefineClassCount();
3010 }
3011 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3012 Locks::mutator_lock_->AssertSharedHeld(self_);
3013 CHECK(returned_);
3014 }
3015
3016 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3017 REQUIRES_SHARED(Locks::mutator_lock_) {
3018 CHECK(!returned_);
3019 self_->DecrDefineClassCount();
3020 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3021 Thread::PoisonObjectPointersIfDebug();
3022 returned_ = true;
3023 return h_klass.Get();
3024 }
3025
3026 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3027 REQUIRES_SHARED(Locks::mutator_lock_) {
3028 StackHandleScope<1> hs(self_);
3029 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3030 return Finish(h_klass);
3031 }
3032
3033 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3034 REQUIRES_SHARED(Locks::mutator_lock_) {
3035 ScopedNullHandle<mirror::Class> snh;
3036 return Finish(snh);
3037 }
3038
3039 private:
3040 Thread* self_;
3041 bool returned_;
3042};
3043
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003044ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3045 const char* descriptor,
3046 size_t hash,
3047 Handle<mirror::ClassLoader> class_loader,
3048 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003049 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003050 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003051 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003052 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003053
Brian Carlstromaded5f72011-10-07 17:15:04 -07003054 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003055 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003056 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003057 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003058 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003059 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003060 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003061 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003062 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003063 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003064 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003065 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003066 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003067 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003068 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003069 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003070 }
3071
Vladimir Markob9c29f62019-03-20 14:22:51 +00003072 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3073 // some runtime modules. Prevent definition of classes in app class loader that could clash
3074 // with these modules as these classes could be resolved differently during execution.
3075 if (class_loader != nullptr &&
3076 Runtime::Current()->IsAotCompiler() &&
Vladimir Markod1f73512020-04-02 10:50:35 +01003077 IsUpdatableBootClassPathDescriptor(descriptor)) {
Vladimir Markob9c29f62019-03-20 14:22:51 +00003078 ObjPtr<mirror::Throwable> pre_allocated =
3079 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3080 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003081 return sdc.Finish(nullptr);
Vladimir Markob9c29f62019-03-20 14:22:51 +00003082 }
3083
Calin Juravle33787682019-07-26 14:27:18 -07003084 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3085 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3086 // public class path then we prevent the definition of the class.
3087 //
3088 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3089 // classpath is not checked.
3090 if (class_loader == nullptr &&
3091 Runtime::Current()->IsAotCompiler() &&
3092 DenyAccessBasedOnPublicSdk(descriptor)) {
3093 ObjPtr<mirror::Throwable> pre_allocated =
3094 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3095 self->SetException(pre_allocated);
3096 return sdc.Finish(nullptr);
3097 }
3098
Alex Lighte9f61032018-09-24 16:04:51 -07003099 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3100 // code to be executed. We put it up here so we can avoid all the allocations associated with
3101 // creating the class. This can happen with (eg) jit threads.
3102 if (!self->CanLoadClasses()) {
3103 // Make sure we don't try to load anything, potentially causing an infinite loop.
3104 ObjPtr<mirror::Throwable> pre_allocated =
3105 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3106 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003107 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003108 }
3109
Andreas Gampefa4333d2017-02-14 11:10:34 -08003110 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003111 // Allocate a class with the status of not ready.
3112 // Interface object should get the right size here. Regular class will
3113 // figure out the right size later and be replaced with one of the right
3114 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003115 if (CanAllocClass()) {
3116 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3117 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003118 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003119 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003120 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003121 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003122 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003123 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003124 }
Alex Lightb0f11922017-01-23 14:25:17 -08003125 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3126 // nothing.
3127 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003128 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003129 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3130 // will only be called once.
3131 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3132 klass,
3133 class_loader,
3134 dex_file,
3135 dex_class_def,
3136 &new_dex_file,
3137 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003138 // Check to see if an exception happened during runtime callbacks. Return if so.
3139 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003140 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003141 }
Alex Lightb0f11922017-01-23 14:25:17 -08003142 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003143 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003144 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003145 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003146 }
3147 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003148 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003149
Jeff Hao848f70a2014-01-15 13:49:50 -08003150 // Mark the string class by setting its access flag.
3151 if (UNLIKELY(!init_done_)) {
3152 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3153 klass->SetStringClass();
3154 }
3155 }
3156
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003157 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003158 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003159 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003160 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003161
Mathieu Chartier590fee92013-09-13 13:46:47 -07003162 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003163 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003164 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003165 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3166 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003167 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003168 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003169
Mathieu Chartierc7853442015-03-27 14:35:38 -07003170 // Load the fields and other things after we are inserted in the table. This is so that we don't
3171 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3172 // other reason is that the field roots are only visited from the class table. So we need to be
3173 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003174 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003175 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003176 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003177 // An exception occured during load, set status to erroneous while holding klass' lock in case
3178 // notification is necessary.
3179 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003180 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003181 }
Alex Light270db1c2019-12-03 12:20:01 +00003182 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003183 }
3184
Brian Carlstromaded5f72011-10-07 17:15:04 -07003185 // Finish loading (if necessary) by finding parents
3186 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003187 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003188 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003189 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003190 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003191 }
Alex Light270db1c2019-12-03 12:20:01 +00003192 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003193 }
3194 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003195
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003196 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003197 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003198 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003199
Brian Carlstromaded5f72011-10-07 17:15:04 -07003200 // Link the class (if necessary)
3201 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003202 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003203 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003204
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003205 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003206 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003207 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003208 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003209 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003210 }
Alex Light270db1c2019-12-03 12:20:01 +00003211 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003212 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003213 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003214 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003215 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003216
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003217 // Instrumentation may have updated entrypoints for all methods of all
3218 // classes. However it could not update methods of this class while we
3219 // were loading it. Now the class is resolved, we can update entrypoints
3220 // as required by instrumentation.
3221 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3222 // We must be in the kRunnable state to prevent instrumentation from
3223 // suspending all threads to update entrypoints while we are doing it
3224 // for this class.
3225 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003226 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003227 }
3228
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003229 /*
3230 * We send CLASS_PREPARE events to the debugger from here. The
3231 * definition of "preparation" is creating the static fields for a
3232 * class and initializing them to the standard default values, but not
3233 * executing any code (that comes later, during "initialization").
3234 *
3235 * We did the static preparation in LinkClass.
3236 *
3237 * The class has been prepared and resolved but possibly not yet verified
3238 * at this point.
3239 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003240 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003241
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003242 // Notify native debugger of the new class and its layout.
3243 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3244
Alex Light270db1c2019-12-03 12:20:01 +00003245 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003246}
3247
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003248uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003249 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003250 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003251 size_t num_8 = 0;
3252 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003253 size_t num_32 = 0;
3254 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003255 ClassAccessor accessor(dex_file, dex_class_def);
3256 // We allow duplicate definitions of the same field in a class_data_item
3257 // but ignore the repeated indexes here, b/21868015.
3258 uint32_t last_field_idx = dex::kDexNoIndex;
3259 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3260 uint32_t field_idx = field.GetIndex();
3261 // Ordering enforced by DexFileVerifier.
3262 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3263 if (UNLIKELY(field_idx == last_field_idx)) {
3264 continue;
3265 }
3266 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003267 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003268 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3269 char c = descriptor[0];
3270 switch (c) {
3271 case 'L':
3272 case '[':
3273 num_ref++;
3274 break;
3275 case 'J':
3276 case 'D':
3277 num_64++;
3278 break;
3279 case 'I':
3280 case 'F':
3281 num_32++;
3282 break;
3283 case 'S':
3284 case 'C':
3285 num_16++;
3286 break;
3287 case 'B':
3288 case 'Z':
3289 num_8++;
3290 break;
3291 default:
3292 LOG(FATAL) << "Unknown descriptor: " << c;
3293 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003294 }
3295 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003296 return mirror::Class::ComputeClassSize(false,
3297 0,
3298 num_8,
3299 num_16,
3300 num_32,
3301 num_64,
3302 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003303 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003304}
3305
Alex Lightfc49fec2018-01-16 22:28:36 +00003306// Special case to get oat code without overwriting a trampoline.
3307const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003308 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003309 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003310 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003311 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003312 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003313 if (code != nullptr) {
3314 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003315 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003316
3317 jit::Jit* jit = Runtime::Current()->GetJit();
3318 if (jit != nullptr) {
3319 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3320 if (code != nullptr) {
3321 return code;
3322 }
3323 }
3324
Alex Lightfc49fec2018-01-16 22:28:36 +00003325 if (method->IsNative()) {
3326 // No code and native? Use generic trampoline.
3327 return GetQuickGenericJniStub();
3328 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003329
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003330 if (interpreter::CanRuntimeUseNterp() && CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003331 return interpreter::GetNterpEntryPoint();
3332 }
3333
Alex Lightfc49fec2018-01-16 22:28:36 +00003334 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003335}
3336
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003337bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003338 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003339 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3340 return false;
3341 }
3342
Elliott Hughes956af0f2014-12-11 14:34:28 -08003343 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003344 return true;
3345 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003346
3347 Runtime* runtime = Runtime::Current();
3348 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3349 if (instr->InterpretOnly()) {
3350 return true;
3351 }
3352
3353 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3354 // Doing this check avoids doing compiled/interpreter transitions.
3355 return true;
3356 }
3357
Alex Lightfc588092020-01-23 15:39:08 -08003358 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003359 // Force the use of interpreter when it is required by the debugger.
3360 return true;
3361 }
3362
Alex Light8f34aba2017-10-09 13:46:32 -07003363 if (Thread::Current()->IsAsyncExceptionPending()) {
3364 // Force use of interpreter to handle async-exceptions
3365 return true;
3366 }
3367
Alex Light2d441b12018-06-08 15:33:21 -07003368 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3369 const void* instr_target = instr->GetCodeForInvoke(method);
3370 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3371 return ShouldUseInterpreterEntrypoint(method, instr_target);
3372 }
3373
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003374 if (runtime->IsJavaDebuggable()) {
3375 // For simplicity, we ignore precompiled code and go to the interpreter
3376 // assuming we don't already have jitted code.
3377 // We could look at the oat file where `quick_code` is being defined,
3378 // and check whether it's been compiled debuggable, but we decided to
3379 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003380 jit::Jit* jit = Runtime::Current()->GetJit();
3381 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3382 }
3383
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003384 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003385 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003386 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003387 // since we want to JIT it (at first use) with extra stackmaps for native
3388 // debugging. We keep however all AOT code from the boot image,
3389 // since the JIT-at-first-use is blocking and would result in non-negligible
3390 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003391 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003392 }
3393
3394 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003395}
3396
Vladimir Marko86c87522020-05-11 16:55:55 +01003397void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003398 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003399 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003400 size_t num_direct_methods = klass->NumDirectMethods();
3401 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003402 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003403 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003404 if (UNLIKELY(klass->IsProxyClass())) {
3405 return;
3406 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003407 PointerSize pointer_size = image_pointer_size_;
3408 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3409 klass->GetDirectMethods(pointer_size).end(),
3410 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3411 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3412 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3413 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3414 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3415 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3416 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3417 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3418 lb->first->SetEntryPointFromJni(lb->second);
3419 lb = critical_native_code_with_clinit_check_.erase(lb);
3420 }
3421 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003422 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003423 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003424 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003425 return; // OAT file unavailable.
3426 }
Ian Rogers19846512012-02-24 11:42:47 -08003427 }
Alex Light64ad14d2014-08-19 14:23:13 -07003428
Mathieu Chartierf8322842014-05-16 10:59:25 -07003429 const DexFile& dex_file = klass->GetDexFile();
Ian Rogers97b52f82014-08-14 11:34:07 -07003430 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003431 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3432 klass->GetDexClassDefIndex(),
3433 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003434 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003435 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3436 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003437 if (!method->IsStatic()) {
3438 // Only update static methods.
3439 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003440 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003441 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003442
3443 // In order:
3444 // 1) Check if we have AOT Code.
3445 // 2) Check if we have JIT Code.
3446 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003447 if (has_oat_class) {
3448 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003449 quick_code = oat_method.GetQuickCode();
3450 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003451
Vladimir Markocce414f2019-10-07 08:51:33 +01003452 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003453 if (quick_code == nullptr && jit != nullptr) {
3454 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003455 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003456
3457 if (quick_code == nullptr &&
3458 interpreter::CanRuntimeUseNterp() &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003459 CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003460 quick_code = interpreter::GetNterpEntryPoint();
3461 }
3462
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003463 // Check whether the method is native, in which case it's generic JNI.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003464 if (quick_code == nullptr && method->IsNative()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003465 quick_code = GetQuickGenericJniStub();
3466 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003467 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003468 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3469 // If we have the trampoline or the bridge already, no need to update.
3470 // This saves in not dirtying boot image memory.
3471 continue;
3472 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003473 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003474 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003475 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003476 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003477 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003478 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003479}
3480
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003481// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3482// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003483inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3484 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003485 DCHECK(method != nullptr);
3486 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003487 method->SetEntryPointFromQuickCompiledCodePtrSize(
3488 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3489 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003490}
3491
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003492static void LinkCode(ClassLinker* class_linker,
3493 ArtMethod* method,
3494 const OatFile::OatClass* oat_class,
3495 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003496 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003497 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003498 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003499 // The following code only applies to a non-compiler runtime.
3500 return;
3501 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003502
Ian Rogers62d6c772013-02-27 08:32:07 -08003503 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003504 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003505
Alex Light9139e002015-10-09 15:59:48 -07003506 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003507 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003508 return;
3509 }
Ian Rogers19846512012-02-24 11:42:47 -08003510
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003511 const void* quick_code = nullptr;
3512 if (oat_class != nullptr) {
3513 // Every kind of method should at least get an invoke stub from the oat_method.
3514 // non-abstract methods also get their code pointers.
3515 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3516 quick_code = oat_method.GetQuickCode();
3517 }
3518
3519 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3520
3521 // Note: this mimics the logic in image_writer.cc that installs the resolution
3522 // stub only if we have compiled code and the method needs a class initialization
3523 // check.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003524 if (quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003525 method->SetEntryPointFromQuickCompiledCode(
3526 method->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge());
3527 } else if (enter_interpreter) {
3528 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003529 } else if (NeedsClinitCheckBeforeCall(method)) {
3530 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3531 // If we do have code but the method needs a class initialization check before calling
3532 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003533 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3534 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003535 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003536 } else {
3537 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003538 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003539
Ian Rogers62d6c772013-02-27 08:32:07 -08003540 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003541 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3542 // as the extra processing for @CriticalNative is not needed yet.
3543 method->SetEntryPointFromJni(
3544 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Andreas Gampe90546832014-03-12 18:07:19 -07003545
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003546 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003547 // We have a native method here without code. Then it should have the generic JNI
3548 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003549 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003550 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003551 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003552 }
3553}
3554
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003555void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003556 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003557 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003558 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003559 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003560 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003561 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003562 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003563 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003564
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003565 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003566 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003567 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003568 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003569 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003570 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003571 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003572
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003573 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003574 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003575}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003576
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003577LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3578 LinearAlloc* allocator,
3579 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003580 if (length == 0) {
3581 return nullptr;
3582 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003583 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3584 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3585 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003586 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003587 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003588 CHECK(ret != nullptr);
3589 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3590 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003591}
3592
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003593LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3594 LinearAlloc* allocator,
3595 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003596 if (length == 0) {
3597 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003598 }
Vladimir Marko14632852015-08-17 12:07:23 +01003599 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3600 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003601 const size_t storage_size =
3602 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003603 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003604 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003605 CHECK(ret != nullptr);
3606 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003607 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003608 }
3609 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003610}
3611
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003612LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003613 if (class_loader == nullptr) {
3614 return Runtime::Current()->GetLinearAlloc();
3615 }
3616 LinearAlloc* allocator = class_loader->GetAllocator();
3617 DCHECK(allocator != nullptr);
3618 return allocator;
3619}
3620
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003621LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003622 if (class_loader == nullptr) {
3623 return Runtime::Current()->GetLinearAlloc();
3624 }
3625 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3626 LinearAlloc* allocator = class_loader->GetAllocator();
3627 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003628 RegisterClassLoader(class_loader);
3629 allocator = class_loader->GetAllocator();
3630 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003631 }
3632 return allocator;
3633}
3634
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003635void ClassLinker::LoadClass(Thread* self,
3636 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003637 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003638 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003639 ClassAccessor accessor(dex_file,
3640 dex_class_def,
3641 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003642 if (!accessor.HasClassData()) {
3643 return;
3644 }
3645 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003646 {
3647 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3648 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003649 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003650 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003651 // We allow duplicate definitions of the same field in a class_data_item
3652 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003653 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003654 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3655 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003656 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003657 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3658 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003659 accessor.NumInstanceFields());
3660 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003661 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003662 uint32_t last_static_field_idx = 0u;
3663 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003664
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003665 // Methods
3666 bool has_oat_class = false;
3667 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3668 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3669 : OatFile::OatClass::Invalid();
3670 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3671 klass->SetMethodsPtr(
3672 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3673 accessor.NumDirectMethods(),
3674 accessor.NumVirtualMethods());
3675 size_t class_def_method_index = 0;
3676 uint32_t last_dex_method_index = dex::kDexNoIndex;
3677 size_t last_class_def_method_index = 0;
3678
3679 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3680 // methods needs to decode all of the fields.
3681 accessor.VisitFieldsAndMethods([&](
3682 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3683 uint32_t field_idx = field.GetIndex();
3684 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3685 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3686 LoadField(field, klass, &sfields->At(num_sfields));
3687 ++num_sfields;
3688 last_static_field_idx = field_idx;
3689 }
3690 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3691 uint32_t field_idx = field.GetIndex();
3692 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3693 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3694 LoadField(field, klass, &ifields->At(num_ifields));
3695 ++num_ifields;
3696 last_instance_field_idx = field_idx;
3697 }
3698 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3699 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3700 image_pointer_size_);
3701 LoadMethod(dex_file, method, klass, art_method);
3702 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3703 uint32_t it_method_index = method.GetIndex();
3704 if (last_dex_method_index == it_method_index) {
3705 // duplicate case
3706 art_method->SetMethodIndex(last_class_def_method_index);
3707 } else {
3708 art_method->SetMethodIndex(class_def_method_index);
3709 last_dex_method_index = it_method_index;
3710 last_class_def_method_index = class_def_method_index;
3711 }
3712 ++class_def_method_index;
3713 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3714 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3715 class_def_method_index - accessor.NumDirectMethods(),
3716 image_pointer_size_);
3717 LoadMethod(dex_file, method, klass, art_method);
3718 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3719 ++class_def_method_index;
3720 });
3721
3722 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003723 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003724 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3725 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3726 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003727 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3728 if (sfields != nullptr) {
3729 sfields->SetSize(num_sfields);
3730 }
3731 if (ifields != nullptr) {
3732 ifields->SetSize(num_ifields);
3733 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003734 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003735 // Set the field arrays.
3736 klass->SetSFieldsPtr(sfields);
3737 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003738 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003739 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003740 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003741 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003742 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003743 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003744}
3745
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003746void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003747 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003748 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003749 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003750 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003751 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003752
David Brazdil85865692018-10-30 17:26:20 +00003753 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3754 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003755}
3756
Mathieu Chartier268764d2016-09-13 12:09:38 -07003757void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003758 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003759 Handle<mirror::Class> klass,
3760 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003761 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003762 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003763 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003764
Mathieu Chartier268764d2016-09-13 12:09:38 -07003765 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003766 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003767 dst->SetDeclaringClass(klass.Get());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003768
David Brazdil85865692018-10-30 17:26:20 +00003769 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3770 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003771
Ian Rogersdfb325e2013-10-30 01:00:44 -07003772 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003773 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003774 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3775 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003776 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003777 klass->SetFinalizable();
3778 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003779 std::string temp;
3780 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003781 // The Enum class declares a "final" finalize() method to prevent subclasses from
3782 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3783 // subclasses, so we exclude it here.
3784 // We also want to avoid setting the flag on Object, where we know that finalize() is
3785 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003786 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3787 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003788 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003789 }
3790 }
3791 }
3792 } else if (method_name[0] == '<') {
3793 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003794 bool is_init = (strcmp("<init>", method_name) == 0);
3795 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003796 if (UNLIKELY(!is_init && !is_clinit)) {
3797 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3798 } else {
3799 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3800 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003801 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003802 access_flags |= kAccConstructor;
3803 }
3804 }
3805 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003806 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3807 // Check if the native method is annotated with @FastNative or @CriticalNative.
3808 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3809 dex_file, dst->GetClassDef(), dex_method_idx);
3810 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003811 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003812 // Must be done after SetAccessFlags since IsAbstract depends on it.
3813 if (klass->IsInterface() && dst->IsAbstract()) {
3814 dst->CalculateAndSetImtIndex();
3815 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01003816 if (dst->HasCodeItem()) {
3817 DCHECK_NE(method.GetCodeItemOffset(), 0u);
3818 if (Runtime::Current()->IsAotCompiler()) {
3819 dst->SetDataPtrSize(reinterpret_cast32<void*>(method.GetCodeItemOffset()), image_pointer_size_);
3820 } else {
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01003821 dst->SetCodeItem(dst->GetDexFile()->GetCodeItem(method.GetCodeItemOffset()));
Nicolas Geoffray47171752020-08-31 15:03:20 +01003822 }
3823 } else {
3824 dst->SetDataPtrSize(nullptr, image_pointer_size_);
3825 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3826 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003827}
3828
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003829void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003830 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003831 self,
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003832 *dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003833 Runtime::Current()->GetLinearAlloc());
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003834 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003835 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003836}
3837
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003838void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003839 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003840 CHECK(dex_file != nullptr);
3841 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3842 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003843 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003844 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003845}
3846
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003847void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003848 ObjPtr<mirror::DexCache> dex_cache,
3849 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003850 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003851 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003852 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003853 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003854 // For app images, the dex cache location may be a suffix of the dex file location since the
3855 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003856 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3857 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003858 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3859 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003860 // The following paths checks don't work on preopt when using boot dex files, where the dex
3861 // cache location is the one on device, and the dex_file's location is the one on host.
3862 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3863 CHECK_GE(dex_file_location.length(), dex_cache_length)
3864 << dex_cache_location << " " << dex_file.GetLocation();
3865 const std::string dex_file_suffix = dex_file_location.substr(
3866 dex_file_location.length() - dex_cache_length,
3867 dex_cache_length);
3868 // Example dex_cache location is SettingsProvider.apk and
3869 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3870 CHECK_EQ(dex_cache_location, dex_file_suffix);
3871 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003872 const OatFile* oat_file =
3873 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003874 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3875 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3876 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3877 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003878 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003879 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3880 DexCacheData data = *it;
3881 if (self->IsJWeakCleared(data.weak_root)) {
3882 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003883 it = dex_caches_.erase(it);
3884 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003885 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003886 it->dex_file->GetOatDexFile() != nullptr &&
3887 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003888 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003889 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003890 ++it;
3891 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003892 }
Vladimir Markob066d432018-01-03 13:14:37 +00003893 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003894 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003895 }
David Brazdila5c3a802019-03-08 14:59:41 +00003896 // Let hiddenapi assign a domain to the newly registered dex file.
3897 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3898
Vladimir Markocd556b02017-02-03 11:47:34 +00003899 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003900 DexCacheData data;
3901 data.weak_root = dex_cache_jweak;
3902 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003903 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003904 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003905 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003906 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3907 // path dex caches without an image.
3908 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003909 // Make sure that the dex cache holds the classloader live.
3910 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003911 if (class_loader != nullptr) {
3912 // Since we added a strong root to the class table, do the write barrier as required for
3913 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003914 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003915 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003916 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003917}
3918
Alex Light725da8f2020-02-19 14:46:33 -08003919ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3920 return data != nullptr
3921 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003922 : nullptr;
3923}
3924
Alex Light725da8f2020-02-19 14:46:33 -08003925bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003926 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003927 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003928 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003929 CHECK(data != nullptr);
3930 DCHECK_EQ(dex_cache->GetDexFile(), data->dex_file);
3931 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003932}
3933
Alex Light07f06212017-06-01 14:01:43 -07003934void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3935 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003936 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003937 Thread* self = Thread::Current();
3938 StackHandleScope<2> hs(self);
3939 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3940 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3941 const DexFile* dex_file = dex_cache->GetDexFile();
3942 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3943 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003944 ReaderMutexLock mu(self, *Locks::dex_lock_);
3945 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3946 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003947 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3948 << "been registered on dex file " << dex_file->GetLocation();
3949 }
3950 ClassTable* table;
3951 {
3952 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3953 table = InsertClassTableForClassLoader(h_class_loader.Get());
3954 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003955 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3956 // a thread holding the dex lock and blocking on a condition variable regarding
3957 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003958 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003959 WriterMutexLock mu(self, *Locks::dex_lock_);
3960 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3961 table->InsertStrongRoot(h_dex_cache.Get());
3962 if (h_class_loader.Get() != nullptr) {
3963 // Since we added a strong root to the class table, do the write barrier as required for
3964 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003965 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003966 }
3967}
3968
Alex Lightde7f8782020-02-24 10:14:22 -08003969static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
3970 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08003971 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08003972 "Attempt to register dex file %s with multiple class loaders",
3973 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08003974}
3975
Vladimir Markocd556b02017-02-03 11:47:34 +00003976ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3977 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003978 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08003979 ObjPtr<mirror::DexCache> old_dex_cache;
3980 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003981 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003982 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003983 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
3984 old_dex_cache = DecodeDexCacheLocked(self, old_data);
3985 if (old_dex_cache != nullptr) {
3986 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
3987 return old_dex_cache;
3988 } else {
3989 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
3990 // be thrown when it's safe to do so to simplify this.
3991 registered_with_another_class_loader = true;
3992 }
3993 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003994 }
Alex Light725da8f2020-02-19 14:46:33 -08003995 // We need to have released the dex_lock_ to allocate safely.
3996 if (registered_with_another_class_loader) {
3997 ThrowDexFileAlreadyRegisteredError(self, dex_file);
3998 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003999 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004000 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004001 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4002 DCHECK(linear_alloc != nullptr);
4003 ClassTable* table;
4004 {
4005 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4006 table = InsertClassTableForClassLoader(class_loader);
4007 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004008 // Don't alloc while holding the lock, since allocation may need to
4009 // suspend all threads and another thread may need the dex_lock_ to
4010 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004011 StackHandleScope<3> hs(self);
4012 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00004013 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004014 {
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);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004019 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004020 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4021 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004022 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
David Srbecky86d6cd52020-12-02 18:13:10 +00004023 // Do InitializeNativeFields while holding dex lock to make sure two threads don't call it
4024 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
4025 // DCHECK that the arrays are null.
4026 h_dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Vladimir Markocd556b02017-02-03 11:47:34 +00004027 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004028 }
Alex Light725da8f2020-02-19 14:46:33 -08004029 if (old_dex_cache != nullptr) {
4030 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4031 // If this thread encountered OOME, ignore it.
4032 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
4033 self->ClearException();
4034 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
4035 // dex_lock_.
4036 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
4037 return old_dex_cache;
4038 } else {
4039 registered_with_another_class_loader = true;
4040 }
4041 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004042 }
Alex Light725da8f2020-02-19 14:46:33 -08004043 if (registered_with_another_class_loader) {
4044 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4045 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004046 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004047 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004048 self->AssertPendingOOMException();
4049 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004050 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004051 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004052 if (h_class_loader.Get() != nullptr) {
4053 // Since we added a strong root to the class table, do the write barrier as required for
4054 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004055 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004056 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004057 PaletteHooks* hooks = nullptr;
4058 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
4059 if (PaletteGetHooks(&hooks) == PaletteStatus::kOkay) {
4060 hooks->NotifyDexFileLoaded(dex_file.GetLocation().c_str());
4061 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004062 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004063}
4064
Vladimir Markocd556b02017-02-03 11:47:34 +00004065bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004066 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004067 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004068}
4069
Vladimir Markocd556b02017-02-03 11:47:34 +00004070ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4071 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004072 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4073 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004074 if (dex_cache != nullptr) {
4075 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004076 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004077 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004078 for (const DexCacheData& data : dex_caches_) {
Alex Light725da8f2020-02-19 14:46:33 -08004079 if (DecodeDexCacheLocked(self, &data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004080 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004081 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004082 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004083 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
Alex Light725da8f2020-02-19 14:46:33 -08004084 << " " << &dex_file << " " << dex_cache_data->dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004085 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004086}
4087
Vladimir Markocd556b02017-02-03 11:47:34 +00004088ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4089 const DexFile* dex_file = dex_cache->GetDexFile();
4090 DCHECK(dex_file != nullptr);
4091 ReaderMutexLock mu(self, *Locks::dex_lock_);
4092 // Search assuming unique-ness of dex file.
4093 for (const DexCacheData& data : dex_caches_) {
4094 // Avoid decoding (and read barriers) other unrelated dex caches.
4095 if (data.dex_file == dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004096 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004097 if (registered_dex_cache != nullptr) {
4098 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4099 return data.class_table;
4100 }
4101 }
4102 }
4103 return nullptr;
4104}
4105
Alex Light725da8f2020-02-19 14:46:33 -08004106const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004107 // Search assuming unique-ness of dex file.
4108 for (const DexCacheData& data : dex_caches_) {
4109 // Avoid decoding (and read barriers) other unrelated dex caches.
4110 if (data.dex_file == &dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004111 return &data;
Vladimir Markocd556b02017-02-03 11:47:34 +00004112 }
4113 }
Alex Light725da8f2020-02-19 14:46:33 -08004114 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004115}
4116
Vladimir Marko70e2a762019-07-12 16:49:00 +01004117void ClassLinker::CreatePrimitiveClass(Thread* self,
4118 Primitive::Type type,
4119 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004120 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004121 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004122 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4123 // Do not hold lock on the primitive class object, the initialization of
4124 // primitive classes is done while the process is still single threaded.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004125 primitive_class->SetAccessFlagsDuringLinking(
Vladimir Marko70e2a762019-07-12 16:49:00 +01004126 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4127 primitive_class->SetPrimitiveType(type);
4128 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4129 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4130 // the kAccVerificationAttempted flag was added above, and there are no
4131 // methods that need the kAccSkipAccessChecks flag.
4132 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004133 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4134 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004135 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004136 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004137 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004138 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004139 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004140 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004141}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004142
Vladimir Marko02610552018-06-04 14:38:00 +01004143inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4144 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4145}
4146
Brian Carlstrombe977852011-07-19 14:54:54 -07004147// Create an array class (i.e. the class object for the array, not the
4148// array itself). "descriptor" looks like "[C" or "[[[[B" or
4149// "[Ljava/lang/String;".
4150//
4151// If "descriptor" refers to an array of primitives, look up the
4152// primitive type's internally-generated class object.
4153//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004154// "class_loader" is the class loader of the class that's referring to
4155// us. It's used to ensure that we're looking for the element type in
4156// the right context. It does NOT become the class loader for the
4157// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004158//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004159// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004160ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4161 const char* descriptor,
4162 size_t hash,
4163 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004164 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004165 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004166 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004167
4168 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4169 // code to be executed. We put it up here so we can avoid all the allocations associated with
4170 // creating the class. This can happen with (eg) jit threads.
4171 if (!self->CanLoadClasses()) {
4172 // Make sure we don't try to load anything, potentially causing an infinite loop.
4173 ObjPtr<mirror::Throwable> pre_allocated =
4174 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4175 self->SetException(pre_allocated);
4176 return nullptr;
4177 }
4178
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004179 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4180 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004181 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004182 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004183 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004184 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4185 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004186 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004187 DCHECK(self->IsExceptionPending());
4188 return nullptr;
4189 } else {
4190 self->ClearException();
4191 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004192 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004193 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4194 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4195 return nullptr;
4196 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004197 // See if the component type is already loaded. Array classes are
4198 // always associated with the class loader of their underlying
4199 // element type -- an array of Strings goes with the loader for
4200 // java/lang/String -- so we need to look for it there. (The
4201 // caller should have checked for the existence of the class
4202 // before calling here, but they did so with *their* class loader,
4203 // not the component type's loader.)
4204 //
4205 // If we find it, the caller adds "loader" to the class' initiating
4206 // loader list, which should prevent us from going through this again.
4207 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004208 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004209 // are the same, because our caller (FindClass) just did the
4210 // lookup. (Even if we get this wrong we still have correct behavior,
4211 // because we effectively do this lookup again when we add the new
4212 // class to the hash table --- necessary because of possible races with
4213 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004214 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004215 ObjPtr<mirror::Class> new_class =
4216 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004217 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004218 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004219 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004220 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004221 // Core array classes, i.e. Object[], Class[], String[] and primitive
4222 // arrays, have special initialization and they should be found above.
4223 DCHECK(!component_type->IsObjectClass() ||
4224 // Guard from false positives for errors before setting superclass.
4225 component_type->IsErroneousUnresolved());
4226 DCHECK(!component_type->IsStringClass());
4227 DCHECK(!component_type->IsClassClass());
4228 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004229
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004230 // Fill out the fields in the Class.
4231 //
4232 // It is possible to execute some methods against arrays, because
4233 // all arrays are subclasses of java_lang_Object_, so we need to set
4234 // up a vtable. We can just point at the one in java_lang_Object_.
4235 //
4236 // Array classes are simple enough that we don't need to do a full
4237 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004238 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4239 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4240 size_t usable_size)
4241 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004242 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004243 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4244 init_class(obj, usable_size);
4245 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4246 klass->SetComponentType(component_type.Get());
4247 // Do not hold lock for initialization, the fence issued after the visitor
4248 // returns ensures memory visibility together with the implicit consume
4249 // semantics (for all supported architectures) for any thread that loads
4250 // the array class reference from any memory locations afterwards.
4251 FinishArrayClassSetup(klass);
4252 };
4253 auto new_class = hs.NewHandle<mirror::Class>(
4254 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004255 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004256 self->AssertPendingOOMException();
4257 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004258 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004259
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004260 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004261 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004262 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4263 // duplicate events in case of races. Array classes don't really follow dedicated
4264 // load and prepare, anyways.
4265 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4266 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4267
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004268 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004269 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004270 }
4271 // Another thread must have loaded the class after we
4272 // started but before we finished. Abandon what we've
4273 // done.
4274 //
4275 // (Yes, this happens.)
4276
Vladimir Markobcf17522018-06-01 13:14:32 +01004277 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004278}
4279
Vladimir Marko9186b182018-11-06 14:55:54 +00004280ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4281 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004282 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004283 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4284 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4285 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4286 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4287 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4288 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4289 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4290 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4291 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004292 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004293 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004294 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004295 return GetClassRoot(class_root, this);
4296}
4297
4298ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4299 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4300 if (UNLIKELY(result == nullptr)) {
4301 std::string printable_type(PrintableChar(type));
4302 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4303 }
4304 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004305}
4306
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004307ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4308 ObjPtr<mirror::Class> klass,
4309 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004310 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004311 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004312 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004313 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004314 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004315 source += " from ";
4316 source += dex_cache->GetLocation()->ToModifiedUtf8();
4317 }
4318 LOG(INFO) << "Loaded class " << descriptor << source;
4319 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004320 {
4321 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004322 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004323 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004324 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004325 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004326 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004327 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004328 VerifyObject(klass);
4329 class_table->InsertWithHash(klass, hash);
4330 if (class_loader != nullptr) {
4331 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004332 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004333 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004334 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004335 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004336 }
4337 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004338 if (kIsDebugBuild) {
4339 // Test that copied methods correctly can find their holder.
4340 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4341 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4342 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004343 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004344 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004345}
4346
Vladimir Marko1998cd02017-01-13 13:02:58 +00004347void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004348 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4349 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4350 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4351 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004352 }
4353}
4354
Alex Lighte64300b2015-12-15 15:02:47 -08004355// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004356void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004357 LengthPrefixedArray<ArtMethod>* new_methods) {
4358 klass->SetMethodsPtrUnchecked(new_methods,
4359 klass->NumDirectMethods(),
4360 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004361 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004362 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004363}
4364
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004365ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4366 const char* descriptor,
4367 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004368 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4369}
4370
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004371ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4372 const char* descriptor,
4373 size_t hash,
4374 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004375 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4376 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4377 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004378 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004379 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004380 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004381 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004382 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004383 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004384}
4385
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004386class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4387 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004388 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004389
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004390 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004391 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004392 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004393 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004394 if (class_table != nullptr) {
4395 class_table->FreezeSnapshot();
4396 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004397 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004398};
4399
4400void ClassLinker::MoveClassTableToPreZygote() {
4401 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004402 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004403 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004404 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004405}
4406
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004407// Look up classes by hash and descriptor and put all matching ones in the result array.
4408class LookupClassesVisitor : public ClassLoaderVisitor {
4409 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004410 LookupClassesVisitor(const char* descriptor,
4411 size_t hash,
4412 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004413 : descriptor_(descriptor),
4414 hash_(hash),
4415 result_(result) {}
4416
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004417 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004418 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004419 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004420 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004421 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4422 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004423 result_->push_back(klass);
4424 }
4425 }
4426
4427 private:
4428 const char* const descriptor_;
4429 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004430 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004431};
4432
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004433void ClassLinker::LookupClasses(const char* descriptor,
4434 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004435 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004436 Thread* const self = Thread::Current();
4437 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004438 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004439 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004440 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004441 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004442 result.push_back(klass);
4443 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004444 LookupClassesVisitor visitor(descriptor, hash, &result);
4445 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004446}
4447
Alex Lightf1f10492015-10-07 16:08:36 -07004448bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4449 Handle<mirror::Class> klass,
4450 Handle<mirror::Class> supertype) {
4451 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004452 DCHECK(klass != nullptr);
4453 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004454
Alex Lightf1f10492015-10-07 16:08:36 -07004455 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4456 VerifyClass(self, supertype);
4457 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004458
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004459 if (supertype->IsVerified()
4460 || supertype->ShouldVerifyAtRuntime()
4461 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004462 // The supertype is either verified, or we soft failed at AOT time.
4463 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004464 return true;
4465 }
4466 // If we got this far then we have a hard failure.
4467 std::string error_msg =
4468 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004469 klass->PrettyDescriptor().c_str(),
4470 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004471 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004472 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004473 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004474 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004475 // Set during VerifyClass call (if at all).
4476 self->ClearException();
4477 }
4478 // Change into a verify error.
4479 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004480 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004481 self->GetException()->SetCause(cause.Get());
4482 }
4483 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4484 if (Runtime::Current()->IsAotCompiler()) {
4485 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4486 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004487 // Need to grab the lock to change status.
4488 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004489 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004490 return false;
4491}
4492
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004493verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004494 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004495 {
4496 // TODO: assert that the monitor on the Class is held
4497 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004498
Andreas Gampe884f3b82016-03-30 19:52:58 -07004499 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004500 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004501 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004502 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004503 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4504 // case we may see the same status again. b/62912904. This is why the check is
4505 // greater or equal.
4506 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004507 << "Class '" << klass->PrettyClass()
4508 << "' performed an illegal verification state transition from " << old_status
4509 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004510 old_status = klass->GetStatus();
4511 }
jeffhao98eacac2011-09-14 16:11:53 -07004512
Andreas Gampe884f3b82016-03-30 19:52:58 -07004513 // The class might already be erroneous, for example at compile time if we attempted to verify
4514 // this class as a parent to another.
4515 if (klass->IsErroneous()) {
4516 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004517 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004518 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004519
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004520 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004521 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004522 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004523 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004524 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004525
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004526 if (klass->IsVerifiedNeedsAccessChecks()) {
4527 if (!Runtime::Current()->IsAotCompiler()) {
4528 // Mark the class as having a verification attempt to avoid re-running
4529 // the verifier and avoid calling EnsureSkipAccessChecksMethods.
4530 klass->SetVerificationAttempted();
4531 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4532 }
4533 return verifier::FailureKind::kAccessChecksFailure;
4534 }
4535
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004536 // For AOT, don't attempt to re-verify if we have already found we should
4537 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004538 if (klass->ShouldVerifyAtRuntime()) {
4539 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004540 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004541 }
jeffhao98eacac2011-09-14 16:11:53 -07004542
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004543 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4544 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004545
4546 // Skip verification if disabled.
4547 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004548 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004549 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004550 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004551 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004552 }
4553
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004554 VLOG(class_linker) << "Beginning verification for class: "
4555 << klass->PrettyDescriptor()
4556 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4557
Ian Rogers9ffb0392012-09-10 11:56:50 -07004558 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004559 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004560 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4561 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004562 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004563 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004564 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004565 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004566
Alex Lightf1f10492015-10-07 16:08:36 -07004567 // Verify all default super-interfaces.
4568 //
4569 // (1) Don't bother if the superclass has already had a soft verification failure.
4570 //
4571 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4572 // recursive initialization by themselves. This is because when an interface is initialized
4573 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4574 // but choose not to for an optimization. If the interfaces is being verified due to a class
4575 // initialization (which would need all the default interfaces to be verified) the class code
4576 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004577 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004578 && !klass->IsInterface()) { // See (2)
4579 int32_t iftable_count = klass->GetIfTableCount();
4580 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4581 // Loop through all interfaces this class has defined. It doesn't matter the order.
4582 for (int32_t i = 0; i < iftable_count; i++) {
4583 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004584 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004585 // We only care if we have default interfaces and can skip if we are already verified...
4586 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4587 continue;
4588 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4589 // We had a hard failure while verifying this interface. Just return immediately.
4590 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004591 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004592 } else if (UNLIKELY(!iface->IsVerified())) {
4593 // We softly failed to verify the iface. Stop checking and clean up.
4594 // Put the iface into the supertype handle so we know what caused us to fail.
4595 supertype.Assign(iface.Get());
4596 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004597 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004598 }
4599 }
4600
Alex Lightf1f10492015-10-07 16:08:36 -07004601 // At this point if verification failed, then supertype is the "first" supertype that failed
4602 // verification (without a specific order). If verification succeeded, then supertype is either
4603 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004604 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004605 supertype.Get() == klass->GetSuperClass() ||
4606 !supertype->IsVerified());
4607
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004608 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004609 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004610 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004611 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004612
4613 VLOG(class_linker) << "Class preverified status for class "
4614 << klass->PrettyDescriptor()
4615 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4616 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004617 << preverified
4618 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004619
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004620 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4621 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004622 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4623 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004624
Ian Rogers62d6c772013-02-27 08:32:07 -08004625 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004626 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004627 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004628 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004629 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004630
4631 // Verification is done, grab the lock again.
4632 ObjectLock<mirror::Class> lock(self, klass);
4633
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004634 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4635 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004636 VLOG(class_linker) << "Soft verification failure in class "
4637 << klass->PrettyDescriptor()
4638 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4639 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004640 }
Ian Rogers1f539342012-10-03 21:09:42 -07004641 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004642 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004643 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004644 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004645 // Even though there were no verifier failures we need to respect whether the super-class and
4646 // super-default-interfaces were verified or requiring runtime reverification.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004647 if (supertype == nullptr
4648 || supertype->IsVerified()
4649 || supertype->IsVerifiedNeedsAccessChecks()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004650 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004651 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004652 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004653 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4654 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004655 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004656 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004657 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004658 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004659 CHECK(verifier_failure == verifier::FailureKind::kSoftFailure ||
Nicolas Geoffrayd1728bf2021-01-12 14:02:29 +00004660 verifier_failure == verifier::FailureKind::kTypeChecksFailure ||
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004661 verifier_failure == verifier::FailureKind::kAccessChecksFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004662 // Soft failures at compile time should be retried at runtime. Soft
4663 // failures at runtime will be handled by slow paths in the generated
4664 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004665 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffrayd1728bf2021-01-12 14:02:29 +00004666 if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4667 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004668 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4669 } else {
4670 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4671 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004672 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004673 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004674 // As this is a fake verified status, make sure the methods are _not_ marked
4675 // kAccSkipAccessChecks later.
4676 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004677 }
4678 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004679 } else {
David Sehr709b0702016-10-13 09:12:37 -07004680 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004681 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4682 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004683 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004684 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004685 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004686 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004687 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004688 if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks ||
4689 UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
Igor Murashkindf707e42016-02-02 16:56:50 -08004690 // Never skip access checks if the verification soft fail is forced.
4691 // Mark the class as having a verification attempt to avoid re-running the verifier.
4692 klass->SetVerificationAttempted();
4693 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004694 // Class is verified so we don't need to do any access check on its methods.
4695 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
4696 // method.
4697 // Note: we're going here during compilation and at runtime. When we set the
4698 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
4699 // in the image and is set when loading the image.
Andreas Gampecc1b5352016-12-01 16:58:38 -08004700 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004701 }
Andreas Gampe48498592014-09-10 19:48:05 -07004702 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004703 // Done verifying. Notify the compiler about the verification status, in case the class
4704 // was verified implicitly (eg super class of a compiled class).
4705 if (Runtime::Current()->IsAotCompiler()) {
4706 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4707 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4708 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004709 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004710}
4711
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004712verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4713 Handle<mirror::Class> klass,
4714 verifier::HardFailLogMode log_level,
4715 std::string* error_msg) {
4716 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004717 return verifier::ClassVerifier::VerifyClass(self,
4718 klass.Get(),
4719 runtime->GetCompilerCallbacks(),
4720 runtime->IsAotCompiler(),
4721 log_level,
4722 Runtime::Current()->GetTargetSdkVersion(),
4723 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004724}
4725
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004726bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004727 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004728 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004729 // If we're compiling, we can only verify the class using the oat file if
4730 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004731 // the compilation unit (app - dependencies). We will let the compiler callback
4732 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004733 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004734 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004735 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004736 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004737 return false;
4738 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004739 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004740
Andreas Gampeb40d3612018-06-26 15:49:42 -07004741 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004742 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004743 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004744 return false;
4745 }
4746
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004747 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004748 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004749 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004750 return true;
4751 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004752 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4753 // We return that the clas has already been verified, and the caller should
4754 // check the class status to ensure we run with access checks.
4755 return true;
4756 }
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004757 // If we only verified a subset of the classes at compile time, we can end up with classes that
4758 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004759 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004760 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004761 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004762 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4763 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4764 << klass->PrettyClass() << " " << dex_file.GetLocation();
4765
Vladimir Marko72ab6842017-01-20 19:32:50 +00004766 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004767 // Compile time verification failed with a hard error. This is caused by invalid instructions
4768 // in the class. These errors are unrecoverable.
4769 return false;
4770 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004771 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004772 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4773 // not loading the class.
4774 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4775 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004776 return false;
4777 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004778 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004779 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004780 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004781 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004782 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004783}
4784
Alex Light5a559862016-01-29 12:24:48 -08004785void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004786 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004787 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004788 }
4789}
4790
Alex Light5a559862016-01-29 12:24:48 -08004791void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004792 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004793 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004794 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004795 return; // native or abstract method
4796 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004797 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004798 return; // nothing to process
4799 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004800 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004801 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004802 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4803 CatchHandlerIterator iterator(handlers_ptr);
4804 for (; iterator.HasNext(); iterator.Next()) {
4805 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4806 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004807 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004808 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004809 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004810 DCHECK(Thread::Current()->IsExceptionPending());
4811 Thread::Current()->ClearException();
4812 }
4813 }
4814 }
4815 handlers_ptr = iterator.EndDataPointer();
4816 }
4817}
4818
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004819ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4820 jstring name,
4821 jobjectArray interfaces,
4822 jobject loader,
4823 jobjectArray methods,
4824 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004825 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004826
4827 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4828 // code to be executed. We put it up here so we can avoid all the allocations associated with
4829 // creating the class. This can happen with (eg) jit-threads.
4830 if (!self->CanLoadClasses()) {
4831 // Make sure we don't try to load anything, potentially causing an infinite loop.
4832 ObjPtr<mirror::Throwable> pre_allocated =
4833 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4834 self->SetException(pre_allocated);
4835 return nullptr;
4836 }
4837
Alex Light133987d2020-03-26 19:22:12 +00004838 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004839 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004840 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004841 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004842 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004843 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004844 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004845 DCHECK(temp_klass->GetClass() != nullptr);
4846 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004847 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4848 // the methods.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004849 temp_klass->SetAccessFlagsDuringLinking(
4850 kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004851 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4852 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4853 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004854 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004855 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004856 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004857 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004858 std::string storage;
4859 const char* descriptor = temp_klass->GetDescriptor(&storage);
4860 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004861
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004862 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004863 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004864
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004865 // Insert the class before loading the fields as the field roots
4866 // (ArtField::declaring_class_) are only visited from the class
4867 // table. There can't be any suspend points between inserting the
4868 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004869 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004870 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004871
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004872 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004873 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004874 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004875 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004876
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004877 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4878 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004879 ArtField& interfaces_sfield = sfields->At(0);
4880 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004881 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004882 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004883
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004884 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004885 ArtField& throws_sfield = sfields->At(1);
4886 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004887 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004888 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004889
Ian Rogers466bb252011-10-14 03:29:56 -07004890 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004891 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004892
Alex Light133987d2020-03-26 19:22:12 +00004893 // The array we get passed contains all methods, including private and static
4894 // ones that aren't proxied. We need to filter those out since only interface
4895 // methods (non-private & virtual) are actually proxied.
4896 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4897 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004898 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004899 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004900 // List of the actual virtual methods this class will have.
4901 std::vector<ArtMethod*> proxied_methods;
4902 std::vector<size_t> proxied_throws_idx;
4903 proxied_methods.reserve(h_methods->GetLength());
4904 proxied_throws_idx.reserve(h_methods->GetLength());
4905 // Filter out to only the non-private virtual methods.
4906 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4907 ArtMethod* m = mirror->GetArtMethod();
4908 if (!m->IsPrivate() && !m->IsStatic()) {
4909 proxied_methods.push_back(m);
4910 proxied_throws_idx.push_back(idx);
4911 }
4912 }
4913 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004914 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4915 // contains an array of all the classes each function is declared to throw.
4916 // This is used to wrap unexpected exceptions in a
4917 // UndeclaredThrowableException exception. This array is in the same order as
4918 // the methods array and like the methods array must be filtered to remove any
4919 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004920 const bool has_filtered_methods =
4921 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4922 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4923 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4924 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4925 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4926 (has_filtered_methods)
4927 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4928 self, original_proxied_throws->GetClass(), num_virtual_methods)
4929 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004930 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4931 self->AssertPendingOOMException();
4932 return nullptr;
4933 }
Alex Light133987d2020-03-26 19:22:12 +00004934 if (has_filtered_methods) {
4935 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
4936 DCHECK_LE(new_idx, orig_idx);
4937 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
4938 }
4939 }
Alex Lighte64300b2015-12-15 15:02:47 -08004940
4941 // Create the methods array.
4942 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4943 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004944 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4945 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004946 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004947 self->AssertPendingOOMException();
4948 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004949 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004950 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004951
4952 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004953 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004954
4955 // Create virtual method using specified prototypes.
4956 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004957 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004958 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004959 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004960 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004961 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4962 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004963 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004964
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004965 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004966 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004967 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004968 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004969 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004970
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004971 // At this point the class is loaded. Publish a ClassLoad event.
4972 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4973 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4974
4975 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004976 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004977 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004978 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004979 // Link the fields and virtual methods, creating vtable and iftables.
4980 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004981 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004982 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004983 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004984 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004985 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004986 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004987 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004988 CHECK(temp_klass->IsRetired());
4989 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004990
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004991 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004992 interfaces_sfield.SetObject<false>(
4993 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004994 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004995 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4996 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004997 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00004998 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004999
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005000 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5001
Vladimir Marko305c38b2018-02-14 11:50:07 +00005002 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5003 // See also ClassLinker::EnsureInitialized().
5004 if (kBitstringSubtypeCheckEnabled) {
5005 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5006 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5007 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5008 }
5009
Vladimir Markobf121912019-06-04 13:49:05 +01005010 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005011 {
5012 // Lock on klass is released. Lock new class object.
5013 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005014 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005015 // Conservatively go through the ClassStatus::kInitialized state.
5016 callback = MarkClassInitialized(self, klass);
5017 }
5018 if (callback != nullptr) {
5019 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005020 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005021
David Srbecky346fd962020-07-27 16:51:00 +01005022 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07005023 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005024 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005025 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5026
Ian Rogersc2b44472011-12-14 21:17:17 -08005027 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005028 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005029 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08005030 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005031
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005032 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005033 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005034 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005035 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005036 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005037
5038 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005039 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005040 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005041
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005042 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005043 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005044 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005045 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005046 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005047 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005048}
5049
Mathieu Chartiere401d142015-04-22 13:56:20 -07005050void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5051 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005052 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5053 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005054
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005055 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5056 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005057 ArtMethod* proxy_constructor =
5058 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005059 DCHECK(proxy_constructor != nullptr)
5060 << "Could not find <init> method in java.lang.reflect.Proxy";
5061
Jeff Haodb8a6642014-08-14 17:18:52 -07005062 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5063 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005064 DCHECK(out != nullptr);
5065 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005066 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005067 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005068 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005069 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5070 kAccPublic |
5071 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005072 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005073
5074 // Set the original constructor method.
5075 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005076}
5077
Mathieu Chartiere401d142015-04-22 13:56:20 -07005078void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005079 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005080 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5081 CHECK_STREQ(np->GetName(), "<init>");
5082 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005083 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005084}
5085
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005086void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005087 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005088 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005089 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005090 DCHECK(out != nullptr);
5091 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005092
Alex Lighte9dd04f2016-03-16 16:09:45 -07005093 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005094 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005095 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5096 // preference to the invocation handler.
5097 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5098 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005099 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5100 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005101 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5102
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005103 // Set the original interface method.
5104 out->SetDataPtrSize(prototype, image_pointer_size_);
5105
Ian Rogers466bb252011-10-14 03:29:56 -07005106 // At runtime the method looks like a reference and argument saving method, clone the code
5107 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005108 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005109}
Jesse Wilson95caa792011-10-12 18:14:17 -04005110
Mathieu Chartiere401d142015-04-22 13:56:20 -07005111void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005112 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005113 CHECK(!prototype->IsFinal());
5114 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005115 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005116
5117 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5118 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005119 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005120 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005121}
5122
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005123bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005124 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005125 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005126 return true;
5127 }
5128 if (!can_init_statics) {
5129 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005130 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005131 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005132 return false;
5133 }
5134 // Check if there are encoded static values needing initialization.
5135 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005136 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005137 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005138 if (dex_class_def->static_values_off_ != 0) {
5139 return false;
5140 }
5141 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005142 }
5143 // If we are a class we need to initialize all interfaces with default methods when we are
5144 // initialized. Check all of them.
5145 if (!klass->IsInterface()) {
5146 size_t num_interfaces = klass->GetIfTableCount();
5147 for (size_t i = 0; i < num_interfaces; i++) {
5148 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5149 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5150 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005151 return false;
5152 }
5153 }
5154 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005155 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005156 if (klass->IsInterface() || !klass->HasSuperClass()) {
5157 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005158 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005159 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005160 if (super_class->IsInitialized()) {
5161 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005162 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005163 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005164}
5165
Mathieu Chartier23369542020-03-04 08:24:11 -08005166bool ClassLinker::InitializeClass(Thread* self,
5167 Handle<mirror::Class> klass,
5168 bool can_init_statics,
5169 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005170 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5171
5172 // Are we already initialized and therefore done?
5173 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5174 // an initialized class will never change its state.
5175 if (klass->IsInitialized()) {
5176 return true;
5177 }
5178
5179 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005180 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005181 return false;
5182 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005183
Ian Rogers7b078e82014-09-10 14:44:24 -07005184 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005185 Runtime* const runtime = Runtime::Current();
5186 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005187 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005188 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005189 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005190
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005191 // Re-check under the lock in case another thread initialized ahead of us.
5192 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005193 return true;
5194 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005195
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005196 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005197 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005198 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005199 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005200 return false;
5201 }
5202
Vladimir Marko72ab6842017-01-20 19:32:50 +00005203 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5204 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005205
5206 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005207 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005208 if (!klass->IsVerified()) {
5209 // We failed to verify, expect either the klass to be erroneous or verification failed at
5210 // compile time.
5211 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005212 // The class is erroneous. This may be a verifier error, or another thread attempted
5213 // verification and/or initialization and failed. We can distinguish those cases by
5214 // whether an exception is already pending.
5215 if (self->IsExceptionPending()) {
5216 // Check that it's a VerifyError.
5217 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005218 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005219 } else {
5220 // Check that another thread attempted initialization.
5221 DCHECK_NE(0, klass->GetClinitThreadId());
5222 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5223 // Need to rethrow the previous failure now.
5224 ThrowEarlierClassFailure(klass.Get(), true);
5225 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005226 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005227 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005228 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005229 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005230 self->AssertNoPendingException();
5231 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005232 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005233 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005234 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005235 } else {
5236 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005237 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005238
5239 // A separate thread could have moved us all the way to initialized. A "simple" example
5240 // involves a subclass of the current class being initialized at the same time (which
5241 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005242 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005243 if (klass->IsInitialized()) {
5244 return true;
5245 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005246 }
5247
Vladimir Marko2c64a832018-01-04 11:31:56 +00005248 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005249 // initializing higher up the stack or another thread has beat us
5250 // to initializing and we need to wait. Either way, this
5251 // invocation of InitializeClass will not be responsible for
5252 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005253 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005254 // Could have got an exception during verification.
5255 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005256 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005257 return false;
5258 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005259 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005260 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005261 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005262 return true;
5263 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005264 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005265 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005266 }
5267
Jeff Haoe2e40342017-07-19 10:45:18 -07005268 // Try to get the oat class's status for this class if the oat file is present. The compiler
5269 // tries to validate superclass descriptors, and writes the result into the oat file.
5270 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5271 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5272 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005273 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005274 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5275 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5276 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005277 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005278 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005279 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005280 return false;
5281 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005282 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005283
Vladimir Marko2c64a832018-01-04 11:31:56 +00005284 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005285 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005286
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005287 // From here out other threads may observe that we're initializing and so changes of state
5288 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005289 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005290 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005291
Mathieu Chartier23369542020-03-04 08:24:11 -08005292 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005293 }
5294
Andreas Gampeaf864702019-07-23 14:05:35 -07005295 uint64_t t_sub = 0;
5296
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005297 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005298 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005299 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005300 if (!super_class->IsInitialized()) {
5301 CHECK(!super_class->IsInterface());
5302 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005303 StackHandleScope<1> hs(self);
5304 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005305 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005306 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005307 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005308 if (!super_initialized) {
5309 // The super class was verified ahead of entering initializing, we should only be here if
5310 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005311 // For the case of aot compiler, the super class might also be initializing but we don't
5312 // want to process circular dependencies in pre-compile.
5313 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005314 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005315 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005316 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005317 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005318 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005319 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005320 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005321 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005322 return false;
5323 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005324 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005325 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005326 }
5327
Alex Lighteb7c1442015-08-31 13:17:42 -07005328 if (!klass->IsInterface()) {
5329 // Initialize interfaces with default methods for the JLS.
5330 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005331 // Only setup the (expensive) handle scope if we actually need to.
5332 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005333 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005334 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5335 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005336 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005337 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005338 CHECK(handle_scope_iface->IsInterface());
5339 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5340 // We have already done this for this interface. Skip it.
5341 continue;
5342 }
5343 // We cannot just call initialize class directly because we need to ensure that ALL
5344 // interfaces with default methods are initialized. Non-default interface initialization
5345 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005346 // This is not very precise, misses all walking.
5347 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005348 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5349 handle_scope_iface,
5350 can_init_statics,
5351 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005352 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005353 if (!iface_initialized) {
5354 ObjectLock<mirror::Class> lock(self, klass);
5355 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005356 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005357 return false;
5358 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005359 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005360 }
5361 }
5362 }
5363
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005364 const size_t num_static_fields = klass->NumStaticFields();
5365 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005366 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005367 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005368 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005369 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005370 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005371
5372 // Eagerly fill in static fields so that the we don't have to do as many expensive
5373 // Class::FindStaticField in ResolveField.
5374 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005375 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005376 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005377 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005378 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005379 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005380 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5381 field,
5382 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5383 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005384 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005385 } else {
5386 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005387 }
5388 }
5389
Vladimir Markoe11dd502017-12-08 14:09:45 +00005390 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5391 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005392 this,
5393 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005394 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005395
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005396 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005397 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005398 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005399 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5400 if (!value_it.HasNext()) {
5401 break;
5402 }
5403 ArtField* art_field = ResolveField(field.GetIndex(),
5404 dex_cache,
5405 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005406 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005407 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005408 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005409 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005410 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005411 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005412 if (self->IsExceptionPending()) {
5413 break;
5414 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005415 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005416 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005417 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005418 }
5419 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005420
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005421
Mathieu Chartierda595be2016-08-10 13:57:39 -07005422 if (!self->IsExceptionPending()) {
5423 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5424 if (clinit != nullptr) {
5425 CHECK(can_init_statics);
5426 JValue result;
5427 clinit->Invoke(self, nullptr, 0, &result, "V");
5428 }
5429 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005430 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005431 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005432
Vladimir Markobf121912019-06-04 13:49:05 +01005433 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005434 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005435 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005436 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005437
5438 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005439 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005440 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005441 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005442 } else if (Runtime::Current()->IsTransactionAborted()) {
5443 // The exception thrown when the transaction aborted has been caught and cleared
5444 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005445 VLOG(compiler) << "Return from class initializer of "
5446 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005447 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005448 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005449 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005450 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005451 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005452 if (stats_enabled) {
5453 RuntimeStats* global_stats = runtime->GetStats();
5454 RuntimeStats* thread_stats = self->GetStats();
5455 ++global_stats->class_init_count;
5456 ++thread_stats->class_init_count;
5457 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5458 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5459 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005460 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005461 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005462 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005463 std::string temp;
5464 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005465 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005466 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005467 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005468 }
Vladimir Markobf121912019-06-04 13:49:05 +01005469 if (callback != nullptr) {
5470 callback->MakeVisible(self);
5471 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005472 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005473}
5474
Alex Lighteb7c1442015-08-31 13:17:42 -07005475// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5476// and perform the initialization only on those interfaces that contain default methods.
5477bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5478 Handle<mirror::Class> iface,
5479 bool can_init_statics,
5480 bool can_init_parents) {
5481 CHECK(iface->IsInterface());
5482 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005483 // Only create the (expensive) handle scope if we need it.
5484 if (UNLIKELY(num_direct_ifaces > 0)) {
5485 StackHandleScope<1> hs(self);
5486 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5487 // First we initialize all of iface's super-interfaces recursively.
5488 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005489 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005490 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005491 if (!super_iface->HasBeenRecursivelyInitialized()) {
5492 // Recursive step
5493 handle_super_iface.Assign(super_iface);
5494 if (!InitializeDefaultInterfaceRecursive(self,
5495 handle_super_iface,
5496 can_init_statics,
5497 can_init_parents)) {
5498 return false;
5499 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005500 }
5501 }
5502 }
5503
5504 bool result = true;
5505 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5506 // initialize if we don't have default methods.
5507 if (iface->HasDefaultMethods()) {
5508 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5509 }
5510
5511 // Mark that this interface has undergone recursive default interface initialization so we know we
5512 // can skip it on any later class initializations. We do this even if we are not a default
5513 // interface since we can still avoid the traversal. This is purely a performance optimization.
5514 if (result) {
5515 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005516 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5517 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5518 // initialization is a performance optimization (to avoid another idempotent visit
5519 // for other implementing classes/interfaces), and can be revisited later.
5520 ObjectTryLock<mirror::Class> lock(self, iface);
5521 if (lock.Acquired()) {
5522 iface->SetRecursivelyInitialized();
5523 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005524 }
5525 return result;
5526}
5527
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005528bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5529 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005530 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005531 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005532 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005533 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005534 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005535 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005536
5537 // When we wake up, repeat the test for init-in-progress. If
5538 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005539 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005540 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005541 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005542 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005543 return false;
5544 }
5545 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005546 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005547 continue;
5548 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005549 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005550 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005551 // Compile time initialization failed.
5552 return false;
5553 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005554 if (klass->IsErroneous()) {
5555 // The caller wants an exception, but it was thrown in a
5556 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005557 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005558 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005559 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005560 return false;
5561 }
5562 if (klass->IsInitialized()) {
5563 return true;
5564 }
David Sehr709b0702016-10-13 09:12:37 -07005565 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005566 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005567 }
Ian Rogers07140832014-09-30 15:43:59 -07005568 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005569}
5570
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005571static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5572 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005573 ArtMethod* method,
5574 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005575 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005576 DCHECK(Thread::Current()->IsExceptionPending());
5577 DCHECK(!m->IsProxyMethod());
5578 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005579 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5580 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005581 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005582 std::string return_type = dex_file->PrettyType(return_type_idx);
5583 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005584 ThrowWrappedLinkageError(klass.Get(),
5585 "While checking class %s method %s signature against %s %s: "
5586 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005587 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5588 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005589 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005590 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005591 return_type.c_str(), class_loader.c_str());
5592}
5593
5594static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5595 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005596 ArtMethod* method,
5597 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005598 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005599 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005600 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005601 DCHECK(Thread::Current()->IsExceptionPending());
5602 DCHECK(!m->IsProxyMethod());
5603 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005604 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5605 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005606 ThrowWrappedLinkageError(klass.Get(),
5607 "While checking class %s method %s signature against %s %s: "
5608 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005609 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5610 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005611 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005612 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005613 index, arg_type.c_str(), class_loader.c_str());
5614}
5615
5616static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5617 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005618 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005619 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005620 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005621 ThrowLinkageError(klass.Get(),
5622 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005623 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5624 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005625 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005626 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005627 error_msg.c_str());
5628}
5629
Ian Rogersb5fb2072014-12-02 17:22:02 -08005630static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005631 Handle<mirror::Class> klass,
5632 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005633 ArtMethod* method1,
5634 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005635 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005636 {
5637 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005638 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005639 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005640 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005641 return false;
5642 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005643 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005644 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005645 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005646 return false;
5647 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005648 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005649 ThrowSignatureMismatch(klass, super_klass, method1,
5650 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005651 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005652 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005653 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005654 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005655 return false;
5656 }
5657 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005658 const dex::TypeList* types1 = method1->GetParameterTypeList();
5659 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005660 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005661 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005662 ThrowSignatureMismatch(klass, super_klass, method1,
5663 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005664 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005665 return false;
5666 }
5667 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005668 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005669 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005670 ThrowSignatureMismatch(klass, super_klass, method1,
5671 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005672 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005673 return false;
5674 }
5675 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005676 }
5677 uint32_t num_types = types1->Size();
5678 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005679 ThrowSignatureMismatch(klass, super_klass, method1,
5680 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005681 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005682 return false;
5683 }
5684 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005685 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005686 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005687 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005688 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005689 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005690 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005691 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005692 return false;
5693 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005694 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005695 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005696 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005697 if (UNLIKELY(other_param_type == nullptr)) {
5698 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005699 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005700 return false;
5701 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005702 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005703 ThrowSignatureMismatch(klass, super_klass, method1,
5704 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5705 i,
David Sehr709b0702016-10-13 09:12:37 -07005706 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005707 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005708 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005709 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005710 return false;
5711 }
5712 }
5713 return true;
5714}
5715
5716
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005717bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005718 if (klass->IsInterface()) {
5719 return true;
5720 }
Ian Rogers151f2212014-05-06 11:27:27 -07005721 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005722 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005723 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005724 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005725 if (klass->HasSuperClass() &&
5726 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005727 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005728 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005729 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5730 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5731 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005732 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5733 klass,
5734 super_klass,
5735 m,
5736 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005737 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005738 return false;
5739 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005740 }
5741 }
5742 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005743 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005744 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5745 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5746 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005747 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005748 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5749 j, image_pointer_size_);
5750 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5751 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005752 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5753 klass,
5754 super_klass,
5755 m,
5756 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005757 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005758 return false;
5759 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005760 }
5761 }
5762 }
5763 }
5764 return true;
5765}
5766
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005767bool ClassLinker::EnsureInitialized(Thread* self,
5768 Handle<mirror::Class> c,
5769 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005770 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005771 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005772
Mathieu Chartier524507a2014-08-27 15:28:28 -07005773 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005774 // If we've seen an initialized but not visibly initialized class
5775 // many times, request visible initialization.
5776 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5777 // Thanks to the x86 memory model classes skip the initialized status.
5778 DCHECK(c->IsVisiblyInitialized());
5779 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5780 if (self->IncrementMakeVisiblyInitializedCounter()) {
5781 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5782 }
5783 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005784 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005785 return true;
5786 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005787 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5788 //
5789 // Ensure the bitstring is initialized before any of the class initialization
5790 // logic occurs. Once a class initializer starts running, objects can
5791 // escape into the heap and use the subtype checking code.
5792 //
5793 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5794 // can be used as a source for the IsSubClass check, and that all ancestors
5795 // of the class are Assigned (can be used as a target for IsSubClass check)
5796 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005797 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005798 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005799 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005800 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5801 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005802 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005803 if (!success) {
5804 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005805 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005806 }
5807 } else {
5808 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005809 }
5810 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005811}
5812
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005813void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5814 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005815 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005816 for (ArtField& field : new_class->GetIFields()) {
5817 if (field.GetDeclaringClass() == temp_class) {
5818 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005819 }
5820 }
5821
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005822 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005823 for (ArtField& field : new_class->GetSFields()) {
5824 if (field.GetDeclaringClass() == temp_class) {
5825 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005826 }
5827 }
5828
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005829 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005830 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005831 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005832 if (method.GetDeclaringClass() == temp_class) {
5833 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005834 }
5835 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005836
5837 // Make sure the remembered set and mod-union tables know that we updated some of the native
5838 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005839 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005840}
5841
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005842void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005843 CHECK(class_loader->GetAllocator() == nullptr);
5844 CHECK(class_loader->GetClassTable() == nullptr);
5845 Thread* const self = Thread::Current();
5846 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005847 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005848 // Create and set the class table.
5849 data.class_table = new ClassTable;
5850 class_loader->SetClassTable(data.class_table);
5851 // Create and set the linear allocator.
5852 data.allocator = Runtime::Current()->CreateLinearAlloc();
5853 class_loader->SetAllocator(data.allocator);
5854 // Add to the list so that we know to free the data later.
5855 class_loaders_.push_back(data);
5856}
5857
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005858ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005859 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005860 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005861 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005862 ClassTable* class_table = class_loader->GetClassTable();
5863 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005864 RegisterClassLoader(class_loader);
5865 class_table = class_loader->GetClassTable();
5866 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005867 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005868 return class_table;
5869}
5870
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005871ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005872 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005873}
5874
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005875static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005876 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005877 while (klass->HasSuperClass()) {
5878 klass = klass->GetSuperClass();
5879 if (klass->ShouldHaveImt()) {
5880 return klass->GetImt(pointer_size);
5881 }
5882 }
5883 return nullptr;
5884}
5885
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005886bool ClassLinker::LinkClass(Thread* self,
5887 const char* descriptor,
5888 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005889 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005890 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005891 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005892
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005893 if (!LinkSuperClass(klass)) {
5894 return false;
5895 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005896 ArtMethod* imt_data[ImTable::kSize];
5897 // If there are any new conflicts compared to super class.
5898 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005899 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005900 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005901 return false;
5902 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005903 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005904 return false;
5905 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005906 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005907 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005908 return false;
5909 }
5910 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005911 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005912
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005913 ImTable* imt = nullptr;
5914 if (klass->ShouldHaveImt()) {
5915 // If there are any new conflicts compared to the super class we can not make a copy. There
5916 // can be cases where both will have a conflict method at the same slot without having the same
5917 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5918 // will possibly create a table that is incorrect for either of the classes.
5919 // Same IMT with new_conflict does not happen very often.
5920 if (!new_conflict) {
5921 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5922 if (super_imt != nullptr) {
5923 bool imt_equals = true;
5924 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5925 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5926 }
5927 if (imt_equals) {
5928 imt = super_imt;
5929 }
5930 }
5931 }
5932 if (imt == nullptr) {
5933 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5934 imt = reinterpret_cast<ImTable*>(
5935 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5936 if (imt == nullptr) {
5937 return false;
5938 }
5939 imt->Populate(imt_data, image_pointer_size_);
5940 }
5941 }
5942
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005943 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5944 // We don't need to retire this class as it has no embedded tables or it was created the
5945 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005946 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005947
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005948 if (klass->ShouldHaveEmbeddedVTable()) {
5949 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005950 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005951 if (klass->ShouldHaveImt()) {
5952 klass->SetImt(imt, image_pointer_size_);
5953 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005954
5955 // Update CHA info based on whether we override methods.
5956 // Have to do this before setting the class as resolved which allows
5957 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005958 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005959 cha_->UpdateAfterLoadingOf(klass);
5960 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005961
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005962 // This will notify waiters on klass that saw the not yet resolved
5963 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005964 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005965 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005966 } else {
5967 CHECK(!klass->IsResolved());
5968 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005969 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01005970 Handle<mirror::Class> h_new_class =
5971 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005972 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5973 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5974 // may not see any references to the target space and clean the card for a class if another
5975 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005976 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005977 klass->SetSFieldsPtrUnchecked(nullptr);
5978 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005979 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005980 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005981 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005982 return false;
5983 }
5984
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005985 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5986 ObjectLock<mirror::Class> lock(self, h_new_class);
5987 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005988
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005989 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005990 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005991 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005992 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005993 const ObjPtr<mirror::Class> existing =
5994 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005995 if (class_loader != nullptr) {
5996 // We updated the class in the class table, perform the write barrier so that the GC knows
5997 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005998 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005999 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006000 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006001 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006002 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6003 }
6004 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006005
Mingyao Yang063fc772016-08-02 11:02:54 -07006006 // Update CHA info based on whether we override methods.
6007 // Have to do this before setting the class as resolved which allows
6008 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006009 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006010 cha_->UpdateAfterLoadingOf(h_new_class);
6011 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006012
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006013 // This will notify waiters on temp class that saw the not yet resolved class in the
6014 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006015 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006016
Vladimir Marko2c64a832018-01-04 11:31:56 +00006017 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006018 // This will notify waiters on new_class that saw the not yet resolved
6019 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006020 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006021 // Return the new class.
6022 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006023 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006024 return true;
6025}
6026
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006027bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006028 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006029 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006030 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6031 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006032 // Check that a class does not inherit from itself directly.
6033 //
6034 // TODO: This is a cheap check to detect the straightforward case
6035 // of a class extending itself (b/28685551), but we should do a
6036 // proper cycle detection on loaded classes, to detect all cases
6037 // of class circularity errors (b/28830038).
6038 if (super_class_idx == class_def.class_idx_) {
6039 ThrowClassCircularityError(klass.Get(),
6040 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006041 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006042 return false;
6043 }
6044
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006045 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006046 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006047 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006048 return false;
6049 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006050 // Verify
6051 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006052 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006053 super_class->PrettyDescriptor().c_str(),
6054 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006055 return false;
6056 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006057 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006058 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006059 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006060 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006061 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006062 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006063 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006064 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006065 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006066 DCHECK(Thread::Current()->IsExceptionPending());
6067 return false;
6068 }
6069 // Verify
6070 if (!klass->CanAccess(interface)) {
6071 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006072 ThrowIllegalAccessError(klass.Get(),
6073 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006074 interface->PrettyDescriptor().c_str(),
6075 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006076 return false;
6077 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006078 }
6079 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006080 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006081 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006082 return true;
6083}
6084
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006085bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006086 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006087 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006088 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6089 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006090 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006091 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006092 return false;
6093 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006094 return true;
6095 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006096 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006097 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006098 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006099 return false;
6100 }
6101 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006102 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006103 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6104 return false;
6105 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006106 if (super->IsFinal()) {
6107 ThrowVerifyError(klass.Get(),
6108 "Superclass %s of %s is declared final",
6109 super->PrettyDescriptor().c_str(),
6110 klass->PrettyDescriptor().c_str());
6111 return false;
6112 }
6113 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006114 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006115 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006116 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006117 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006118 return false;
6119 }
6120 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006121 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006122 super->PrettyDescriptor().c_str(),
6123 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006124 return false;
6125 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006126
Brian Carlstromf3632832014-05-20 15:36:53 -07006127 // Inherit kAccClassIsFinalizable from the superclass in case this
6128 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006129 if (super->IsFinalizable()) {
6130 klass->SetFinalizable();
6131 }
6132
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006133 // Inherit class loader flag form super class.
6134 if (super->IsClassLoaderClass()) {
6135 klass->SetClassLoaderClass();
6136 }
6137
Elliott Hughes2da50362011-10-10 16:57:08 -07006138 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006139 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006140 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006141 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006142 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006143 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006144 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006145 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006146 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006147 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006148 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006149 return false;
6150 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006151
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006152 if (kIsDebugBuild) {
6153 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006154 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006155 CHECK(super->IsResolved());
6156 super = super->GetSuperClass();
6157 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006158 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006159 return true;
6160}
6161
Vladimir Marko782fb712020-12-23 12:47:31 +00006162// A wrapper class representing the result of a method translation used for linking methods and
6163// updating superclass default methods. For each method in a classes vtable there are 4 states it
6164// could be in:
6165// 1) No translation is necessary. In this case there is no MethodTranslation object for it. This
6166// is the standard case and is true when the method is not overridable by a default method,
6167// the class defines a concrete implementation of the method, the default method implementation
6168// remains the same, or an abstract method stayed abstract.
6169// 2) The method must be translated to a different default method. We note this with
6170// CreateTranslatedMethod.
6171// 3) The method must be replaced with a conflict method. This happens when a superclass
6172// implements an interface with a default method and this class implements an unrelated
6173// interface that also defines that default method. We note this with CreateConflictingMethod.
6174// 4) The method must be replaced with an abstract miranda method. This happens when a superclass
6175// implements an interface with a default method and this class implements a subinterface of
6176// the superclass's interface which declares the default method abstract. We note this with
6177// CreateAbstractMethod.
6178//
6179// When a method translation is unnecessary (case #1), we don't put it into the
6180// default_translation maps. So an instance of MethodTranslation must be in one of #2-#4.
6181class ClassLinker::MethodTranslation {
6182 public:
6183 MethodTranslation() : translation_(nullptr), type_(Type::kInvalid) {}
6184
6185 // This slot must become a default conflict method.
6186 static MethodTranslation CreateConflictingMethod() {
6187 return MethodTranslation(Type::kConflict, /*translation=*/nullptr);
6188 }
6189
6190 // This slot must become an abstract method.
6191 static MethodTranslation CreateAbstractMethod() {
6192 return MethodTranslation(Type::kAbstract, /*translation=*/nullptr);
6193 }
6194
6195 // Use the given method as the current value for this vtable slot during translation.
6196 static MethodTranslation CreateTranslatedMethod(ArtMethod* new_method) {
6197 return MethodTranslation(Type::kTranslation, new_method);
6198 }
6199
6200 // Returns true if this is a method that must become a conflict method.
6201 bool IsInConflict() const {
6202 return type_ == Type::kConflict;
6203 }
6204
6205 // Returns true if this is a method that must become an abstract method.
6206 bool IsAbstract() const {
6207 return type_ == Type::kAbstract;
6208 }
6209
6210 // Returns true if this is a method that must become a different method.
6211 bool IsTranslation() const {
6212 return type_ == Type::kTranslation;
6213 }
6214
6215 // Get the translated version of this method.
6216 ArtMethod* GetTranslation() const {
6217 DCHECK(IsTranslation());
6218 DCHECK(translation_ != nullptr);
6219 return translation_;
6220 }
6221
6222 private:
6223 enum class Type {
6224 kInvalid,
6225 kTranslation,
6226 kConflict,
6227 kAbstract,
6228 };
6229
6230 MethodTranslation(Type type, ArtMethod* translation)
6231 : translation_(translation), type_(type) {}
6232
6233 ArtMethod* translation_;
6234 Type type_;
6235};
6236
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006237// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006238bool ClassLinker::LinkMethods(Thread* self,
6239 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006240 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006241 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006242 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006243 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006244 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6245 // need to have default methods be in the virtuals array of each class but we don't set that up
6246 // until LinkInterfaceMethods.
Vladimir Marko782fb712020-12-23 12:47:31 +00006247 constexpr size_t kBufferSize = 8; // Avoid malloc/free for a few translations.
6248 std::pair<size_t, ClassLinker::MethodTranslation> buffer[kBufferSize];
6249 HashMap<size_t, ClassLinker::MethodTranslation> default_translations(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07006250 // Link virtual methods then interface methods.
6251 // We set up the interface lookup table first because we need it to determine if we need to update
6252 // any vtable entries with new default method implementations.
6253 return SetupInterfaceLookupTable(self, klass, interfaces)
6254 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006255 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006256}
6257
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006258// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6259// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6260// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006261class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006262 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006263 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006264 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006265 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6266 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006267 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006268 }
6269
6270 const char* GetName() {
6271 if (name_ == nullptr) {
6272 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6273 }
6274 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006275 }
6276
Mathieu Chartiere401d142015-04-22 13:56:20 -07006277 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006278 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006279 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006280 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006281 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006282 if (dex_file_ == other_dex_file) {
6283 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6284 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006285 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006286 uint32_t other_name_len;
6287 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6288 &other_name_len);
6289 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6290 return false;
6291 }
6292 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6293 }
6294
6295 private:
6296 // Dex file for the method to compare against.
6297 const DexFile* const dex_file_;
6298 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006299 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006300 // Lazily computed name from the dex file's strings.
6301 const char* name_;
6302 // Lazily computed name length.
6303 uint32_t name_len_;
6304};
6305
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006306class LinkVirtualHashTable {
6307 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006308 LinkVirtualHashTable(Handle<mirror::Class> klass,
6309 size_t hash_size,
6310 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006311 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006312 : klass_(klass),
6313 hash_size_(hash_size),
6314 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006315 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006316 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6317 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006318
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006319 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006320 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6321 virtual_method_index, image_pointer_size_);
6322 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006323 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006324 uint32_t index = hash % hash_size_;
6325 // Linear probe until we have an empty slot.
6326 while (hash_table_[index] != invalid_index_) {
6327 if (++index == hash_size_) {
6328 index = 0;
6329 }
6330 }
6331 hash_table_[index] = virtual_method_index;
6332 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006333
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006334 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006335 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006336 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006337 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006338 size_t index = hash % hash_size_;
6339 while (true) {
6340 const uint32_t value = hash_table_[index];
6341 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6342 // the block and can safely assume not found.
6343 if (value == invalid_index_) {
6344 break;
6345 }
6346 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006347 ArtMethod* virtual_method =
6348 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6349 if (comparator->HasSameNameAndSignature(
6350 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006351 hash_table_[index] = removed_index_;
6352 return value;
6353 }
6354 }
6355 if (++index == hash_size_) {
6356 index = 0;
6357 }
6358 }
6359 return GetNotFoundIndex();
6360 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006361
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006362 static uint32_t GetNotFoundIndex() {
6363 return invalid_index_;
6364 }
6365
6366 private:
6367 static const uint32_t invalid_index_;
6368 static const uint32_t removed_index_;
6369
6370 Handle<mirror::Class> klass_;
6371 const size_t hash_size_;
6372 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006373 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006374};
6375
6376const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6377const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6378
Stephen Hines1ddd9132017-02-08 01:51:18 -08006379bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006380 Thread* self,
6381 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00006382 /*out*/HashMap<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006383 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006384 if (klass->IsInterface()) {
6385 // No vtable.
6386 if (!IsUint<16>(num_virtual_methods)) {
6387 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6388 return false;
6389 }
6390 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006391 // Assign each method an IMT index and set the default flag.
6392 for (size_t i = 0; i < num_virtual_methods; ++i) {
6393 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6394 m->SetMethodIndex(i);
6395 if (!m->IsAbstract()) {
Vladimir Marko1c993cd2020-05-28 09:30:06 +00006396 // If the dex file does not support default methods, throw ClassFormatError.
6397 // This check is necessary to protect from odd cases, such as native default
6398 // methods, that the dex file verifier permits for old dex file versions. b/157170505
6399 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
6400 // currently running CTS tests for default methods with dex file version 035 which
6401 // does not support default methods. So, we limit this to native methods. b/157718952
6402 if (m->IsNative()) {
6403 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
6404 ThrowClassFormatError(klass.Get(),
6405 "Dex file does not support default method '%s'",
6406 m->PrettyMethod().c_str());
6407 return false;
6408 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006409 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6410 has_defaults = true;
6411 }
6412 }
6413 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6414 // during initialization. This is a performance optimization. We could simply traverse the
6415 // virtual_methods_ array again during initialization.
6416 if (has_defaults) {
6417 klass->SetHasDefaultMethods();
6418 }
6419 return true;
6420 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006421 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6422 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006423 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006424 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006425 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006426 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006427 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006428 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006429 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006430 return false;
6431 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006432 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006433 vtable->SetElementPtrSize(
6434 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006435 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006436 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6437 // might give us new default methods). If no new interfaces then we can skip the rest since
6438 // the class cannot override any of the super-class's methods. This is required for
6439 // correctness since without it we might not update overridden default method vtable entries
6440 // correctly.
6441 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006442 klass->SetVTable(vtable.Get());
6443 return true;
6444 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006445 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006446 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006447 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006448 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006449 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6450 // might give us new default methods). See comment above.
6451 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006452 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006453 return true;
6454 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006455 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6456 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006457 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006458 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006459 return false;
6460 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006461 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006462 // How the algorithm works:
6463 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6464 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6465 // method which has not been matched to a vtable method, and j if the virtual method at the
6466 // index overrode the super virtual method at index j.
6467 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6468 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6469 // the need for the initial vtable which we later shrink back down).
6470 // 3. Add non overridden methods to the end of the vtable.
6471 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006472 // + 1 so that even if we only have new default methods we will still be able to use this hash
6473 // table (i.e. it will never have 0 size).
6474 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006475 uint32_t* hash_table_ptr;
6476 std::unique_ptr<uint32_t[]> hash_heap_storage;
6477 if (hash_table_size <= kMaxStackHash) {
6478 hash_table_ptr = reinterpret_cast<uint32_t*>(
6479 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6480 } else {
6481 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6482 hash_table_ptr = hash_heap_storage.get();
6483 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006484 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006485 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006486 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006487 DCHECK(klass->GetVirtualMethodDuringLinking(
6488 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006489 hash_table.Add(i);
6490 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006491 // 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 -07006492 // the hash table.
6493 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006494 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006495 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006496 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6497 super_method->GetAccessFlags())) {
6498 // Continue on to the next method since this one is package private and canot be overridden.
6499 // Before Android 4.1, the package-private method super_method might have been incorrectly
6500 // overridden.
6501 continue;
6502 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006503 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006504 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006505 // We remove the method so that subsequent lookups will be faster by making the hash-map
6506 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006507 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6508 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006509 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6510 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006511 if (super_method->IsFinal()) {
6512 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6513 virtual_method->PrettyMethod().c_str(),
6514 super_method->GetDeclaringClassDescriptor());
6515 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006516 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006517 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6518 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006519 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006520 // We didn't directly override this method but we might through default methods...
6521 // Check for default method update.
6522 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006523 switch (FindDefaultMethodImplementation(self,
6524 super_method,
6525 klass,
6526 /*out*/&default_method)) {
6527 case DefaultMethodSearchResult::kDefaultConflict: {
6528 // A conflict was found looking for default methods. Note this (assuming it wasn't
6529 // pre-existing) in the translations map.
6530 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6531 // Don't generate another conflict method to reduce memory use as an optimization.
6532 default_translations->insert(
6533 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6534 }
6535 break;
6536 }
6537 case DefaultMethodSearchResult::kAbstractFound: {
6538 // No conflict but method is abstract.
6539 // We note that this vtable entry must be made abstract.
6540 if (UNLIKELY(!super_method->IsAbstract())) {
6541 default_translations->insert(
6542 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6543 }
6544 break;
6545 }
6546 case DefaultMethodSearchResult::kDefaultFound: {
6547 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6548 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6549 // Found a default method implementation that is new.
6550 // TODO Refactor this add default methods to virtuals here and not in
6551 // LinkInterfaceMethods maybe.
6552 // The problem is default methods might override previously present
6553 // default-method or miranda-method vtable entries from the superclass.
6554 // Unfortunately we need these to be entries in this class's virtuals. We do not
6555 // give these entries there until LinkInterfaceMethods so we pass this map around
6556 // to let it know which vtable entries need to be updated.
6557 // Make a note that vtable entry j must be updated, store what it needs to be updated
6558 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6559 // then.
6560 default_translations->insert(
6561 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006562 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6563 << " overridden by default "
6564 << default_method->PrettyMethod()
6565 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006566 }
6567 break;
6568 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006569 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006570 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006571 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006572 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006573 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006574 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006575 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006576 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6577 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006578 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006579 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006580 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006581 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006582 local_method->SetMethodIndex(actual_count);
6583 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006584 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006585 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006586 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006587 return false;
6588 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006589 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006590 CHECK_LE(actual_count, max_count);
6591 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006592 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6593 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006594 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006595 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006596 return false;
6597 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006598 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006599 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006600 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006601 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006602 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006603 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6604 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006605 return false;
6606 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006607 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006608 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006609 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006610 return false;
6611 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006612 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006613 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6614 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006615 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006616 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006617 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006618 }
6619 return true;
6620}
6621
Alex Light9139e002015-10-09 15:59:48 -07006622// Determine if the given iface has any subinterface in the given list that declares the method
6623// specified by 'target'.
6624//
6625// Arguments
6626// - self: The thread we are running on
6627// - target: A comparator that will match any method that overrides the method we are checking for
6628// - iftable: The iftable we are searching for an overriding method on.
6629// - ifstart: The index of the interface we are checking to see if anything overrides
6630// - iface: The interface we are checking to see if anything overrides.
6631// - image_pointer_size:
6632// The image pointer size.
6633//
6634// Returns
6635// - True: There is some method that matches the target comparator defined in an interface that
6636// is a subtype of iface.
6637// - False: There is no method that matches the target comparator in any interface that is a subtype
6638// of iface.
6639static bool ContainsOverridingMethodOf(Thread* self,
6640 MethodNameAndSignatureComparator& target,
6641 Handle<mirror::IfTable> iftable,
6642 size_t ifstart,
6643 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006644 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006645 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006646 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006647 DCHECK(iface != nullptr);
6648 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006649 DCHECK_GE(ifstart, 0u);
6650 DCHECK_LT(ifstart, iftable->Count());
6651 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6652 DCHECK(iface->IsInterface());
6653
6654 size_t iftable_count = iftable->Count();
6655 StackHandleScope<1> hs(self);
6656 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6657 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6658 // Skip ifstart since our current interface obviously cannot override itself.
6659 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006660 // Iterate through every method on this interface. The order does not matter.
6661 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006662 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006663 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006664 // Check if the i'th interface is a subtype of this one.
6665 if (iface->IsAssignableFrom(current_iface.Get())) {
6666 return true;
6667 }
6668 break;
6669 }
6670 }
6671 }
6672 return false;
6673}
6674
Alex Lighteb7c1442015-08-31 13:17:42 -07006675// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006676// out_default_method and returns kDefaultFound on success. If no default method was found return
6677// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6678// default_method conflict) it will return kDefaultConflict.
6679ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6680 Thread* self,
6681 ArtMethod* target_method,
6682 Handle<mirror::Class> klass,
6683 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006684 DCHECK(self != nullptr);
6685 DCHECK(target_method != nullptr);
6686 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006687
6688 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006689
6690 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6691 // table. This lets us walk the table backwards when searching for default methods. The first one
6692 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6693 // track of it and then continue checking all other interfaces, since we need to throw an error if
6694 // we encounter conflicting default method implementations (one is not a subtype of the other).
6695 //
6696 // The order of unrelated interfaces does not matter and is not defined.
6697 size_t iftable_count = klass->GetIfTableCount();
6698 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006699 // No interfaces. We have already reset out to null so just return kAbstractFound.
6700 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006701 }
6702
Alex Light9139e002015-10-09 15:59:48 -07006703 StackHandleScope<3> hs(self);
6704 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006705 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006706 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006707 MethodNameAndSignatureComparator target_name_comparator(
6708 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6709 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006710 for (size_t k = iftable_count; k != 0; ) {
6711 --k;
6712
Alex Lighteb7c1442015-08-31 13:17:42 -07006713 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006714
6715 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006716 // Iterate through every declared method on this interface. The order does not matter.
6717 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6718 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006719 // Skip abstract methods and methods with different names.
6720 if (current_method->IsAbstract() ||
6721 !target_name_comparator.HasSameNameAndSignature(
6722 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6723 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006724 } else if (!current_method->IsPublic()) {
6725 // The verifier should have caught the non-public method for dex version 37. Just warn and
6726 // skip it since this is from before default-methods so we don't really need to care that it
6727 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006728 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6729 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006730 << "This will be a fatal error in subsequent versions of android. "
6731 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006732 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006733 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006734 // We have multiple default impls of the same method. This is a potential default conflict.
6735 // We need to check if this possibly conflicting method is either a superclass of the chosen
6736 // default implementation or is overridden by a non-default interface method. In either case
6737 // there is no conflict.
6738 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6739 !ContainsOverridingMethodOf(self,
6740 target_name_comparator,
6741 iftable,
6742 k,
6743 iface,
6744 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006745 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006746 << current_method->PrettyMethod() << " and "
6747 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6748 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006749 *out_default_method = nullptr;
6750 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006751 } else {
6752 break; // Continue checking at the next interface.
6753 }
6754 } else {
Alex Light9139e002015-10-09 15:59:48 -07006755 // chosen_iface == null
6756 if (!ContainsOverridingMethodOf(self,
6757 target_name_comparator,
6758 iftable,
6759 k,
6760 iface,
6761 image_pointer_size_)) {
6762 // Don't set this as the chosen interface if something else is overriding it (because that
6763 // other interface would be potentially chosen instead if it was default). If the other
6764 // interface was abstract then we wouldn't select this interface as chosen anyway since
6765 // the abstract method masks it.
6766 *out_default_method = current_method;
6767 chosen_iface.Assign(iface.Get());
6768 // We should now finish traversing the graph to find if we have default methods that
6769 // conflict.
6770 } else {
David Sehr709b0702016-10-13 09:12:37 -07006771 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6772 << "' was "
6773 << "skipped because it was overridden by an abstract method in a "
6774 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006775 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006776 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006777 break;
6778 }
6779 }
Alex Light9139e002015-10-09 15:59:48 -07006780 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006781 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6782 << "' selected "
6783 << "as the implementation for '" << target_method->PrettyMethod()
6784 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006785 return DefaultMethodSearchResult::kDefaultFound;
6786 } else {
6787 return DefaultMethodSearchResult::kAbstractFound;
6788 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006789}
6790
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006791ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006792 ArtMethod* conflict_method,
6793 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006794 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006795 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006796 Runtime* const runtime = Runtime::Current();
6797 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006798
6799 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006800 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006801 ? runtime->CreateImtConflictMethod(linear_alloc)
6802 : conflict_method;
6803
6804 // Allocate a new table. Note that we will leak this table at the next conflict,
6805 // but that's a tradeoff compared to making the table fixed size.
6806 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006807 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6808 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006809 if (data == nullptr) {
6810 LOG(ERROR) << "Failed to allocate conflict table";
6811 return conflict_method;
6812 }
6813 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6814 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006815 method,
6816 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006817
6818 // Do a fence to ensure threads see the data in the table before it is assigned
6819 // to the conflict method.
6820 // Note that there is a race in the presence of multiple threads and we may leak
6821 // memory from the LinearAlloc, but that's a tradeoff compared to using
6822 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006823 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006824 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006825 return new_conflict_method;
6826}
6827
Vladimir Marko921094a2017-01-12 18:37:06 +00006828bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6829 Handle<mirror::Class> klass,
6830 Handle<mirror::IfTable> iftable) {
6831 DCHECK(!klass->IsInterface());
6832 const bool has_superclass = klass->HasSuperClass();
6833 const bool extend_super_iftable = has_superclass;
6834 const size_t ifcount = klass->GetIfTableCount();
6835 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6836 for (size_t i = 0; i < ifcount; ++i) {
6837 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6838 if (num_methods > 0) {
6839 const bool is_super = i < super_ifcount;
6840 // This is an interface implemented by a super-class. Therefore we can just copy the method
6841 // array from the superclass.
6842 const bool super_interface = is_super && extend_super_iftable;
6843 ObjPtr<mirror::PointerArray> method_array;
6844 if (super_interface) {
6845 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6846 DCHECK(if_table != nullptr);
6847 DCHECK(if_table->GetMethodArray(i) != nullptr);
6848 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006849 StackHandleScope<1u> hs(self);
6850 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6851 method_array =
6852 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006853 } else {
6854 method_array = AllocPointerArray(self, num_methods);
6855 }
6856 if (UNLIKELY(method_array == nullptr)) {
6857 self->AssertPendingOOMException();
6858 return false;
6859 }
6860 iftable->SetMethodArray(i, method_array);
6861 }
6862 }
6863 return true;
6864}
6865
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006866void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6867 ArtMethod* imt_conflict_method,
6868 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006869 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006870 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006871 // Place method in imt if entry is empty, place conflict otherwise.
6872 if (*imt_ref == unimplemented_method) {
6873 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006874 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006875 // If we are not a conflict and we have the same signature and name as the imt
6876 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006877 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6878 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006879 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006880 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006881 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006882 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006883 *imt_ref = current_method;
6884 } else {
Alex Light9139e002015-10-09 15:59:48 -07006885 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006886 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006887 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006888 } else {
6889 // Place the default conflict method. Note that there may be an existing conflict
6890 // method in the IMT, but it could be one tailored to the super class, with a
6891 // specific ImtConflictTable.
6892 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006893 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006894 }
6895}
6896
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006897void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006898 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6899 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006900 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006901 Runtime* const runtime = Runtime::Current();
6902 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6903 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006904 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006905 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006906 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006907 FillIMTFromIfTable(klass->GetIfTable(),
6908 unimplemented_method,
6909 conflict_method,
6910 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006911 /*create_conflict_tables=*/true,
6912 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006913 &new_conflict,
6914 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006915 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006916 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6917 // we can just use the same pointer.
6918 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006919 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006920 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6921 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6922 bool same = true;
6923 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6924 ArtMethod* method = imt_data[i];
6925 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6926 if (method != super_method) {
6927 bool is_conflict_table = method->IsRuntimeMethod() &&
6928 method != unimplemented_method &&
6929 method != conflict_method;
6930 // Verify conflict contents.
6931 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6932 super_method != unimplemented_method &&
6933 super_method != conflict_method;
6934 if (!is_conflict_table || !super_conflict_table) {
6935 same = false;
6936 } else {
6937 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6938 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6939 same = same && table1->Equals(table2, image_pointer_size_);
6940 }
6941 }
6942 }
6943 if (same) {
6944 imt = super_imt;
6945 }
6946 }
6947 if (imt == nullptr) {
6948 imt = klass->GetImt(image_pointer_size_);
6949 DCHECK(imt != nullptr);
6950 imt->Populate(imt_data, image_pointer_size_);
6951 } else {
6952 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006953 }
6954}
6955
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006956ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6957 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006958 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006959 void* data = linear_alloc->Alloc(Thread::Current(),
6960 ImtConflictTable::ComputeSize(count,
6961 image_pointer_size));
6962 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6963}
6964
6965ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6966 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6967}
6968
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006969void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006970 ArtMethod* unimplemented_method,
6971 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006972 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006973 bool create_conflict_tables,
6974 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006975 /*out*/bool* new_conflict,
6976 /*out*/ArtMethod** imt) {
6977 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006978 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006979 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006980 const size_t num_virtuals = interface->NumVirtualMethods();
6981 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6982 // Virtual methods can be larger than the if table methods if there are default methods.
6983 DCHECK_GE(num_virtuals, method_array_count);
6984 if (kIsDebugBuild) {
6985 if (klass->IsInterface()) {
6986 DCHECK_EQ(method_array_count, 0u);
6987 } else {
6988 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6989 }
6990 }
6991 if (method_array_count == 0) {
6992 continue;
6993 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006994 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006995 for (size_t j = 0; j < method_array_count; ++j) {
6996 ArtMethod* implementation_method =
6997 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6998 if (ignore_copied_methods && implementation_method->IsCopied()) {
6999 continue;
7000 }
7001 DCHECK(implementation_method != nullptr);
7002 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7003 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7004 // or interface methods in the IMT here they will not create extra conflicts since we compare
7005 // names and signatures in SetIMTRef.
7006 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007007 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007008
7009 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7010 // the same implementation method, keep track of this to avoid creating a conflict table in
7011 // this case.
7012
7013 // Conflict table size for each IMT slot.
7014 ++conflict_counts[imt_index];
7015
7016 SetIMTRef(unimplemented_method,
7017 imt_conflict_method,
7018 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007019 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007020 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007021 }
7022 }
7023
7024 if (create_conflict_tables) {
7025 // Create the conflict tables.
7026 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007027 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007028 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007029 if (imt[i] == imt_conflict_method) {
7030 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7031 if (new_table != nullptr) {
7032 ArtMethod* new_conflict_method =
7033 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7034 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7035 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007036 } else {
7037 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007038 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007039 }
7040 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007041 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007042 }
7043 }
7044
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007045 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007046 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007047 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7048 // Virtual methods can be larger than the if table methods if there are default methods.
7049 if (method_array_count == 0) {
7050 continue;
7051 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007052 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007053 for (size_t j = 0; j < method_array_count; ++j) {
7054 ArtMethod* implementation_method =
7055 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7056 if (ignore_copied_methods && implementation_method->IsCopied()) {
7057 continue;
7058 }
7059 DCHECK(implementation_method != nullptr);
7060 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007061 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007062 if (!imt[imt_index]->IsRuntimeMethod() ||
7063 imt[imt_index] == unimplemented_method ||
7064 imt[imt_index] == imt_conflict_method) {
7065 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007066 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007067 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7068 const size_t num_entries = table->NumEntries(image_pointer_size_);
7069 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7070 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007071 }
7072 }
7073 }
7074}
7075
Alex Lighteb7c1442015-08-31 13:17:42 -07007076// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7077// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007078static bool NotSubinterfaceOfAny(
Vladimir Marko782fb712020-12-23 12:47:31 +00007079 const HashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007080 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007081 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007082 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007083 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007084 for (ObjPtr<mirror::Class> c : classes) {
7085 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007086 return false;
7087 }
7088 }
7089 return true;
7090}
7091
7092// Fills in and flattens the interface inheritance hierarchy.
7093//
7094// By the end of this function all interfaces in the transitive closure of to_process are added to
7095// the iftable and every interface precedes all of its sub-interfaces in this list.
7096//
7097// all I, J: Interface | I <: J implies J precedes I
7098//
7099// (note A <: B means that A is a subtype of B)
7100//
7101// This returns the total number of items in the iftable. The iftable might be resized down after
7102// this call.
7103//
7104// We order this backwards so that we do not need to reorder superclass interfaces when new
7105// interfaces are added in subclass's interface tables.
7106//
7107// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7108// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7109// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7110// iftable must be large enough to hold all interfaces without changing its size.
Vladimir Marko782fb712020-12-23 12:47:31 +00007111static size_t FillIfTable(Thread* self,
7112 ObjPtr<mirror::Class> klass,
7113 ObjPtr<mirror::ObjectArray<mirror::Class>> interfaces,
7114 ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007115 size_t super_ifcount,
Vladimir Marko782fb712020-12-23 12:47:31 +00007116 size_t num_interfaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007117 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00007118 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
7119 // This is the set of all classes already in the iftable. Used to make checking
7120 // if a class has already been added quicker.
7121 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
7122 mirror::Class* buffer[kBufferSize];
7123 HashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07007124 // The first super_ifcount elements are from the superclass. We note that they are already added.
7125 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007126 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007127 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007128 classes_in_iftable.insert(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007129 }
7130 size_t filled_ifcount = super_ifcount;
Vladimir Marko782fb712020-12-23 12:47:31 +00007131 const bool have_interfaces = interfaces != nullptr;
7132 for (size_t i = 0; i != num_interfaces; ++i) {
7133 ObjPtr<mirror::Class> interface = have_interfaces
7134 ? interfaces->Get(i)
7135 : mirror::Class::GetDirectInterface(self, klass, i);
7136
Alex Lighteb7c1442015-08-31 13:17:42 -07007137 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7138 // At this point in the loop current-iface-list has the invariant that:
7139 // for every pair of interfaces I,J within it:
7140 // if index_of(I) < index_of(J) then I is not a subtype of J
7141
7142 // If we have already seen this element then all of its super-interfaces must already be in the
7143 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00007144 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007145 // We haven't seen this interface so add all of its super-interfaces onto the
7146 // current-iface-list, skipping those already on it.
7147 int32_t ifcount = interface->GetIfTableCount();
7148 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007149 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007150 if (!ContainsElement(classes_in_iftable, super_interface)) {
7151 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007152 classes_in_iftable.insert(super_interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007153 iftable->SetInterface(filled_ifcount, super_interface);
7154 filled_ifcount++;
7155 }
7156 }
7157 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7158 // Place this interface onto the current-iface-list after all of its super-interfaces.
Vladimir Marko782fb712020-12-23 12:47:31 +00007159 classes_in_iftable.insert(interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007160 iftable->SetInterface(filled_ifcount, interface);
7161 filled_ifcount++;
7162 } else if (kIsDebugBuild) {
7163 // Check all super-interfaces are already in the list.
7164 int32_t ifcount = interface->GetIfTableCount();
7165 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007166 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007167 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007168 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7169 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007170 }
7171 }
7172 }
7173 if (kIsDebugBuild) {
7174 // Check that the iftable is ordered correctly.
7175 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007176 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007177 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007178 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007179 // !(if_a <: if_b)
7180 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007181 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7182 << ") extends "
7183 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007184 << "interface list.";
7185 }
7186 }
7187 }
7188 return filled_ifcount;
7189}
7190
Vladimir Marko782fb712020-12-23 12:47:31 +00007191bool ClassLinker::SetupInterfaceLookupTable(Thread* self,
7192 Handle<mirror::Class> klass,
Alex Lighteb7c1442015-08-31 13:17:42 -07007193 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7194 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007195 const bool has_superclass = klass->HasSuperClass();
7196 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007197 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007198 const size_t num_interfaces =
7199 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007200 if (num_interfaces == 0) {
7201 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007202 if (LIKELY(has_superclass)) {
7203 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7204 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007205 // Class implements no interfaces.
7206 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007207 return true;
7208 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007209 // Class implements same interfaces as parent, are any of these not marker interfaces?
7210 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007211 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007212 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007213 if (super_iftable->GetMethodArrayCount(i) > 0) {
7214 has_non_marker_interface = true;
7215 break;
7216 }
7217 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007218 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007219 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007220 klass->SetIfTable(super_iftable);
7221 return true;
7222 }
7223 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007224 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007225 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007226 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007227 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007228 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007229 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007230 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007231 if (UNLIKELY(!interface->IsInterface())) {
7232 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007233 ThrowIncompatibleClassChangeError(klass.Get(),
7234 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007235 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007236 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7237 return false;
7238 }
7239 ifcount += interface->GetIfTableCount();
7240 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007241 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007242 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007243 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007244 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007245 return false;
7246 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007247 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007248 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007249 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007250 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007251 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007252 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007253 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007254 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007255
7256 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7257 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7258 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007259 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007260
Vladimir Marko782fb712020-12-23 12:47:31 +00007261 const size_t new_ifcount = FillIfTable(
7262 self, klass.Get(), interfaces.Get(), iftable.Get(), super_ifcount, num_interfaces);
Alex Lighteb7c1442015-08-31 13:17:42 -07007263
Ian Rogers7b078e82014-09-10 14:44:24 -07007264 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007265
Ian Rogersb52b01a2012-01-12 17:01:38 -08007266 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007267 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007268 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007269 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007270 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007271 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007272 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007273 return false;
7274 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007275 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007276 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007277 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007278 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007279 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007280 return true;
7281}
7282
Alex Light1f3925d2016-09-07 12:04:20 -07007283// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7284// of methods must be unique.
7285static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7286 return nullptr;
7287}
7288
7289template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007290static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007291 const ScopedArenaVector<ArtMethod*>& list,
7292 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007293 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007294 for (ArtMethod* method : list) {
7295 if (cmp.HasSameNameAndSignature(method)) {
7296 return method;
7297 }
7298 }
Alex Light1f3925d2016-09-07 12:04:20 -07007299 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007300}
7301
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007302namespace {
7303
Alex Light1f3925d2016-09-07 12:04:20 -07007304// Check that all vtable entries are present in this class's virtuals or are the same as a
7305// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007306void CheckClassOwnsVTableEntries(Thread* self,
7307 Handle<mirror::Class> klass,
7308 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007309 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007310 StackHandleScope<2> hs(self);
7311 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007312 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007313 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007314 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007315 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7316 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7317 CHECK(m != nullptr);
7318
Alex Lighta41a30782017-03-29 11:33:19 -07007319 if (m->GetMethodIndexDuringLinking() != i) {
7320 LOG(WARNING) << m->PrettyMethod()
7321 << " has an unexpected method index for its spot in the vtable for class"
7322 << klass->PrettyClass();
7323 }
Alex Lighte64300b2015-12-15 15:02:47 -08007324 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7325 auto is_same_method = [m] (const ArtMethod& meth) {
7326 return &meth == m;
7327 };
Alex Light3f980532017-03-17 15:10:32 -07007328 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7329 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7330 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7331 << klass->PrettyClass() << " or any of its superclasses!";
7332 }
Alex Lighte64300b2015-12-15 15:02:47 -08007333 }
7334}
7335
Alex Light1f3925d2016-09-07 12:04:20 -07007336// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7337// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007338template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007339void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007340 REQUIRES_SHARED(Locks::mutator_lock_) {
7341 StackHandleScope<1> hs(self);
7342 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7343 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007344
7345 // Observations:
7346 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7347 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7348 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7349 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7350 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7351 // * The single-pass algorithm will trade memory for speed, but that is OK.
7352
7353 CHECK_GT(num_entries, 0);
7354
7355 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7356 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7357 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7358 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7359 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7360 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7361 << m2->PrettyMethod() << " (0x" << std::hex
7362 << reinterpret_cast<uintptr_t>(m2) << ")";
7363 };
7364 struct BaseHashType {
7365 static size_t HashCombine(size_t seed, size_t val) {
7366 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7367 }
7368 };
7369
7370 // Check assuming all entries come from the same dex file.
7371 {
7372 // Find the first interesting method and its dex file.
7373 int32_t start = 0;
7374 for (; start < num_entries; ++start) {
7375 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7376 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7377 // maybe).
7378 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7379 vtable_entry->GetAccessFlags())) {
7380 continue;
7381 }
7382 break;
7383 }
7384 if (start == num_entries) {
7385 return;
7386 }
7387 const DexFile* dex_file =
7388 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7389 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7390
7391 // Helper function to avoid logging if we have to run the cross-file checks.
7392 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7393 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7394 using PairType = std::pair<uint32_t, uint16_t>;
7395 struct PairHash : BaseHashType {
7396 size_t operator()(const PairType& key) const {
7397 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7398 }
7399 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007400 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007401 seen.reserve(2 * num_entries);
7402 bool need_slow_path = false;
7403 bool found_dup = false;
7404 for (int i = start; i < num_entries; ++i) {
7405 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7406 // wrt/ kPointerSize.
7407 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7408 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7409 vtable_entry->GetAccessFlags())) {
7410 continue;
7411 }
7412 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7413 if (dex_file != m->GetDexFile()) {
7414 need_slow_path = true;
7415 break;
7416 }
7417 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7418 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7419 auto it = seen.find(pair);
7420 if (it != seen.end()) {
7421 found_dup = true;
7422 if (log_warn) {
7423 log_fn(it->second, i);
7424 }
7425 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007426 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007427 }
7428 }
7429 return std::make_pair(need_slow_path, found_dup);
7430 };
7431 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7432 if (!result.first) {
7433 if (result.second) {
7434 check_fn(/* log_warn= */ true);
7435 }
7436 return;
7437 }
7438 }
7439
7440 // Need to check across dex files.
7441 struct Entry {
7442 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00007443 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007444 const char* name = nullptr;
7445 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007446
Vladimir Marko782fb712020-12-23 12:47:31 +00007447 Entry() = default;
7448 Entry(const Entry& other) = default;
7449 Entry& operator=(const Entry& other) = default;
7450
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007451 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00007452 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
7453 // This call writes `name_len` and it is therefore necessary that the
7454 // initializer for `name_len` comes before it, otherwise the value
7455 // from the call would be overwritten by that initializer.
7456 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007457 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00007458 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
7459 if (name[name_len] != 0) {
7460 name_len += strlen(name + name_len);
7461 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007462 }
7463
7464 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00007465 return name_len == other.name_len &&
7466 memcmp(name, other.name, name_len) == 0 &&
7467 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007468 }
7469 };
7470 struct EntryHash {
7471 size_t operator()(const Entry& key) const {
7472 return key.cached_hash;
7473 }
7474 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007475 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007476 for (int32_t i = 0; i < num_entries; ++i) {
7477 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7478 // wrt/ kPointerSize.
7479 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7480 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7481 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007482 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7483 vtable_entry->GetAccessFlags())) {
7484 continue;
7485 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007486 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7487 const DexFile* dex_file = m->GetDexFile();
7488 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7489
7490 Entry e(dex_file, mid);
7491
7492 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7493 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7494 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7495 sig_hash);
7496
7497 auto it = map.find(e);
7498 if (it != map.end()) {
7499 log_fn(it->second, i);
7500 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007501 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07007502 }
7503 }
7504}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007505
7506void CheckVTableHasNoDuplicates(Thread* self,
7507 Handle<mirror::Class> klass,
7508 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007509 REQUIRES_SHARED(Locks::mutator_lock_) {
7510 switch (pointer_size) {
7511 case PointerSize::k64:
7512 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7513 break;
7514 case PointerSize::k32:
7515 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7516 break;
7517 }
7518}
Alex Light1f3925d2016-09-07 12:04:20 -07007519
Orion Hodson5880c772020-07-28 20:12:08 +01007520static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07007521 REQUIRES_SHARED(Locks::mutator_lock_) {
7522 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7523 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7524}
7525
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007526} // namespace
7527
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007528void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7529 ArtMethod* unimplemented_method,
7530 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007531 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007532 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007533 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007534 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007535 if (super_class->ShouldHaveImt()) {
7536 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7537 for (size_t i = 0; i < ImTable::kSize; ++i) {
7538 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007539 }
7540 } else {
7541 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007542 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007543 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007544 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007545 FillIMTFromIfTable(if_table,
7546 unimplemented_method,
7547 imt_conflict_method,
7548 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007549 /*create_conflict_tables=*/false,
7550 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007551 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007552 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007553 }
7554 }
7555}
7556
Vladimir Marko921094a2017-01-12 18:37:06 +00007557class ClassLinker::LinkInterfaceMethodsHelper {
7558 public:
7559 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7560 Handle<mirror::Class> klass,
7561 Thread* self,
7562 Runtime* runtime)
7563 : class_linker_(class_linker),
7564 klass_(klass),
7565 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7566 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7567 self_(self),
7568 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7569 allocator_(&stack_),
7570 default_conflict_methods_(allocator_.Adapter()),
7571 overriding_default_conflict_methods_(allocator_.Adapter()),
7572 miranda_methods_(allocator_.Adapter()),
7573 default_methods_(allocator_.Adapter()),
7574 overriding_default_methods_(allocator_.Adapter()),
7575 move_table_(allocator_.Adapter()) {
7576 }
7577
7578 ArtMethod* FindMethod(ArtMethod* interface_method,
7579 MethodNameAndSignatureComparator& interface_name_comparator,
7580 ArtMethod* vtable_impl)
7581 REQUIRES_SHARED(Locks::mutator_lock_);
7582
7583 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7584 MethodNameAndSignatureComparator& interface_name_comparator)
7585 REQUIRES_SHARED(Locks::mutator_lock_);
7586
7587 bool HasNewVirtuals() const {
7588 return !(miranda_methods_.empty() &&
7589 default_methods_.empty() &&
7590 overriding_default_methods_.empty() &&
7591 overriding_default_conflict_methods_.empty() &&
7592 default_conflict_methods_.empty());
7593 }
7594
7595 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7596
7597 ObjPtr<mirror::PointerArray> UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007598 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007599 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007600
7601 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7602
7603 void UpdateIMT(ArtMethod** out_imt);
7604
7605 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7606 if (kIsDebugBuild) {
7607 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7608 // Check that there are no stale methods are in the dex cache array.
7609 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7610 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007611 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7612 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007613 CHECK(move_table_.find(m) == move_table_.end() ||
7614 // The original versions of copied methods will still be present so allow those too.
7615 // Note that if the first check passes this might fail to GetDeclaringClass().
7616 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7617 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7618 [m] (ArtMethod& meth) {
7619 return &meth == m;
7620 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7621 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7622 }
7623 }
7624 }
7625
7626 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7627 LengthPrefixedArray<ArtMethod>* methods) {
7628 if (kIsDebugBuild) {
7629 CHECK(methods != nullptr);
7630 // Put some random garbage in old methods to help find stale pointers.
7631 if (methods != old_methods && old_methods != nullptr) {
7632 // Need to make sure the GC is not running since it could be scanning the methods we are
7633 // about to overwrite.
7634 ScopedThreadStateChange tsc(self_, kSuspended);
7635 gc::ScopedGCCriticalSection gcs(self_,
7636 gc::kGcCauseClassLinker,
7637 gc::kCollectorTypeClassLinker);
7638 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7639 method_size_,
7640 method_alignment_);
7641 memset(old_methods, 0xFEu, old_size);
7642 }
7643 }
7644 }
7645
7646 private:
7647 size_t NumberOfNewVirtuals() const {
7648 return miranda_methods_.size() +
7649 default_methods_.size() +
7650 overriding_default_conflict_methods_.size() +
7651 overriding_default_methods_.size() +
7652 default_conflict_methods_.size();
7653 }
7654
7655 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7656 return !klass_->IsInterface();
7657 }
7658
7659 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7660 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7661 << "Interfaces should only have default-conflict methods appended to them.";
7662 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7663 << miranda_methods_.size()
7664 << " default_methods=" << default_methods_.size()
7665 << " overriding_default_methods=" << overriding_default_methods_.size()
7666 << " default_conflict_methods=" << default_conflict_methods_.size()
7667 << " overriding_default_conflict_methods="
7668 << overriding_default_conflict_methods_.size();
7669 }
7670
7671 ClassLinker* class_linker_;
7672 Handle<mirror::Class> klass_;
7673 size_t method_alignment_;
7674 size_t method_size_;
7675 Thread* const self_;
7676
7677 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7678 // the virtual methods array.
7679 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7680 // during cross compilation.
7681 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7682 ArenaStack stack_;
7683 ScopedArenaAllocator allocator_;
7684
7685 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7686 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7687 ScopedArenaVector<ArtMethod*> miranda_methods_;
7688 ScopedArenaVector<ArtMethod*> default_methods_;
7689 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7690
7691 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7692};
7693
7694ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7695 ArtMethod* interface_method,
7696 MethodNameAndSignatureComparator& interface_name_comparator,
7697 ArtMethod* vtable_impl) {
7698 ArtMethod* current_method = nullptr;
7699 switch (class_linker_->FindDefaultMethodImplementation(self_,
7700 interface_method,
7701 klass_,
7702 /*out*/&current_method)) {
7703 case DefaultMethodSearchResult::kDefaultConflict: {
7704 // Default method conflict.
7705 DCHECK(current_method == nullptr);
7706 ArtMethod* default_conflict_method = nullptr;
7707 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7708 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7709 default_conflict_method = vtable_impl;
7710 } else {
7711 // See if we already have a conflict method for this method.
7712 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7713 interface_name_comparator,
7714 default_conflict_methods_,
7715 overriding_default_conflict_methods_);
7716 if (LIKELY(preexisting_conflict != nullptr)) {
7717 // We already have another conflict we can reuse.
7718 default_conflict_method = preexisting_conflict;
7719 } else {
7720 // Note that we do this even if we are an interface since we need to create this and
7721 // cannot reuse another classes.
7722 // Create a new conflict method for this to use.
7723 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7724 new(default_conflict_method) ArtMethod(interface_method,
7725 class_linker_->GetImagePointerSize());
7726 if (vtable_impl == nullptr) {
7727 // Save the conflict method. We need to add it to the vtable.
7728 default_conflict_methods_.push_back(default_conflict_method);
7729 } else {
7730 // Save the conflict method but it is already in the vtable.
7731 overriding_default_conflict_methods_.push_back(default_conflict_method);
7732 }
7733 }
7734 }
7735 current_method = default_conflict_method;
7736 break;
7737 } // case kDefaultConflict
7738 case DefaultMethodSearchResult::kDefaultFound: {
7739 DCHECK(current_method != nullptr);
7740 // Found a default method.
7741 if (vtable_impl != nullptr &&
7742 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7743 // We found a default method but it was the same one we already have from our
7744 // superclass. Don't bother adding it to our vtable again.
7745 current_method = vtable_impl;
7746 } else if (LIKELY(FillTables())) {
7747 // Interfaces don't need to copy default methods since they don't have vtables.
7748 // Only record this default method if it is new to save space.
7749 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7750 // would make lookup for interface super much faster. (We would only need to scan
7751 // the iftable to find if there is a NSME or AME.)
7752 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7753 default_methods_,
7754 overriding_default_methods_);
7755 if (old == nullptr) {
7756 // We found a default method implementation and there were no conflicts.
7757 if (vtable_impl == nullptr) {
7758 // Save the default method. We need to add it to the vtable.
7759 default_methods_.push_back(current_method);
7760 } else {
7761 // Save the default method but it is already in the vtable.
7762 overriding_default_methods_.push_back(current_method);
7763 }
7764 } else {
7765 CHECK(old == current_method) << "Multiple default implementations selected!";
7766 }
7767 }
7768 break;
7769 } // case kDefaultFound
7770 case DefaultMethodSearchResult::kAbstractFound: {
7771 DCHECK(current_method == nullptr);
7772 // Abstract method masks all defaults.
7773 if (vtable_impl != nullptr &&
7774 vtable_impl->IsAbstract() &&
7775 !vtable_impl->IsDefaultConflicting()) {
7776 // We need to make this an abstract method but the version in the vtable already is so
7777 // don't do anything.
7778 current_method = vtable_impl;
7779 }
7780 break;
7781 } // case kAbstractFound
7782 }
7783 return current_method;
7784}
7785
7786ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7787 ArtMethod* interface_method,
7788 MethodNameAndSignatureComparator& interface_name_comparator) {
7789 // Find out if there is already a miranda method we can use.
7790 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7791 miranda_methods_);
7792 if (miranda_method == nullptr) {
7793 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7794 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7795 CHECK(miranda_method != nullptr);
7796 // Point the interface table at a phantom slot.
7797 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7798 miranda_methods_.push_back(miranda_method);
7799 }
7800 return miranda_method;
7801}
7802
7803void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7804 LogNewVirtuals();
7805
7806 const size_t old_method_count = klass_->NumMethods();
7807 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7808 DCHECK_NE(old_method_count, new_method_count);
7809
7810 // Attempt to realloc to save RAM if possible.
7811 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7812 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7813 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7814 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7815 // CopyFrom has internal read barriers.
7816 //
7817 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7818 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7819 method_size_,
7820 method_alignment_);
7821 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7822 method_size_,
7823 method_alignment_);
7824 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7825 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007826 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007827 self_, old_methods, old_methods_ptr_size, new_size));
7828 CHECK(methods != nullptr); // Native allocation failure aborts.
7829
7830 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7831 if (methods != old_methods) {
7832 // Maps from heap allocated miranda method to linear alloc miranda method.
7833 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7834 // Copy over the old methods.
7835 for (auto& m : klass_->GetMethods(pointer_size)) {
7836 move_table_.emplace(&m, &*out);
7837 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7838 // barriers when it copies.
7839 out->CopyFrom(&m, pointer_size);
7840 ++out;
7841 }
7842 }
7843 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7844 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7845 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007846 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7847 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007848 ArtMethod& new_method = *out;
7849 new_method.CopyFrom(mir_method, pointer_size);
7850 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7851 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7852 << "Miranda method should be abstract!";
7853 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007854 // Update the entry in the method array, as the array will be used for future lookups,
7855 // where thread suspension is allowed.
7856 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7857 // would not see them.
7858 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007859 ++out;
7860 }
7861 // We need to copy the default methods into our own method table since the runtime requires that
7862 // every method on a class's vtable be in that respective class's virtual method table.
7863 // NOTE This means that two classes might have the same implementation of a method from the same
7864 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7865 // default method found on a class with one found on the declaring interface directly and must
7866 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007867 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7868 &overriding_default_methods_}) {
7869 for (size_t i = 0; i < methods_vec->size(); ++i) {
7870 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007871 ArtMethod& new_method = *out;
7872 new_method.CopyFrom(def_method, pointer_size);
7873 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7874 // verified yet it shouldn't have methods that are skipping access checks.
7875 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7876 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007877 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007878 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7879 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7880 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7881 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007882 // Update the entry in the method array, as the array will be used for future lookups,
7883 // where thread suspension is allowed.
7884 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7885 // would not see them.
7886 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007887 ++out;
7888 }
7889 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007890 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7891 &overriding_default_conflict_methods_}) {
7892 for (size_t i = 0; i < methods_vec->size(); ++i) {
7893 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007894 ArtMethod& new_method = *out;
7895 new_method.CopyFrom(conf_method, pointer_size);
7896 // This is a type of default method (there are default method impls, just a conflict) so
7897 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7898 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7899 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007900 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7901 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007902 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007903 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007904 constexpr uint32_t kMaskFlags =
7905 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007906 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7907 DCHECK(new_method.IsDefaultConflicting());
7908 // The actual method might or might not be marked abstract since we just copied it from a
7909 // (possibly default) interface method. We need to set it entry point to be the bridge so
7910 // that the compiler will not invoke the implementation of whatever method we copied from.
7911 EnsureThrowsInvocationError(class_linker_, &new_method);
7912 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007913 // Update the entry in the method array, as the array will be used for future lookups,
7914 // where thread suspension is allowed.
7915 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7916 // would not see them.
7917 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007918 ++out;
7919 }
7920 }
7921 methods->SetSize(new_method_count);
7922 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7923}
7924
7925ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007926 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007927 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007928 // Update the vtable to the new method structures. We can skip this for interfaces since they
7929 // do not have vtables.
7930 const size_t old_vtable_count = old_vtable->GetLength();
7931 const size_t new_vtable_count = old_vtable_count +
7932 miranda_methods_.size() +
7933 default_methods_.size() +
7934 default_conflict_methods_.size();
7935
Vladimir Marko3068d582019-05-28 16:39:29 +01007936 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
7937 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007938 if (UNLIKELY(vtable == nullptr)) {
7939 self_->AssertPendingOOMException();
7940 return nullptr;
7941 }
7942
7943 size_t vtable_pos = old_vtable_count;
7944 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7945 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7946 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7947 default_conflict_methods_,
7948 miranda_methods_}) {
7949 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007950 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007951 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7952 // fields are references into the dex file the method was defined in. Since the ArtMethod
7953 // does not store that information it uses declaring_class_->dex_cache_.
7954 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7955 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7956 ++vtable_pos;
7957 }
7958 }
7959 DCHECK_EQ(vtable_pos, new_vtable_count);
7960
7961 // Update old vtable methods. We use the default_translations map to figure out what each
7962 // vtable entry should be updated to, if they need to be at all.
7963 for (size_t i = 0; i < old_vtable_count; ++i) {
7964 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7965 // Try and find what we need to change this method to.
7966 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007967 if (translation_it != default_translations.end()) {
7968 if (translation_it->second.IsInConflict()) {
7969 // Find which conflict method we are to use for this method.
7970 MethodNameAndSignatureComparator old_method_comparator(
7971 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7972 // We only need to look through overriding_default_conflict_methods since this is an
7973 // overridden method we are fixing up here.
7974 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7975 old_method_comparator, overriding_default_conflict_methods_);
7976 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7977 translated_method = new_conflict_method;
7978 } else if (translation_it->second.IsAbstract()) {
7979 // Find which miranda method we are to use for this method.
7980 MethodNameAndSignatureComparator old_method_comparator(
7981 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7982 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7983 miranda_methods_);
7984 DCHECK(miranda_method != nullptr);
7985 translated_method = miranda_method;
7986 } else {
7987 // Normal default method (changed from an older default or abstract interface method).
7988 DCHECK(translation_it->second.IsTranslation());
7989 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007990 auto it = move_table_.find(translated_method);
7991 DCHECK(it != move_table_.end());
7992 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007993 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007994 } else {
7995 auto it = move_table_.find(translated_method);
7996 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007997 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007998
7999 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008000 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008001 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008002 if (kIsDebugBuild) {
8003 auto* methods = klass_->GetMethodsPtr();
8004 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008005 reinterpret_cast<uintptr_t>(translated_method));
8006 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008007 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8008 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008009 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008010 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008011 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008012 }
8013 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008014 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008015 return vtable;
8016}
8017
8018void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8019 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8020 const size_t ifcount = klass_->GetIfTableCount();
8021 // Go fix up all the stale iftable pointers.
8022 for (size_t i = 0; i < ifcount; ++i) {
8023 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008024 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8025 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008026 DCHECK(m != nullptr) << klass_->PrettyClass();
8027 auto it = move_table_.find(m);
8028 if (it != move_table_.end()) {
8029 auto* new_m = it->second;
8030 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8031 method_array->SetElementPtrSize(j, new_m, pointer_size);
8032 }
8033 }
8034 }
8035}
8036
8037void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8038 // Fix up IMT next.
8039 for (size_t i = 0; i < ImTable::kSize; ++i) {
8040 auto it = move_table_.find(out_imt[i]);
8041 if (it != move_table_.end()) {
8042 out_imt[i] = it->second;
8043 }
8044 }
8045}
8046
Alex Light705ad492015-09-21 11:36:30 -07008047// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008048bool ClassLinker::LinkInterfaceMethods(
8049 Thread* self,
8050 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00008051 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008052 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008053 ArtMethod** out_imt) {
8054 StackHandleScope<3> hs(self);
8055 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008056
8057 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008058 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008059 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008060 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008061 const size_t ifcount = klass->GetIfTableCount();
8062
Vladimir Marko921094a2017-01-12 18:37:06 +00008063 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008064
8065 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8066 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008067 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008068 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008069 const bool extend_super_iftable = has_superclass;
8070 if (has_superclass && fill_tables) {
8071 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008072 unimplemented_method,
8073 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008074 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008075 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008076 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008077 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8078 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008079 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008080 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8081 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008082 }
8083 }
8084
Vladimir Marko921094a2017-01-12 18:37:06 +00008085 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8086
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008087 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008088 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008089 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8090 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8091 // they will already be null. This has the additional benefit that the declarer of a miranda
8092 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008093 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008094 --i;
Alex Light9139e002015-10-09 15:59:48 -07008095 DCHECK_LT(i, ifcount);
8096
Alex Light705ad492015-09-21 11:36:30 -07008097 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008098 if (num_methods > 0) {
8099 StackHandleScope<2> hs2(self);
8100 const bool is_super = i < super_ifcount;
8101 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008102 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8103 // conflict methods. Just set this as nullptr in those cases.
8104 Handle<mirror::PointerArray> method_array(fill_tables
8105 ? hs2.NewHandle(iftable->GetMethodArray(i))
8106 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008107
Alex Lighte64300b2015-12-15 15:02:47 -08008108 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008109 ScopedNullHandle<mirror::PointerArray> null_handle;
8110 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008111 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008112
Alex Light9139e002015-10-09 15:59:48 -07008113 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8114 // and confusing. Default methods should always look through all the superclasses
8115 // because they are the last choice of an implementation. We get around this by looking
8116 // at the super-classes iftable methods (copied into method_array previously) when we are
8117 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008118 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008119 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008120 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008121 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008122 using_virtuals = true;
Alex Lighta467a6e2020-03-23 16:07:29 -07008123 input_virtual_methods = klass->GetDeclaredVirtualMethodsSlice(image_pointer_size_);
Alex Lighte64300b2015-12-15 15:02:47 -08008124 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008125 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008126 // For a new interface, however, we need the whole vtable in case a new
8127 // interface method is implemented in the whole superclass.
8128 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008129 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008130 input_vtable_array = vtable;
8131 input_array_length = input_vtable_array->GetLength();
8132 }
Alex Lighte64300b2015-12-15 15:02:47 -08008133
Alex Lighteb7c1442015-08-31 13:17:42 -07008134 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008135 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008136 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008137 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008138 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008139 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008140 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008141 // For each method listed in the interface's method list, find the
8142 // matching method in our class's method list. We want to favor the
8143 // subclass over the superclass, which just requires walking
8144 // back from the end of the vtable. (This only matters if the
8145 // superclass defines a private method and this class redefines
8146 // it -- otherwise it would use the same vtable slot. In .dex files
8147 // those don't end up in the virtual method table, so it shouldn't
8148 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008149 //
8150 // To find defaults we need to do the same but also go over interfaces.
8151 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008152 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008153 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008154 ArtMethod* vtable_method = using_virtuals ?
8155 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008156 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8157 ArtMethod* vtable_method_for_name_comparison =
8158 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Alex Lighta467a6e2020-03-23 16:07:29 -07008159 DCHECK(!vtable_method->IsStatic()) << vtable_method->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008160 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008161 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008162 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008163 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8164 // allocations.
8165 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008166 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008167 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008168 vtable_method->PrettyMethod().c_str(),
8169 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008170 return false;
Alex Light9139e002015-10-09 15:59:48 -07008171 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008172 // We might have a newer, better, default method for this, so we just skip it. If we
8173 // are still using this we will select it again when scanning for default methods. To
8174 // obviate the need to copy the method again we will make a note that we already found
8175 // a default here.
8176 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008177 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008178 break;
8179 } else {
8180 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008181 if (LIKELY(fill_tables)) {
8182 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8183 // Place method in imt if entry is empty, place conflict otherwise.
8184 SetIMTRef(unimplemented_method,
8185 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008186 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008187 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008188 /*out*/imt_ptr);
8189 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008190 break;
8191 }
8192 }
Alex Light9139e002015-10-09 15:59:48 -07008193 }
8194 // Continue on to the next method if we are done.
8195 if (LIKELY(found_impl)) {
8196 continue;
8197 } else if (LIKELY(super_interface)) {
8198 // Don't look for a default implementation when the super-method is implemented directly
8199 // by the class.
8200 //
8201 // See if we can use the superclasses method and skip searching everything else.
8202 // Note: !found_impl && super_interface
8203 CHECK(extend_super_iftable);
8204 // If this is a super_interface method it is possible we shouldn't override it because a
8205 // superclass could have implemented it directly. We get the method the superclass used
8206 // to implement this to know if we can override it with a default method. Doing this is
8207 // safe since we know that the super_iftable is filled in so we can simply pull it from
8208 // there. We don't bother if this is not a super-classes interface since in that case we
8209 // have scanned the entire vtable anyway and would have found it.
8210 // TODO This is rather dirty but it is faster than searching through the entire vtable
8211 // every time.
8212 ArtMethod* supers_method =
8213 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8214 DCHECK(supers_method != nullptr);
8215 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008216 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008217 // The method is not overridable by a default method (i.e. it is directly implemented
8218 // in some class). Therefore move onto the next interface method.
8219 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008220 } else {
8221 // If the super-classes method is override-able by a default method we need to keep
8222 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8223 // 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 -07008224 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8225 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8226 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008227 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008228 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8229 << " and not 'nullptr' or "
8230 << supers_method->PrettyMethod()
8231 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008232 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008233 }
8234 }
8235 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008236 ArtMethod* current_method = helper.FindMethod(interface_method,
8237 interface_name_comparator,
8238 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008239 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008240 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008241 // We could not find an implementation for this method and since it is a brand new
8242 // interface we searched the entire vtable (and all default methods) for an
8243 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008244 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8245 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008246 }
8247
8248 if (current_method != nullptr) {
8249 // We found a default method implementation. Record it in the iftable and IMT.
8250 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8251 SetIMTRef(unimplemented_method,
8252 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008253 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008254 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008255 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008256 }
8257 }
Alex Light705ad492015-09-21 11:36:30 -07008258 } // For each method in interface end.
8259 } // if (num_methods > 0)
8260 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008261 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008262 if (helper.HasNewVirtuals()) {
8263 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8264 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8265 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8266
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008267 // 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 -07008268 // suspension assert.
8269 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008270
Alex Light705ad492015-09-21 11:36:30 -07008271 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008272 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008273 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008274 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008275 return false;
8276 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008277 helper.UpdateIfTable(iftable);
8278 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008279 }
Alex Light705ad492015-09-21 11:36:30 -07008280
Vladimir Marko921094a2017-01-12 18:37:06 +00008281 helper.CheckNoStaleMethodsInDexCache();
8282 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008283 } else {
8284 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008285 }
Alex Light705ad492015-09-21 11:36:30 -07008286 if (kIsDebugBuild && !is_interface) {
Orion Hodson5880c772020-07-28 20:12:08 +01008287 CheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008288 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008289 return true;
8290}
8291
Vladimir Marko42bee502021-01-28 14:58:35 +00008292class ClassLinker::LinkFieldsHelper {
8293 public:
8294 static bool LinkFields(ClassLinker* class_linker,
8295 Thread* self,
8296 Handle<mirror::Class> klass,
8297 bool is_static,
8298 size_t* class_size)
8299 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008300
Vladimir Marko42bee502021-01-28 14:58:35 +00008301 private:
8302 enum class FieldTypeOrder : uint16_t;
8303 class FieldGaps;
8304
8305 struct FieldTypeOrderAndIndex {
8306 FieldTypeOrder field_type_order;
8307 uint16_t field_index;
8308 };
8309
8310 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8311
8312 template <size_t kSize>
8313 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8314 REQUIRES_SHARED(Locks::mutator_lock_);
8315};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008316
Vladimir Markoc7993d52021-01-27 15:20:56 +00008317// We use the following order of field types for assigning offsets.
8318// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008319enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008320 kReference = 0u,
8321 kLong,
8322 kDouble,
8323 kInt,
8324 kFloat,
8325 kChar,
8326 kShort,
8327 kBoolean,
8328 kByte,
8329
8330 kLast64BitType = kDouble,
8331 kLast32BitType = kFloat,
8332 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008333};
8334
Vladimir Markoc7993d52021-01-27 15:20:56 +00008335ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008336ClassLinker::LinkFieldsHelper::FieldTypeOrder
8337ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008338 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008339 case 'J':
8340 return FieldTypeOrder::kLong;
8341 case 'D':
8342 return FieldTypeOrder::kDouble;
8343 case 'I':
8344 return FieldTypeOrder::kInt;
8345 case 'F':
8346 return FieldTypeOrder::kFloat;
8347 case 'C':
8348 return FieldTypeOrder::kChar;
8349 case 'S':
8350 return FieldTypeOrder::kShort;
8351 case 'Z':
8352 return FieldTypeOrder::kBoolean;
8353 case 'B':
8354 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008355 default:
8356 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8357 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008358 }
8359}
8360
8361// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008362class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008363 public:
8364 template <uint32_t kSize>
8365 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8366 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8367 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8368 uint32_t gap_start = field_offset.Uint32Value();
8369 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8370 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8371 }
8372 return field_offset;
8373 }
8374
8375 template <uint32_t kSize>
8376 bool HasGap() const {
8377 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8378 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8379 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8380 gap4_offset_ != kNoOffset;
8381 }
8382
8383 template <uint32_t kSize>
8384 MemberOffset ReleaseGap() {
8385 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8386 uint32_t result;
8387 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8388 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8389 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8390 result = gap1_offset_;
8391 gap1_offset_ = kNoOffset;
8392 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8393 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8394 result = gap2_offset_;
8395 gap2_offset_ = kNoOffset;
8396 if (kSize < 2u) {
8397 AddGaps<1u>(result + kSize, result + 2u);
8398 }
8399 } else {
8400 DCHECK_NE(gap4_offset_, kNoOffset);
8401 result = gap4_offset_;
8402 gap4_offset_ = kNoOffset;
8403 if (kSize < 4u) {
8404 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8405 }
8406 }
8407 return MemberOffset(result);
8408 }
8409
8410 private:
8411 template <uint32_t kGapsToCheck>
8412 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8413 if ((kGapsToCheck & 1u) != 0u) {
8414 DCHECK_LT(gap_start, gap_end);
8415 DCHECK_ALIGNED(gap_end, 2u);
8416 if ((gap_start & 1u) != 0u) {
8417 DCHECK_EQ(gap1_offset_, kNoOffset);
8418 gap1_offset_ = gap_start;
8419 gap_start += 1u;
8420 if (kGapsToCheck == 1u || gap_start == gap_end) {
8421 DCHECK_EQ(gap_start, gap_end);
8422 return;
8423 }
8424 }
8425 }
8426
8427 if ((kGapsToCheck & 2u) != 0u) {
8428 DCHECK_LT(gap_start, gap_end);
8429 DCHECK_ALIGNED(gap_start, 2u);
8430 DCHECK_ALIGNED(gap_end, 4u);
8431 if ((gap_start & 2u) != 0u) {
8432 DCHECK_EQ(gap2_offset_, kNoOffset);
8433 gap2_offset_ = gap_start;
8434 gap_start += 2u;
8435 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8436 DCHECK_EQ(gap_start, gap_end);
8437 return;
8438 }
8439 }
8440 }
8441
8442 if ((kGapsToCheck & 4u) != 0u) {
8443 DCHECK_LT(gap_start, gap_end);
8444 DCHECK_ALIGNED(gap_start, 4u);
8445 DCHECK_ALIGNED(gap_end, 8u);
8446 DCHECK_EQ(gap_start + 4u, gap_end);
8447 DCHECK_EQ(gap4_offset_, kNoOffset);
8448 gap4_offset_ = gap_start;
8449 return;
8450 }
8451
8452 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8453 << " after checking " << kGapsToCheck;
8454 }
8455
8456 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8457
8458 uint32_t gap4_offset_ = kNoOffset;
8459 uint32_t gap2_offset_ = kNoOffset;
8460 uint32_t gap1_offset_ = kNoOffset;
8461};
8462
8463template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008464ALWAYS_INLINE
8465MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8466 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008467 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8468 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8469 field->SetOffset(field_offset);
8470 return MemberOffset(field_offset.Uint32Value() + kSize);
8471}
8472
Vladimir Marko42bee502021-01-28 14:58:35 +00008473bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8474 Thread* self,
8475 Handle<mirror::Class> klass,
8476 bool is_static,
8477 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008478 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008479 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008480 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8481 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008482
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008483 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008484 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008485 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008486 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8487 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008488 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008489 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008490 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008491 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008492 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008493 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008494 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008495 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008496
David Sehr709b0702016-10-13 09:12:37 -07008497 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008498
Brian Carlstromdbc05252011-09-09 01:59:59 -07008499 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008500 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008501 //
8502 // The overall sort order order is:
8503 // 1) All object reference fields, sorted alphabetically.
8504 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8505 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8506 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8507 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8508 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8509 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8510 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8511 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8512 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008513 // (References are first to increase the chance of reference visiting
8514 // being able to take a fast path using a bitmap of references at the
8515 // start of the object, see `Class::reference_instance_offsets_`.)
8516 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008517 // Once the fields are sorted in this order we will attempt to fill any gaps
8518 // that might be present in the memory layout of the structure.
8519 // Note that we shall not fill gaps between the superclass fields.
8520
8521 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008522 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008523 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008524 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8525 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8526 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8527 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008528 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008529 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008530 } else {
8531 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008532 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008533 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008534 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008535 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008536 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008537 for (size_t i = 0; i != num_fields; ++i) {
8538 ArtField* field = &fields->At(i);
8539 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008540 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8541 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008542 // Insert references to the start, other fields to the end.
8543 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008544 if (field_type_order == FieldTypeOrder::kReference) {
8545 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008546 ++num_reference_fields;
8547 } else {
8548 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008549 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008550 }
8551 }
8552 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008553
Vladimir Marko42bee502021-01-28 14:58:35 +00008554 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008555 DCHECK(std::is_sorted(
8556 sorted_fields.begin(),
8557 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008558 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8559 ArtField* lhs_field = &fields->At(lhs.field_index);
8560 ArtField* rhs_field = &fields->At(rhs.field_index);
8561 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8562 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8563 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8564 lhs.field_index < rhs.field_index);
8565 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008566 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008567 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008568 DCHECK(std::is_sorted(
8569 sorted_fields.begin() + primitive_fields_start,
8570 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008571 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8572 ArtField* lhs_field = &fields->At(lhs.field_index);
8573 ArtField* rhs_field = &fields->At(rhs.field_index);
8574 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8575 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8576 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8577 lhs.field_index > rhs.field_index);
8578 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008579 }));
8580 // Sort the primitive fields by the field type order, then field index.
8581 std::sort(sorted_fields.begin() + primitive_fields_start,
8582 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008583 [](const auto& lhs, const auto& rhs) {
8584 if (lhs.field_type_order != rhs.field_type_order) {
8585 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008586 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008587 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008588 }
8589 });
8590 // Primitive fields are now sorted by field size (descending), then type, then field index.
8591 DCHECK(std::is_sorted(
8592 sorted_fields.begin() + primitive_fields_start,
8593 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008594 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8595 ArtField* lhs_field = &fields->At(lhs.field_index);
8596 ArtField* rhs_field = &fields->At(rhs.field_index);
8597 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008598 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008599 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008600 CHECK_NE(rhs_type, Primitive::kPrimNot);
8601 if (lhs_type != rhs_type) {
8602 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8603 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8604 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8605 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008606 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008607 }
8608 }));
8609
8610 // Process reference fields.
8611 FieldGaps field_gaps;
8612 size_t index = 0u;
8613 if (num_reference_fields != 0u) {
8614 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8615 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8616 for (; index != num_reference_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008617 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008618 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008619 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008620 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008621 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008622 if (index != num_fields &&
8623 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008624 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008625 while (index != num_fields &&
8626 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8627 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008628 field_offset = AssignFieldOffset<8u>(field, field_offset);
8629 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008630 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008631 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008632 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008633 if (index != num_fields &&
8634 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008635 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8636 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008637 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008638 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8639 ++index;
8640 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8641 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008642 while (index != num_fields &&
8643 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8644 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008645 field_offset = AssignFieldOffset<4u>(field, field_offset);
8646 ++index;
8647 }
8648 }
8649 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008650 if (index != num_fields &&
8651 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008652 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8653 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008654 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008655 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008656 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008657 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8658 ++index;
8659 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008660 while (index != num_fields &&
8661 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8662 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008663 field_offset = AssignFieldOffset<2u>(field, field_offset);
8664 ++index;
8665 }
8666 }
8667 // Process 8-bit fields.
8668 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008669 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008670 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8671 }
8672 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008673 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008674 field_offset = AssignFieldOffset<1u>(field, field_offset);
8675 }
8676
Ian Rogers7b078e82014-09-10 14:44:24 -07008677 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008678
Elliott Hughesadb460d2011-10-05 17:02:34 -07008679 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Vladimir Marko42bee502021-01-28 14:58:35 +00008680 DCHECK(!class_linker->init_done_ || !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
8681 if (!is_static &&
8682 UNLIKELY(!class_linker->init_done_) &&
8683 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008684 // We know there are no non-reference fields in the Reference classes, and we know
8685 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008686 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008687 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008688 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008689 --num_reference_fields;
8690 }
8691
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008692 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008693 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008694 if (is_static) {
8695 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008696 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008697 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008698 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008699 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008700 if (num_reference_fields == 0 || super_class == nullptr) {
8701 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008702 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008703 if (super_class == nullptr ||
8704 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8705 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008706 }
8707 }
8708 if (kIsDebugBuild) {
8709 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8710 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008711 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008712 while (cur_super != nullptr) {
8713 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8714 cur_super = cur_super->GetSuperClass();
8715 }
8716 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008717 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008718 } else {
8719 // Check that there is at least num_reference_fields other than Object.class.
8720 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008721 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008722 }
8723 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008724 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008725 std::string temp;
8726 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8727 size_t previous_size = klass->GetObjectSize();
8728 if (previous_size != 0) {
8729 // Make sure that we didn't originally have an incorrect size.
8730 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008731 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008732 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008733 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008734 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008735
8736 if (kIsDebugBuild) {
8737 // Make sure that the fields array is ordered by name but all reference
8738 // offsets are at the beginning as far as alignment allows.
8739 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00008740 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008741 : klass->GetFirstReferenceInstanceFieldOffset();
8742 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8743 num_reference_fields *
8744 sizeof(mirror::HeapReference<mirror::Object>));
8745 MemberOffset current_ref_offset = start_ref_offset;
8746 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008747 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008748 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008749 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8750 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008751 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008752 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008753 // NOTE: The field names can be the same. This is not possible in the Java language
8754 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008755 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008756 }
8757 Primitive::Type type = field->GetTypeAsPrimitiveType();
8758 bool is_primitive = type != Primitive::kPrimNot;
8759 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8760 strcmp("referent", field->GetName()) == 0) {
8761 is_primitive = true; // We lied above, so we have to expect a lie here.
8762 }
8763 MemberOffset offset = field->GetOffsetDuringLinking();
8764 if (is_primitive) {
8765 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8766 // Shuffled before references.
8767 size_t type_size = Primitive::ComponentSize(type);
8768 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8769 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8770 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8771 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8772 }
8773 } else {
8774 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8775 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8776 sizeof(mirror::HeapReference<mirror::Object>));
8777 }
8778 }
8779 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8780 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008781 return true;
8782}
8783
Vladimir Marko42bee502021-01-28 14:58:35 +00008784bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
8785 CHECK(klass != nullptr);
8786 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
8787}
8788
8789bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
8790 CHECK(klass != nullptr);
8791 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
8792}
8793
Vladimir Marko76649e82014-11-10 18:32:59 +00008794// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008795void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008796 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008797 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008798 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008799 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008800 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008801 // Compute reference offsets unless our superclass overflowed.
8802 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8803 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008804 if (num_reference_fields != 0u) {
8805 // All of the fields that contain object references are guaranteed be grouped in memory
8806 // starting at an appropriately aligned address after super class object data.
8807 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8808 sizeof(mirror::HeapReference<mirror::Object>));
8809 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008810 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008811 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008812 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008813 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008814 reference_offsets |= (0xffffffffu << start_bit) &
8815 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008816 }
8817 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008818 }
8819 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008820 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008821}
8822
Vladimir Marko18090d12018-06-01 16:53:12 +01008823ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8824 ObjPtr<mirror::DexCache> dex_cache) {
8825 StackHandleScope<1> hs(Thread::Current());
8826 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8827 return DoResolveString(string_idx, h_dex_cache);
8828}
8829
8830ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8831 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008832 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008833 uint32_t utf16_length;
8834 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008835 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008836 if (string != nullptr) {
8837 dex_cache->SetResolvedString(string_idx, string);
8838 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008839 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008840}
8841
Vladimir Marko18090d12018-06-01 16:53:12 +01008842ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8843 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008844 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008845 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008846 uint32_t utf16_length;
8847 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008848 ObjPtr<mirror::String> string =
8849 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008850 if (string != nullptr) {
8851 dex_cache->SetResolvedString(string_idx, string);
8852 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008853 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008854}
8855
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008856ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008857 ObjPtr<mirror::Class> referrer) {
8858 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8859}
8860
8861ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008862 ObjPtr<mirror::DexCache> dex_cache,
8863 ObjPtr<mirror::ClassLoader> class_loader) {
8864 const DexFile& dex_file = *dex_cache->GetDexFile();
8865 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8866 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8867 ObjPtr<mirror::Class> type = nullptr;
8868 if (descriptor[1] == '\0') {
8869 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8870 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008871 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008872 } else {
8873 Thread* const self = Thread::Current();
8874 DCHECK(self != nullptr);
8875 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8876 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008877 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008878 }
8879 if (type != nullptr) {
8880 if (type->IsResolved()) {
8881 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008882 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008883 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008884 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008885 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008886 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008887}
8888
Andreas Gampeb0625e02019-05-01 12:43:31 -07008889template <typename RefType>
8890ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008891 StackHandleScope<2> hs(Thread::Current());
8892 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8893 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8894 return DoResolveType(type_idx, dex_cache, class_loader);
8895}
8896
Andreas Gampe4835d212018-11-21 14:55:10 -08008897// Instantiate the above.
8898template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8899 ArtField* referrer);
8900template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8901 ArtMethod* referrer);
8902template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8903 ObjPtr<mirror::Class> referrer);
8904
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008905ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008906 Handle<mirror::DexCache> dex_cache,
8907 Handle<mirror::ClassLoader> class_loader) {
8908 Thread* self = Thread::Current();
8909 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8910 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8911 if (resolved != nullptr) {
8912 // TODO: we used to throw here if resolved's class loader was not the
8913 // boot class loader. This was to permit different classes with the
8914 // same name to be loaded simultaneously by different loaders
8915 dex_cache->SetResolvedType(type_idx, resolved);
8916 } else {
8917 CHECK(self->IsExceptionPending())
8918 << "Expected pending exception for failed resolution of: " << descriptor;
8919 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8920 StackHandleScope<1> hs(self);
8921 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008922 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008923 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8924 self->ClearException();
8925 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8926 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008927 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008928 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008929 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008930 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008931 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008932}
8933
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008934ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8935 ObjPtr<mirror::DexCache> dex_cache,
8936 ObjPtr<mirror::ClassLoader> class_loader,
8937 uint32_t method_idx) {
8938 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8939 // functions can optimize the search if the dex_cache is the same as the DexCache
8940 // of the class, with fall-back to name and signature search otherwise.
8941 ArtMethod* resolved = nullptr;
8942 if (klass->IsInterface()) {
8943 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8944 } else {
8945 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8946 }
8947 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008948 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008949 hiddenapi::ShouldDenyAccessToMember(resolved,
8950 hiddenapi::AccessContext(class_loader, dex_cache),
8951 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008952 resolved = nullptr;
8953 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008954 if (resolved != nullptr) {
8955 // In case of jmvti, the dex file gets verified before being registered, so first
8956 // check if it's registered before checking class tables.
8957 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008958 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8959 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008960 << "DexFile referrer: " << dex_file.GetLocation()
8961 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8962 // Be a good citizen and update the dex cache to speed subsequent calls.
8963 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008964 // Disable the following invariant check as the verifier breaks it. b/73760543
8965 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8966 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8967 // << "Method: " << resolved->PrettyMethod() << ", "
8968 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8969 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008970 }
8971 return resolved;
8972}
8973
David Brazdil4525e0b2018-04-05 16:57:32 +01008974// Returns true if `method` is either null or hidden.
8975// Does not print any warnings if it is hidden.
8976static bool CheckNoSuchMethod(ArtMethod* method,
8977 ObjPtr<mirror::DexCache> dex_cache,
8978 ObjPtr<mirror::ClassLoader> class_loader)
8979 REQUIRES_SHARED(Locks::mutator_lock_) {
8980 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008981 hiddenapi::ShouldDenyAccessToMember(method,
8982 hiddenapi::AccessContext(class_loader, dex_cache),
8983 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008984}
8985
8986ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8987 ObjPtr<mirror::DexCache> dex_cache,
8988 ObjPtr<mirror::ClassLoader> class_loader,
8989 uint32_t method_idx) {
8990 if (klass->IsInterface()) {
8991 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8992 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8993 } else {
8994 // If there was an interface method with the same signature, we would have
8995 // found it in the "copied" methods. Only DCHECK that the interface method
8996 // really does not exist.
8997 if (kIsDebugBuild) {
8998 ArtMethod* method =
8999 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9000 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
9001 }
9002 return nullptr;
9003 }
9004}
9005
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009006template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00009007ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07009008 Handle<mirror::DexCache> dex_cache,
9009 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009010 ArtMethod* referrer,
9011 InvokeType type) {
Nicolas Geoffray605c5912020-04-08 15:12:39 +01009012 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Andreas Gampefa4333d2017-02-14 11:10:34 -08009013 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01009014 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07009015 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01009016 PointerSize pointer_size = image_pointer_size_;
9017 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009018 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009019 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
9020 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01009021 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
9022 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07009023 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009024 return resolved;
9025 }
Vladimir Marko89011192017-12-11 13:45:05 +00009026 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009027 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009028 ObjPtr<mirror::Class> klass = nullptr;
9029 if (valid_dex_cache_method) {
9030 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
9031 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009032 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009033 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009034 // We normaly should not end up here. However the verifier currently doesn't guarantee
9035 // the invariant of having the klass in the class table. b/73760543
9036 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Nicolas Geoffray07614192020-04-28 17:31:31 +01009037 if (klass == nullptr) {
9038 // This can only happen if the current thread is not allowed to load
9039 // classes.
9040 DCHECK(!Thread::Current()->CanLoadClasses());
9041 DCHECK(Thread::Current()->IsExceptionPending());
9042 return nullptr;
9043 }
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009044 }
Vladimir Markoba118822017-06-12 15:41:56 +01009045 } else {
9046 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009047 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01009048 if (klass == nullptr) {
9049 DCHECK(Thread::Current()->IsExceptionPending());
9050 return nullptr;
9051 }
9052 }
9053
9054 // Check if the invoke type matches the class type.
9055 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009056 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01009057 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07009058 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009059 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009060 }
Vladimir Markoba118822017-06-12 15:41:56 +01009061
9062 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009063 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009064 }
Vladimir Markoba118822017-06-12 15:41:56 +01009065
9066 // Note: We can check for IllegalAccessError only if we have a referrer.
9067 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
9068 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
9069 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9070 if (!referring_class->CheckResolvedMethodAccess(methods_class,
9071 resolved,
9072 dex_cache.Get(),
9073 method_idx,
9074 type)) {
9075 DCHECK(Thread::Current()->IsExceptionPending());
9076 return nullptr;
9077 }
9078 }
9079
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009080 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01009081 if (LIKELY(resolved != nullptr) &&
9082 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
9083 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07009084 return resolved;
9085 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009086 // If we had a method, or if we can find one with another lookup type,
9087 // it's an incompatible-class-change error.
9088 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01009089 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009090 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009091 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07009092 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009093 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009094 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009095 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
9096 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01009097 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07009098 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08009099 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009100 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07009101 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009102}
9103
Vladimir Marko89011192017-12-11 13:45:05 +00009104ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009105 Handle<mirror::DexCache> dex_cache,
9106 Handle<mirror::ClassLoader> class_loader) {
9107 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009108 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009109 if (resolved != nullptr) {
9110 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009111 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9112 return resolved;
9113 }
9114 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009115 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009116 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009117 if (klass == nullptr) {
9118 Thread::Current()->AssertPendingException();
9119 return nullptr;
9120 }
9121 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009122 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9123 } else {
9124 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009125 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009126 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009127 hiddenapi::ShouldDenyAccessToMember(
9128 resolved,
9129 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9130 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009131 resolved = nullptr;
9132 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009133 return resolved;
9134}
9135
Vladimir Markof44d36c2017-03-14 14:18:46 +00009136ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9137 ObjPtr<mirror::DexCache> dex_cache,
9138 ObjPtr<mirror::ClassLoader> class_loader,
9139 bool is_static) {
9140 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009141 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009142 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9143 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009144 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009145 }
9146 if (klass == nullptr) {
9147 // The class has not been resolved yet, so the field is also unresolved.
9148 return nullptr;
9149 }
9150 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009151
David Brazdil1ab0fa82018-05-04 11:28:03 +01009152 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009153}
9154
Vladimir Markoe11dd502017-12-08 14:09:45 +00009155ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009156 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009157 Handle<mirror::ClassLoader> class_loader,
9158 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009159 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayf3688822020-03-25 15:04:03 +00009160 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07009161 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009162 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009163 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009164 return resolved;
9165 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009166 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009167 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009168 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009169 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08009170 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07009171 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009172 }
9173
David Brazdil1ab0fa82018-05-04 11:28:03 +01009174 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07009175 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08009176 const char* name = dex_file.GetFieldName(field_id);
9177 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009178 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009179 }
Ian Rogersb067ac22011-12-13 18:05:09 -08009180 return resolved;
9181}
9182
Vladimir Markoe11dd502017-12-08 14:09:45 +00009183ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009184 Handle<mirror::DexCache> dex_cache,
9185 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009186 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009187 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009188 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009189 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009190 return resolved;
9191 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009192 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009193 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009194 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009195 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009196 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009197 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009198 }
9199
David Brazdil1ab0fa82018-05-04 11:28:03 +01009200 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9201 if (resolved == nullptr) {
9202 const char* name = dex_file.GetFieldName(field_id);
9203 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009204 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009205 }
9206 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009207}
9208
David Brazdil1ab0fa82018-05-04 11:28:03 +01009209ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9210 ObjPtr<mirror::DexCache> dex_cache,
9211 ObjPtr<mirror::ClassLoader> class_loader,
9212 uint32_t field_idx,
9213 bool is_static) {
9214 ArtField* resolved = nullptr;
9215 Thread* self = is_static ? Thread::Current() : nullptr;
9216 const DexFile& dex_file = *dex_cache->GetDexFile();
9217
9218 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
9219 : klass->FindInstanceField(dex_cache, field_idx);
9220
9221 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009222 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009223 const char* name = dex_file.GetFieldName(field_id);
9224 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9225 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
9226 : klass->FindInstanceField(name, type);
9227 }
9228
9229 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009230 hiddenapi::ShouldDenyAccessToMember(resolved,
9231 hiddenapi::AccessContext(class_loader, dex_cache),
9232 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009233 resolved = nullptr;
9234 }
9235
9236 if (resolved != nullptr) {
9237 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9238 }
9239
9240 return resolved;
9241}
9242
9243ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9244 ObjPtr<mirror::DexCache> dex_cache,
9245 ObjPtr<mirror::ClassLoader> class_loader,
9246 uint32_t field_idx) {
9247 ArtField* resolved = nullptr;
9248 Thread* self = Thread::Current();
9249 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009250 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009251
9252 const char* name = dex_file.GetFieldName(field_id);
9253 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9254 resolved = mirror::Class::FindField(self, klass, name, type);
9255
9256 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009257 hiddenapi::ShouldDenyAccessToMember(resolved,
9258 hiddenapi::AccessContext(class_loader, dex_cache),
9259 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009260 resolved = nullptr;
9261 }
9262
9263 if (resolved != nullptr) {
9264 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9265 }
9266
9267 return resolved;
9268}
9269
Vladimir Markoaf940202017-12-08 15:01:18 +00009270ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9271 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009272 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009273 Handle<mirror::DexCache> dex_cache,
9274 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009275 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009276 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009277
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009278 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009279 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009280 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009281 }
9282
Narayan Kamath25352fc2016-08-03 12:46:58 +01009283 StackHandleScope<4> hs(self);
9284
9285 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009286 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009287 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009288 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009289 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009290 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009291 DCHECK(self->IsExceptionPending());
9292 return nullptr;
9293 }
9294
9295 // Then resolve the argument types.
9296 //
9297 // TODO: Is there a better way to figure out the number of method arguments
9298 // other than by looking at the shorty ?
9299 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9300
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009301 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009302 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9303 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009304 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009305 DCHECK(self->IsExceptionPending());
9306 return nullptr;
9307 }
9308
9309 DexFileParameterIterator it(dex_file, proto_id);
9310 int32_t i = 0;
9311 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9312 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009313 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009314 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009315 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009316 DCHECK(self->IsExceptionPending());
9317 return nullptr;
9318 }
9319
9320 method_params->Set(i++, param_class.Get());
9321 }
9322
9323 DCHECK(!it.HasNext());
9324
9325 Handle<mirror::MethodType> type = hs.NewHandle(
9326 mirror::MethodType::Create(self, return_type, method_params));
9327 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9328
9329 return type.Get();
9330}
9331
Vladimir Markoaf940202017-12-08 15:01:18 +00009332ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009333 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009334 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009335 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009336 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9337 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009338 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009339}
9340
Vladimir Marko5aead702019-03-27 11:00:36 +00009341ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009342 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009343 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009344 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009345 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009346 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9347 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009348 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009349 bool is_static;
9350 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009351 switch (handle_type) {
9352 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009353 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009354 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009355 is_static = true;
9356 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009357 break;
9358 }
9359 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009360 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009361 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009362 is_static = true;
9363 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009364 break;
9365 }
9366 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009367 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009368 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009369 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009370 num_params = 2;
9371 break;
9372 }
9373 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009374 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009375 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009376 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009377 num_params = 1;
9378 break;
9379 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009380 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009381 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009382 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009383 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009384 case DexFile::MethodHandleType::kInvokeInterface:
9385 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009386 }
9387
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009388 ArtField* target_field =
9389 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9390 if (LIKELY(target_field != nullptr)) {
9391 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9392 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9393 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9394 ThrowIllegalAccessErrorField(referring_class, target_field);
9395 return nullptr;
9396 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009397 if (UNLIKELY(is_put && target_field->IsFinal())) {
9398 ThrowIllegalAccessErrorField(referring_class, target_field);
9399 return nullptr;
9400 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009401 } else {
9402 DCHECK(Thread::Current()->IsExceptionPending());
9403 return nullptr;
9404 }
9405
9406 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009407 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009408 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9409 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009410 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009411 DCHECK(self->IsExceptionPending());
9412 return nullptr;
9413 }
9414
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009415 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009416 Handle<mirror::Class> return_type;
9417 switch (handle_type) {
9418 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009419 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009420 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009421 break;
9422 }
9423 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009424 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009425 break;
9426 }
9427 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009428 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009429 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009430 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009431 break;
9432 }
9433 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009434 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009435 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009436 break;
9437 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009438 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009439 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009440 case DexFile::MethodHandleType::kInvokeConstructor:
9441 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009442 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009443 UNREACHABLE();
9444 }
9445
9446 for (int32_t i = 0; i < num_params; ++i) {
9447 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9448 DCHECK(self->IsExceptionPending());
9449 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009450 }
9451 }
9452
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009453 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009454 DCHECK(self->IsExceptionPending());
9455 return nullptr;
9456 }
9457
9458 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009459 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9460 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009461 DCHECK(self->IsExceptionPending());
9462 return nullptr;
9463 }
Orion Hodson631827d2017-04-10 14:53:47 +01009464
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009465 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9466 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9467}
9468
Vladimir Marko5aead702019-03-27 11:00:36 +00009469ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009470 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009471 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009472 ArtMethod* referrer) {
9473 DexFile::MethodHandleType handle_type =
9474 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9475 mirror::MethodHandle::Kind kind;
9476 uint32_t receiver_count = 0;
9477 ArtMethod* target_method = nullptr;
9478 switch (handle_type) {
9479 case DexFile::MethodHandleType::kStaticPut:
9480 case DexFile::MethodHandleType::kStaticGet:
9481 case DexFile::MethodHandleType::kInstancePut:
9482 case DexFile::MethodHandleType::kInstanceGet:
9483 UNREACHABLE();
9484 case DexFile::MethodHandleType::kInvokeStatic: {
9485 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9486 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009487 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9488 method_handle.field_or_method_idx_,
9489 referrer,
9490 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009491 break;
9492 }
9493 case DexFile::MethodHandleType::kInvokeInstance: {
9494 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9495 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009496 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9497 method_handle.field_or_method_idx_,
9498 referrer,
9499 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009500 break;
9501 }
9502 case DexFile::MethodHandleType::kInvokeConstructor: {
9503 // Constructors are currently implemented as a transform. They
9504 // are special cased later in this method.
9505 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9506 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009507 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9508 method_handle.field_or_method_idx_,
9509 referrer,
9510 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009511 break;
9512 }
9513 case DexFile::MethodHandleType::kInvokeDirect: {
9514 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9515 receiver_count = 1;
9516 StackHandleScope<2> hs(self);
9517 // A constant method handle with type kInvokeDirect can refer to
9518 // a method that is private or to a method in a super class. To
9519 // disambiguate the two options, we resolve the method ignoring
9520 // the invocation type to determine if the method is private. We
9521 // then resolve again specifying the intended invocation type to
9522 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009523 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009524 hs.NewHandle(referrer->GetDexCache()),
9525 hs.NewHandle(referrer->GetClassLoader()));
9526 if (UNLIKELY(target_method == nullptr)) {
9527 break;
9528 }
9529
9530 if (target_method->IsPrivate()) {
9531 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009532 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9533 method_handle.field_or_method_idx_,
9534 referrer,
9535 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009536 } else {
9537 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009538 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9539 method_handle.field_or_method_idx_,
9540 referrer,
9541 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009542 if (UNLIKELY(target_method == nullptr)) {
9543 break;
9544 }
9545 // Find the method specified in the parent in referring class
9546 // so invoke-super invokes the method in the parent of the
9547 // referrer.
9548 target_method =
9549 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9550 kRuntimePointerSize);
9551 }
9552 break;
9553 }
9554 case DexFile::MethodHandleType::kInvokeInterface: {
9555 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9556 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009557 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9558 method_handle.field_or_method_idx_,
9559 referrer,
9560 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009561 break;
9562 }
Orion Hodson631827d2017-04-10 14:53:47 +01009563 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009564
9565 if (UNLIKELY(target_method == nullptr)) {
9566 DCHECK(Thread::Current()->IsExceptionPending());
9567 return nullptr;
9568 }
9569
9570 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9571 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9572 uint32_t access_flags = target_method->GetAccessFlags();
9573 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9574 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9575 return nullptr;
9576 }
9577
9578 // Calculate the number of parameters from the method shorty. We add the
9579 // receiver count (0 or 1) and deduct one for the return value.
9580 uint32_t shorty_length;
9581 target_method->GetShorty(&shorty_length);
9582 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9583
Orion Hodsonecd58562018-09-24 11:27:33 +01009584 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009585 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009586 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9587 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9588 if (method_params.Get() == nullptr) {
9589 DCHECK(self->IsExceptionPending());
9590 return nullptr;
9591 }
9592
Orion Hodsonecd58562018-09-24 11:27:33 +01009593 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009594 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009595 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009596 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009597 // Insert receiver. Use the class identified in the method handle rather than the declaring
9598 // class of the resolved method which may be super class or default interface method
9599 // (b/115964401).
9600 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9601 // receiver_class should have been resolved when resolving the target method.
9602 DCHECK(receiver_class != nullptr);
9603 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009604 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009605
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009606 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009607 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009608 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009609 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009610 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009611 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009612 if (nullptr == klass) {
9613 DCHECK(self->IsExceptionPending());
9614 return nullptr;
9615 }
9616 method_params->Set(index++, klass);
9617 it.Next();
9618 }
9619
Orion Hodsonecd58562018-09-24 11:27:33 +01009620 Handle<mirror::Class> return_type =
9621 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009622 if (UNLIKELY(return_type.IsNull())) {
9623 DCHECK(self->IsExceptionPending());
9624 return nullptr;
9625 }
9626
9627 Handle<mirror::MethodType>
9628 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9629 if (UNLIKELY(method_type.IsNull())) {
9630 DCHECK(self->IsExceptionPending());
9631 return nullptr;
9632 }
9633
9634 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9635 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9636 Handle<mirror::MethodHandlesLookup> lookup =
9637 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9638 return lookup->FindConstructor(self, constructor_class, method_type);
9639 }
9640
9641 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9642 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9643}
9644
Vladimir Markoaf940202017-12-08 15:01:18 +00009645ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9646 uint32_t method_handle_idx,
9647 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009648 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009649 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009650 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009651 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9652 case DexFile::MethodHandleType::kStaticPut:
9653 case DexFile::MethodHandleType::kStaticGet:
9654 case DexFile::MethodHandleType::kInstancePut:
9655 case DexFile::MethodHandleType::kInstanceGet:
9656 return ResolveMethodHandleForField(self, method_handle, referrer);
9657 case DexFile::MethodHandleType::kInvokeStatic:
9658 case DexFile::MethodHandleType::kInvokeInstance:
9659 case DexFile::MethodHandleType::kInvokeConstructor:
9660 case DexFile::MethodHandleType::kInvokeDirect:
9661 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009662 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009663 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009664}
9665
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009666bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9667 return (entry_point == GetQuickResolutionStub()) ||
9668 (quick_resolution_trampoline_ == entry_point);
9669}
9670
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009671bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9672 return (entry_point == GetQuickToInterpreterBridge()) ||
9673 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9674}
9675
9676bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9677 return (entry_point == GetQuickGenericJniStub()) ||
9678 (quick_generic_jni_trampoline_ == entry_point);
9679}
9680
David Sehra49e0532017-08-25 08:05:29 -07009681bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009682 return entry_point == GetJniDlsymLookupStub() ||
9683 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009684}
9685
Vladimir Markofa458ac2020-02-12 14:08:07 +00009686bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9687 return entry_point == GetJniDlsymLookupCriticalStub() ||
9688 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9689}
9690
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009691const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9692 return GetQuickGenericJniStub();
9693}
9694
Mathieu Chartiere401d142015-04-22 13:56:20 -07009695void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009696 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009697 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9698 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009699 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009700 }
9701}
9702
Alex Lightdb01a092017-04-03 15:39:55 -07009703void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9704 DCHECK(method->IsObsolete());
9705 // We cannot mess with the entrypoints of native methods because they are used to determine how
9706 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9707 if (!method->IsNative()) {
9708 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9709 }
9710}
9711
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009712void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009713 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009714 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009715 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9716 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009717 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9718 os << "Dumping registered class loaders\n";
9719 size_t class_loader_index = 0;
9720 for (const ClassLoaderData& class_loader : class_loaders_) {
9721 ObjPtr<mirror::ClassLoader> loader =
9722 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9723 if (loader != nullptr) {
9724 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9725 bool saw_one_dex_file = false;
9726 for (const DexCacheData& dex_cache : dex_caches_) {
9727 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9728 if (saw_one_dex_file) {
9729 os << ":";
9730 }
9731 saw_one_dex_file = true;
9732 os << dex_cache.dex_file->GetLocation();
9733 }
9734 }
9735 os << "]";
9736 bool found_parent = false;
9737 if (loader->GetParent() != nullptr) {
9738 size_t parent_index = 0;
9739 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9740 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9741 soa.Self()->DecodeJObject(class_loader2.weak_root));
9742 if (loader2 == loader->GetParent()) {
9743 os << ", parent #" << parent_index;
9744 found_parent = true;
9745 break;
9746 }
9747 parent_index++;
9748 }
9749 if (!found_parent) {
9750 os << ", unregistered parent of type "
9751 << loader->GetParent()->GetClass()->PrettyDescriptor();
9752 }
9753 } else {
9754 os << ", no parent";
9755 }
9756 os << "\n";
9757 }
9758 }
9759 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009760 Runtime* runtime = Runtime::Current();
9761 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9762 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009763}
9764
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009765class CountClassesVisitor : public ClassLoaderVisitor {
9766 public:
9767 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9768
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009769 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009770 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009771 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009772 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009773 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9774 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009775 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009776 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009777
9778 size_t num_zygote_classes;
9779 size_t num_non_zygote_classes;
9780};
9781
9782size_t ClassLinker::NumZygoteClasses() const {
9783 CountClassesVisitor visitor;
9784 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009785 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009786}
9787
9788size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009789 CountClassesVisitor visitor;
9790 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009791 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009792}
9793
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009794size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009795 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009796 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009797 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009798}
9799
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009800pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009801 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009802}
9803
9804pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009805 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009806}
9807
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009808void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009809 DCHECK(!init_done_);
9810
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009811 DCHECK(klass != nullptr);
9812 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009813
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009814 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009815 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009816 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9817 int32_t index = static_cast<int32_t>(class_root);
9818 DCHECK(class_roots->Get(index) == nullptr);
9819 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009820}
9821
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009822ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9823 Thread* self,
9824 const std::vector<const DexFile*>& dex_files,
9825 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009826 Handle<mirror::ClassLoader> parent_loader,
9827 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009828
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009829 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009830
Mathieu Chartierc7853442015-03-27 14:35:38 -07009831 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009832 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009833
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009834 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009835 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009836 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009837 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009838 mirror::ObjectArray<mirror::Object>::Alloc(self,
9839 dex_elements_class.Get(),
9840 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009841 Handle<mirror::Class> h_dex_element_class =
9842 hs.NewHandle(dex_elements_class->GetComponentType());
9843
Mathieu Chartierc7853442015-03-27 14:35:38 -07009844 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009845 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009846 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009847
Andreas Gampe08883de2016-11-08 13:20:52 -08009848 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009849 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009850
Andreas Gampe08883de2016-11-08 13:20:52 -08009851 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009852 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009853
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009854 // Fill the elements array.
9855 int32_t index = 0;
9856 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009857 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009858
Calin Juravle7865ac72017-06-28 11:03:12 -07009859 // CreateWellKnownClassLoader is only used by gtests and compiler.
9860 // 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 -07009861 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9862 self,
9863 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009864 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009865 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009866
Mathieu Chartier3738e982017-05-12 16:07:28 -07009867 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9868 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009869 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009870 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009871 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009872 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009873
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009874 Handle<mirror::String> h_file_name = hs2.NewHandle(
9875 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009876 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009877 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9878
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009879 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009880 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009881 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009882
9883 h_dex_elements->Set(index, h_element.Get());
9884 index++;
9885 }
9886 DCHECK_EQ(index, h_dex_elements->GetLength());
9887
9888 // Create DexPathList.
9889 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009890 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009891 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009892 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009893 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009894 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9895 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9896 // elements.
9897 {
9898 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9899 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9900 DCHECK(native_lib_dirs != nullptr);
9901 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9902 DCHECK(list_class != nullptr);
9903 {
9904 StackHandleScope<1> h_list_scope(self);
9905 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9906 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9907 DCHECK(list_init);
9908 list_class = h_list_class.Get();
9909 }
9910 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9911 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9912 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9913 // normally never null), as long as one does not try to add elements, this will still
9914 // work.
9915 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9916 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009917
Calin Juravle7865ac72017-06-28 11:03:12 -07009918 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009919 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9920 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009921 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009922 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009923 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009924 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009925 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009926 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009927
9928 // Make a pretend boot-classpath.
9929 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009930 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009931 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009932 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009933 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009934 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009935 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009936 if (parent_loader.Get() == nullptr) {
9937 ScopedObjectAccessUnchecked soa(self);
9938 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9939 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9940 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9941 } else {
9942 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9943 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009944
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009945 ArtField* shared_libraries_field =
9946 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9947 DCHECK(shared_libraries_field != nullptr);
9948 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9949
9950 return h_class_loader.Get();
9951}
9952
9953jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9954 const std::vector<const DexFile*>& dex_files,
9955 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009956 jobject parent_loader,
9957 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009958 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9959 WellKnownClasses::dalvik_system_PathClassLoader) ||
9960 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009961 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9962 self->GetJniEnv()->IsSameObject(loader_class,
9963 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009964
9965 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9966 // We could move the jobject to the callers, but all call-sites do this...
9967 ScopedObjectAccessUnchecked soa(self);
9968
9969 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009970 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009971
9972 Handle<mirror::Class> h_loader_class =
9973 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009974 Handle<mirror::ClassLoader> h_parent =
9975 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9976 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9977 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009978
9979 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9980 self,
9981 dex_files,
9982 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009983 h_parent,
9984 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009985
9986 // Make it a global ref and return.
9987 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009988 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009989 return soa.Env()->NewGlobalRef(local_ref.get());
9990}
9991
Calin Juravle7865ac72017-06-28 11:03:12 -07009992jobject ClassLinker::CreatePathClassLoader(Thread* self,
9993 const std::vector<const DexFile*>& dex_files) {
9994 return CreateWellKnownClassLoader(self,
9995 dex_files,
9996 WellKnownClasses::dalvik_system_PathClassLoader,
9997 nullptr);
9998}
9999
Andreas Gampe8ac75952015-06-02 21:01:45 -070010000void ClassLinker::DropFindArrayClassCache() {
10001 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
10002 find_array_class_cache_next_victim_ = 0;
10003}
10004
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010005void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010006 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010007 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -070010008 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010009 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
10010 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010011 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +010010012 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010013 }
10014 }
10015}
10016
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010017void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10018 for (const ClassLoaderData& data : class_loaders_) {
10019 LinearAlloc* alloc = data.allocator;
10020 if (alloc != nullptr && !visitor->Visit(alloc)) {
10021 break;
10022 }
10023 }
10024}
10025
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010026void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10027 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010028 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010029 Thread* const self = Thread::Current();
10030 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010031 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010032 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010033 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010034 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10035 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010036 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010037 }
10038}
10039
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010040void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010041 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010042 std::vector<ClassLoaderData> to_delete;
10043 // Do the delete outside the lock to avoid lock violation in jit code cache.
10044 {
10045 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10046 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10047 const ClassLoaderData& data = *it;
10048 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010049 ObjPtr<mirror::ClassLoader> class_loader =
10050 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010051 if (class_loader != nullptr) {
10052 ++it;
10053 } else {
10054 VLOG(class_linker) << "Freeing class loader";
10055 to_delete.push_back(data);
10056 it = class_loaders_.erase(it);
10057 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010058 }
10059 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010060 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010061 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010062 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010063 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010064}
10065
Mathieu Chartier65975772016-08-05 10:46:36 -070010066class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10067 public:
10068 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10069 : method_(method),
10070 pointer_size_(pointer_size) {}
10071
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010072 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010073 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10074 holder_ = klass;
10075 }
10076 // Return false to stop searching if holder_ is not null.
10077 return holder_ == nullptr;
10078 }
10079
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010080 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010081 const ArtMethod* const method_;
10082 const PointerSize pointer_size_;
10083};
10084
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010085ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010086 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10087 CHECK(method->IsCopied());
10088 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10089 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010090 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010091}
10092
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010093ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
10094 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010095 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +010010096 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010097 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010098}
10099
Vladimir Markod1f73512020-04-02 10:50:35 +010010100bool ClassLinker::IsUpdatableBootClassPathDescriptor(const char* descriptor ATTRIBUTE_UNUSED) {
10101 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10102 LOG(FATAL) << "UNREACHABLE";
10103 UNREACHABLE();
10104}
10105
Calin Juravle33787682019-07-26 14:27:18 -070010106bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10107 REQUIRES_SHARED(Locks::mutator_lock_) {
10108 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10109 LOG(FATAL) << "UNREACHABLE";
10110 UNREACHABLE();
10111}
10112
10113bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10114 REQUIRES_SHARED(Locks::mutator_lock_) {
10115 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10116 LOG(FATAL) << "UNREACHABLE";
10117 UNREACHABLE();
10118}
10119
10120bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10121 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10122 LOG(FATAL) << "UNREACHABLE";
10123 UNREACHABLE();
10124}
10125
Calin Juravle2c2724c2021-01-14 19:54:23 -080010126void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10127 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10128 LOG(FATAL) << "UNREACHABLE";
10129 UNREACHABLE();
10130}
10131
Roland Levillain0e840272018-08-23 19:55:30 +010010132// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +010010133template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010134 uint32_t method_idx,
10135 Handle<mirror::DexCache> dex_cache,
10136 Handle<mirror::ClassLoader> class_loader,
10137 ArtMethod* referrer,
10138 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +010010139template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010140 uint32_t method_idx,
10141 Handle<mirror::DexCache> dex_cache,
10142 Handle<mirror::ClassLoader> class_loader,
10143 ArtMethod* referrer,
10144 InvokeType type);
10145
Roland Levillain0e840272018-08-23 19:55:30 +010010146// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010147template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010148 Thread* self,
10149 ObjPtr<mirror::Class> java_lang_Class,
10150 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010151template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010152 Thread* self,
10153 ObjPtr<mirror::Class> java_lang_Class,
10154 uint32_t class_size);
10155
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010156} // namespace art